[
  {
    "path": ".dockerignore",
    "content": "# IDE\n.vscode/\n.idea/\n\n.DS_Store\n\n/bin\n/cmake*/\n"
  },
  {
    "path": ".editorconfig",
    "content": "# EditorConfig is awesome: https://EditorConfig.org\n\nroot = true\n\n[*]\ncharset = utf-8\nend_of_line = lf\ntrim_trailing_whitespace = true\ninsert_final_newline = true\nindent_style = space\nindent_size = 4\n"
  },
  {
    "path": ".gitignore",
    "content": ".vs/\n.idea/\n.vscode/\n\n/cmake-build*\n\n# Prerequisites\n*.d\n\n# Compiled Object files\n*.slo\n*.lo\n*.o\n*.obj\n\n# Precompiled Headers\n*.gch\n*.pch\n\n# Compiled Dynamic libraries\n*.so\n*.dylib\n*.dll\n\n# Fortran module files\n*.mod\n*.smod\n\n# Compiled Static libraries\n*.lai\n*.la\n*.a\n*.lib\n\n# Executables\n*.exe\n*.out\n*.app\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/.clang-format",
    "content": "---\nLanguage:        Cpp\nBasedOnStyle:  Google\nPointerAlignment: Left\n...\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/.clang-tidy",
    "content": "---\nChecks:          'clang-analyzer-*,readability-redundant-*,performance-*'\nWarningsAsErrors: 'clang-analyzer-*,readability-redundant-*,performance-*'\nHeaderFilterRegex: '.*'\nAnalyzeTemporaryDtors: false\nFormatStyle:     none\nUser:            user\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/.github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: \"[BUG]\"\nlabels: ''\nassignees: ''\n\n---\n\n**Describe the bug**\nA clear and concise description of what the bug is.\n\n**System**\nWhich OS, compiler, and compiler version are you using:\n  - OS: \n  - Compiler and version: \n\n**To reproduce**\nSteps to reproduce the behavior:\n1. sync to commit ...\n2. cmake/bazel...\n3. make ...\n4. See error\n\n**Expected behavior**\nA clear and concise description of what you expected to happen.\n\n**Screenshots**\nIf applicable, add screenshots to help explain your problem.\n\n**Additional context**\nAdd any other context about the problem here.\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/.github/ISSUE_TEMPLATE/feature_request.md",
    "content": "---\nname: Feature request\nabout: Suggest an idea for this project\ntitle: \"[FR]\"\nlabels: ''\nassignees: ''\n\n---\n\n**Is your feature request related to a problem? Please describe.**\nA clear and concise description of what the problem is. Ex. I'm always frustrated when [...]\n\n**Describe the solution you'd like**\nA clear and concise description of what you want to happen.\n\n**Describe alternatives you've considered**\nA clear and concise description of any alternative solutions or features you've considered.\n\n**Additional context**\nAdd any other context or screenshots about the feature request here.\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/.github/install_bazel.sh",
    "content": "if ! bazel version; then\n  arch=$(uname -m)\n  if [ \"$arch\" == \"aarch64\" ]; then\n    arch=\"arm64\"\n  fi\n  echo \"Installing wget and downloading $arch Bazel binary from GitHub releases.\"\n  yum install -y wget\n  wget \"https://github.com/bazelbuild/bazel/releases/download/6.0.0/bazel-6.0.0-linux-$arch\" -O /usr/local/bin/bazel\n  chmod +x /usr/local/bin/bazel\nelse\n  # bazel is installed for the correct architecture\n  exit 0\nfi\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/.github/libcxx-setup.sh",
    "content": "#!/usr/bin/env bash\n\nset -e\n\n# Checkout LLVM sources\ngit clone --depth=1 https://github.com/llvm/llvm-project.git llvm-project\n\n## Setup libc++ options\nif [ -z \"$BUILD_32_BITS\" ]; then\n  export BUILD_32_BITS=OFF && echo disabling 32 bit build\nfi\n\n## Build and install libc++ (Use unstable ABI for better sanitizer coverage)\nmkdir llvm-build && cd llvm-build\ncmake -DCMAKE_C_COMPILER=${CC}                  \\\n      -DCMAKE_CXX_COMPILER=${CXX}               \\\n      -DCMAKE_BUILD_TYPE=RelWithDebInfo         \\\n      -DCMAKE_INSTALL_PREFIX=/usr               \\\n      -DLIBCXX_ABI_UNSTABLE=OFF                 \\\n      -DLLVM_USE_SANITIZER=${LIBCXX_SANITIZER}  \\\n      -DLLVM_BUILD_32_BITS=${BUILD_32_BITS}     \\\n      -DLLVM_ENABLE_RUNTIMES='libcxx;libcxxabi;libunwind' \\\n      -G \"Unix Makefiles\" \\\n      ../llvm-project/runtimes/\nmake -j cxx cxxabi unwind\ncd ..\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/.github/workflows/bazel.yml",
    "content": "name: bazel\n\non:\n  push: {}\n  pull_request: {}\n\njobs:\n  build_and_test_default:\n    name: bazel.${{ matrix.os }}.${{ matrix.bzlmod && 'bzlmod' || 'no_bzlmod' }}\n    runs-on: ${{ matrix.os }}\n    strategy:\n      fail-fast: false\n      matrix:\n        os: [ubuntu-latest, macos-latest, windows-2022]\n        bzlmod: [false, true]\n    steps:\n    - uses: actions/checkout@v3\n\n    - name: mount bazel cache\n      uses: actions/cache@v3\n      env:\n        cache-name: bazel-cache\n      with:\n        path: \"~/.cache/bazel\"\n        key: ${{ env.cache-name }}-${{ matrix.os }}-${{ github.ref }}\n        restore-keys: |\n          ${{ env.cache-name }}-${{ matrix.os }}-main\n\n    - name: build\n      run: |\n        bazel build ${{ matrix.bzlmod && '--enable_bzlmod' || '--noenable_bzlmod' }} //:benchmark //:benchmark_main //test/...\n\n    - name: test\n      run: |\n        bazel test ${{ matrix.bzlmod && '--enable_bzlmod' || '--noenable_bzlmod' }} --test_output=all //test/...\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/.github/workflows/build-and-test-min-cmake.yml",
    "content": "name: build-and-test-min-cmake\n\non:\n  push:\n    branches: [ main ]\n  pull_request:\n    branches: [ main ]\n\njobs:\n  job:\n    name: ${{ matrix.os }}.min-cmake\n    runs-on: ${{ matrix.os }}\n    strategy:\n      fail-fast: false\n      matrix:\n        os: [ubuntu-latest, macos-latest]\n\n    steps:\n      - uses: actions/checkout@v3\n\n      - uses: lukka/get-cmake@latest\n        with:\n          cmakeVersion: 3.10.0\n\n      - name: create build environment\n        run: cmake -E make_directory ${{ runner.workspace }}/_build\n\n      - name: setup cmake initial cache\n        run: touch compiler-cache.cmake\n\n      - name: configure cmake\n        env:\n          CXX: ${{ matrix.compiler }}\n        shell: bash\n        working-directory: ${{ runner.workspace }}/_build\n        run: >\n          cmake -C ${{ github.workspace }}/compiler-cache.cmake\n          $GITHUB_WORKSPACE\n          -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON\n          -DCMAKE_CXX_VISIBILITY_PRESET=hidden\n          -DCMAKE_VISIBILITY_INLINES_HIDDEN=ON\n\n      - name: build\n        shell: bash\n        working-directory: ${{ runner.workspace }}/_build\n        run: cmake --build .\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/.github/workflows/build-and-test-perfcounters.yml",
    "content": "name: build-and-test-perfcounters\n\non:\n  push:\n    branches: [ main ]\n  pull_request:\n    branches: [ main ]\n\njobs:\n  job:\n    # TODO(dominic): Extend this to include compiler and set through env: CC/CXX.\n    name: ${{ matrix.os }}.${{ matrix.build_type }}\n    runs-on: ${{ matrix.os }}\n    strategy:\n      fail-fast: false\n      matrix:\n        os: [ubuntu-22.04, ubuntu-20.04]\n        build_type: ['Release', 'Debug']\n    steps:\n    - uses: actions/checkout@v3\n\n    - name: install libpfm\n      run: |\n        sudo apt update\n        sudo apt -y install libpfm4-dev\n\n    - name: create build environment\n      run: cmake -E make_directory ${{ runner.workspace }}/_build\n\n    - name: configure cmake\n      shell: bash\n      working-directory: ${{ runner.workspace }}/_build\n      run: >\n        cmake $GITHUB_WORKSPACE\n        -DBENCHMARK_ENABLE_LIBPFM=1\n        -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON\n        -DCMAKE_BUILD_TYPE=${{ matrix.build_type }}\n\n    - name: build\n      shell: bash\n      working-directory: ${{ runner.workspace }}/_build\n      run: cmake --build . --config ${{ matrix.build_type }}\n\n    # Skip testing, for now. It seems perf_event_open does not succeed on the\n    # hosting machine, very likely a permissions issue.\n    # TODO(mtrofin): Enable test.\n    # - name: test\n    #   shell: bash\n    #   working-directory: ${{ runner.workspace }}/_build\n    #   run: ctest -C ${{ matrix.build_type }} --rerun-failed --output-on-failure\n\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/.github/workflows/build-and-test.yml",
    "content": "name: build-and-test\n\non:\n  push:\n    branches: [ main ]\n  pull_request:\n    branches: [ main ]\n\njobs:\n  # TODO: add 32-bit builds (g++ and clang++) for ubuntu\n  #   (requires g++-multilib and libc6:i386)\n  # TODO: add coverage build (requires lcov)\n  # TODO: add clang + libc++ builds for ubuntu\n  job:\n    name: ${{ matrix.os }}.${{ matrix.build_type }}.${{ matrix.lib }}.${{ matrix.compiler }}\n    runs-on: ${{ matrix.os }}\n    strategy:\n      fail-fast: false\n      matrix:\n        os: [ubuntu-22.04, ubuntu-20.04, macos-latest]\n        build_type: ['Release', 'Debug']\n        compiler: ['g++', 'clang++']\n        lib: ['shared', 'static']\n\n    steps:\n      - uses: actions/checkout@v3\n\n      - uses: lukka/get-cmake@latest\n\n      - name: create build environment\n        run: cmake -E make_directory ${{ runner.workspace }}/_build\n\n      - name: setup cmake initial cache\n        run: touch compiler-cache.cmake\n\n      - name: configure cmake\n        env:\n          CXX: ${{ matrix.compiler }}\n        shell: bash\n        working-directory: ${{ runner.workspace }}/_build\n        run: >\n          cmake -C ${{ github.workspace }}/compiler-cache.cmake\n          $GITHUB_WORKSPACE\n          -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON\n          -DBUILD_SHARED_LIBS=${{ matrix.lib == 'shared' }}\n          -DCMAKE_BUILD_TYPE=${{ matrix.build_type }}\n          -DCMAKE_CXX_COMPILER=${{ env.CXX }}\n          -DCMAKE_CXX_VISIBILITY_PRESET=hidden\n          -DCMAKE_VISIBILITY_INLINES_HIDDEN=ON\n\n      - name: build\n        shell: bash\n        working-directory: ${{ runner.workspace }}/_build\n        run: cmake --build . --config ${{ matrix.build_type }}\n\n      - name: test\n        shell: bash\n        working-directory: ${{ runner.workspace }}/_build\n        run: ctest -C ${{ matrix.build_type }} -VV\n\n  msvc:\n    name: ${{ matrix.os }}.${{ matrix.build_type }}.${{ matrix.lib }}.${{ matrix.msvc }}\n    runs-on: ${{ matrix.os }}\n    defaults:\n        run:\n            shell: powershell\n    strategy:\n      fail-fast: false\n      matrix:\n        msvc:\n          - VS-16-2019\n          - VS-17-2022\n        arch:\n          - x64\n        build_type:\n          - Debug\n          - Release\n        lib:\n          - shared\n          - static\n        include:\n          - msvc: VS-16-2019\n            os: windows-2019\n            generator: 'Visual Studio 16 2019'\n          - msvc: VS-17-2022\n            os: windows-2022\n            generator: 'Visual Studio 17 2022'\n\n    steps:\n      - uses: actions/checkout@v2\n\n      - uses: lukka/get-cmake@latest\n\n      - name: configure cmake\n        run: >\n          cmake -S . -B _build/\n          -A ${{ matrix.arch }}\n          -G \"${{ matrix.generator }}\"\n          -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON\n          -DBUILD_SHARED_LIBS=${{ matrix.lib == 'shared' }}\n\n      - name: build\n        run: cmake --build _build/ --config ${{ matrix.build_type }}\n\n      - name: setup test environment\n        # Make sure gmock and benchmark DLLs can be found\n        run: >\n            echo \"$((Get-Item .).FullName)/_build/bin/${{ matrix.build_type }}\" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append;\n            echo \"$((Get-Item .).FullName)/_build/src/${{ matrix.build_type }}\" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append;\n\n      - name: test\n        run: ctest --test-dir _build/ -C ${{ matrix.build_type }} -VV\n\n\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/.github/workflows/clang-format-lint.yml",
    "content": "name: clang-format-lint\non:\n  push: {}\n  pull_request: {}\n\njobs:\n  build:\n    runs-on: ubuntu-latest\n\n    steps:\n    - uses: actions/checkout@v3\n    - uses: DoozyX/clang-format-lint-action@v0.13\n      with:\n        source: './include/benchmark ./src ./test'\n        extensions: 'h,cc'\n        clangFormatVersion: 12\n        style: Google\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/.github/workflows/clang-tidy.yml",
    "content": "name: clang-tidy\n\non:\n  push: {}\n  pull_request: {}\n\njobs:\n  job:\n    name: run-clang-tidy\n    runs-on: ubuntu-latest\n    strategy:\n      fail-fast: false\n    steps:\n    - uses: actions/checkout@v3\n\n    - name: install clang-tidy\n      run: sudo apt update && sudo apt -y install clang-tidy\n\n    - name: create build environment\n      run: cmake -E make_directory ${{ runner.workspace }}/_build\n\n    - name: configure cmake\n      shell: bash\n      working-directory: ${{ runner.workspace }}/_build\n      run: >\n        cmake $GITHUB_WORKSPACE\n        -DBENCHMARK_ENABLE_ASSEMBLY_TESTS=OFF\n        -DBENCHMARK_ENABLE_LIBPFM=OFF\n        -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON\n        -DCMAKE_C_COMPILER=clang\n        -DCMAKE_CXX_COMPILER=clang++\n        -DCMAKE_EXPORT_COMPILE_COMMANDS=ON\n        -DGTEST_COMPILE_COMMANDS=OFF\n\n    - name: run\n      shell: bash\n      working-directory: ${{ runner.workspace }}/_build\n      run: run-clang-tidy\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/.github/workflows/doxygen.yml",
    "content": "name: doxygen\n\non:\n  push:\n    branches: [main]\n  pull_request:\n    branches: [main]\n\njobs:\n  build-and-deploy:\n    name: Build HTML documentation\n    runs-on: ubuntu-latest\n    steps:\n    - name: Fetching sources\n      uses: actions/checkout@v3\n\n    - name: Installing build dependencies\n      run: |\n        sudo apt update\n        sudo apt install doxygen gcc git\n\n    - name: Creating build directory\n      run: mkdir build\n\n    - name: Building HTML documentation with Doxygen\n      run: |\n        cmake -S . -B build -DBENCHMARK_ENABLE_TESTING:BOOL=OFF -DBENCHMARK_ENABLE_DOXYGEN:BOOL=ON -DBENCHMARK_INSTALL_DOCS:BOOL=ON\n        cmake --build build --target benchmark_doxygen\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/.github/workflows/pylint.yml",
    "content": "name: pylint\n\non:\n  push:\n    branches: [ main ]\n  pull_request:\n    branches: [ main ]\n\njobs:\n  pylint:\n\n    runs-on: ubuntu-latest\n\n    steps:\n    - uses: actions/checkout@v3\n    - name: Set up Python 3.8\n      uses: actions/setup-python@v1\n      with:\n        python-version: 3.8\n\n    - name: Install dependencies\n      run: |\n        python -m pip install --upgrade pip\n        pip install pylint pylint-exit conan\n\n    - name: Run pylint\n      run: |\n        pylint `find . -name '*.py'|xargs` || pylint-exit $?\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/.github/workflows/sanitizer.yml",
    "content": "name: sanitizer\n\non:\n  push: {}\n  pull_request: {}\n\nenv:\n  UBSAN_OPTIONS: \"print_stacktrace=1\"\n\njobs:\n  job:\n    name: ${{ matrix.sanitizer }}.${{ matrix.build_type }}\n    runs-on: ubuntu-latest\n    strategy:\n      fail-fast: false\n      matrix:\n        build_type: ['Debug', 'RelWithDebInfo']\n        sanitizer: ['asan', 'ubsan', 'tsan', 'msan']\n\n    steps:\n    - uses: actions/checkout@v3\n\n    - name: configure msan env\n      if: matrix.sanitizer == 'msan'\n      run: |\n        echo \"EXTRA_FLAGS=-g -O2 -fno-omit-frame-pointer -fsanitize=memory -fsanitize-memory-track-origins\" >> $GITHUB_ENV\n        echo \"LIBCXX_SANITIZER=MemoryWithOrigins\" >> $GITHUB_ENV\n\n    - name: configure ubsan env\n      if: matrix.sanitizer == 'ubsan'\n      run: |\n        echo \"EXTRA_FLAGS=-g -O2 -fno-omit-frame-pointer -fsanitize=undefined -fno-sanitize-recover=all\" >> $GITHUB_ENV\n        echo \"LIBCXX_SANITIZER=Undefined\" >> $GITHUB_ENV\n\n    - name: configure asan env\n      if: matrix.sanitizer == 'asan'\n      run: |\n        echo \"EXTRA_FLAGS=-g -O2 -fno-omit-frame-pointer -fsanitize=address -fno-sanitize-recover=all\" >> $GITHUB_ENV\n        echo \"LIBCXX_SANITIZER=Address\" >> $GITHUB_ENV\n\n    - name: configure tsan env\n      if: matrix.sanitizer == 'tsan'\n      run: |\n        echo \"EXTRA_FLAGS=-g -O2 -fno-omit-frame-pointer -fsanitize=thread -fno-sanitize-recover=all\" >> $GITHUB_ENV\n        echo \"LIBCXX_SANITIZER=Thread\" >> $GITHUB_ENV\n\n    - name: fine-tune asan options\n      # in asan we get an error from std::regex. ignore it.\n      if: matrix.sanitizer == 'asan'\n      run: |\n        echo \"ASAN_OPTIONS=alloc_dealloc_mismatch=0\" >> $GITHUB_ENV\n\n    - name: setup clang\n      uses: egor-tensin/setup-clang@v1\n      with:\n        version: latest\n        platform: x64\n\n    - name: configure clang\n      run: |\n        echo \"CC=cc\" >> $GITHUB_ENV\n        echo \"CXX=c++\" >> $GITHUB_ENV\n\n    - name: build libc++ (non-asan)\n      if: matrix.sanitizer != 'asan'\n      run: |\n        \"${GITHUB_WORKSPACE}/.github/libcxx-setup.sh\"\n        echo \"EXTRA_CXX_FLAGS=-stdlib=libc++ -L ${GITHUB_WORKSPACE}/llvm-build/lib -lc++abi -Isystem${GITHUB_WORKSPACE}/llvm-build/include -Isystem${GITHUB_WORKSPACE}/llvm-build/include/c++/v1 -Wl,-rpath,${GITHUB_WORKSPACE}/llvm-build/lib\" >> $GITHUB_ENV\n\n    - name: create build environment\n      run: cmake -E make_directory ${{ runner.workspace }}/_build\n\n    - name: configure cmake\n      shell: bash\n      working-directory: ${{ runner.workspace }}/_build\n      run: >\n        VERBOSE=1\n        cmake $GITHUB_WORKSPACE\n        -DBENCHMARK_ENABLE_ASSEMBLY_TESTS=OFF\n        -DBENCHMARK_ENABLE_LIBPFM=OFF\n        -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON\n        -DCMAKE_C_COMPILER=${{ env.CC }}\n        -DCMAKE_CXX_COMPILER=${{ env.CXX }}\n        -DCMAKE_C_FLAGS=\"${{ env.EXTRA_FLAGS }}\"\n        -DCMAKE_CXX_FLAGS=\"${{ env.EXTRA_FLAGS }} ${{ env.EXTRA_CXX_FLAGS }}\"\n        -DCMAKE_BUILD_TYPE=${{ matrix.build_type }}\n\n    - name: build\n      shell: bash\n      working-directory: ${{ runner.workspace }}/_build\n      run: cmake --build . --config ${{ matrix.build_type }}\n\n    - name: test\n      shell: bash\n      working-directory: ${{ runner.workspace }}/_build\n      run: ctest -C ${{ matrix.build_type }} -VV\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/.github/workflows/test_bindings.yml",
    "content": "name: test-bindings\n\non:\n  push:\n    branches: [main]\n  pull_request:\n    branches: [main]\n\njobs:\n  python_bindings:\n    name: Test GBM Python bindings on ${{ matrix.os }}\n    runs-on: ${{ matrix.os }}\n    strategy:\n      fail-fast: false\n      matrix:\n        os: [ ubuntu-latest, macos-latest, windows-latest ]\n\n    steps:\n      - uses: actions/checkout@v3\n      - name: Set up Python\n        uses: actions/setup-python@v4\n        with:\n          python-version: 3.11\n      - name: Install GBM Python bindings on ${{ matrix.os}}\n        run:\n          python -m pip install wheel .\n      - name: Run bindings example on ${{ matrix.os }}\n        run:\n          python bindings/python/google_benchmark/example.py\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/.github/workflows/wheels.yml",
    "content": "name: Build and upload Python wheels\n\non:\n  workflow_dispatch:\n  release:\n    types:\n      - published\n\njobs:\n  build_sdist:\n    name: Build source distribution\n    runs-on: ubuntu-latest\n    steps:\n      - name: Check out repo\n        uses: actions/checkout@v3\n\n      - name: Install Python 3.11\n        uses: actions/setup-python@v4\n        with:\n          python-version: 3.11\n\n      - name: Build and check sdist\n        run: |\n          python setup.py sdist\n      - name: Upload sdist\n        uses: actions/upload-artifact@v3\n        with:\n          name: dist\n          path: dist/*.tar.gz\n\n  build_wheels:\n    name: Build Google Benchmark wheels on ${{ matrix.os }}\n    runs-on: ${{ matrix.os }}\n    strategy:\n      matrix:\n        os: [ubuntu-latest, macos-latest, windows-latest]\n\n    steps:\n      - name: Check out Google Benchmark\n        uses: actions/checkout@v3\n\n      - name: Set up QEMU\n        if: runner.os == 'Linux'\n        uses: docker/setup-qemu-action@v2\n        with:\n          platforms: all\n\n      - name: Build wheels on ${{ matrix.os }} using cibuildwheel\n        uses: pypa/cibuildwheel@v2.12.0\n        env:\n          CIBW_BUILD: 'cp38-* cp39-* cp310-* cp311-*'\n          CIBW_SKIP: \"*-musllinux_*\"\n          CIBW_TEST_SKIP: \"*-macosx_arm64\"\n          CIBW_ARCHS_LINUX: x86_64 aarch64\n          CIBW_ARCHS_MACOS: x86_64 arm64\n          CIBW_ARCHS_WINDOWS: AMD64\n          CIBW_BEFORE_ALL_LINUX: bash .github/install_bazel.sh\n          CIBW_TEST_COMMAND: python {project}/bindings/python/google_benchmark/example.py\n\n      - name: Upload Google Benchmark ${{ matrix.os }} wheels\n        uses: actions/upload-artifact@v3\n        with:\n          name: dist\n          path: ./wheelhouse/*.whl\n\n  pypi_upload:\n    name: Publish google-benchmark wheels to PyPI\n    needs: [build_sdist, build_wheels]\n    runs-on: ubuntu-latest\n    steps:\n    - uses: actions/download-artifact@v3\n      with:\n        name: dist\n        path: dist\n\n    - uses: pypa/gh-action-pypi-publish@v1.6.4\n      with:\n        user: __token__\n        password: ${{ secrets.PYPI_PASSWORD }}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/.gitignore",
    "content": "*.a\n*.so\n*.so.?*\n*.dll\n*.exe\n*.dylib\n*.cmake\n!/cmake/*.cmake\n!/test/AssemblyTests.cmake\n*~\n*.swp\n*.pyc\n__pycache__\n.DS_Store\n\n# lcov\n*.lcov\n/lcov\n\n# cmake files.\n/Testing\nCMakeCache.txt\nCMakeFiles/\ncmake_install.cmake\n\n# makefiles.\nMakefile\n\n# in-source build.\nbin/\nlib/\n/test/*_test\n\n# exuberant ctags.\ntags\n\n# YouCompleteMe configuration.\n.ycm_extra_conf.pyc\n\n# ninja generated files.\n.ninja_deps\n.ninja_log\nbuild.ninja\ninstall_manifest.txt\nrules.ninja\n\n# bazel output symlinks.\nbazel-*\n\n# out-of-source build top-level folders.\nbuild/\n_build/\nbuild*/\n\n# in-source dependencies\n/googletest/\n\n# Visual Studio 2015/2017 cache/options directory\n.vs/\nCMakeSettings.json\n\n# Visual Studio Code cache/options directory\n.vscode/\n\n# Python build stuff\ndist/\n*.egg-info*\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/.travis.yml",
    "content": "sudo: required\ndist: trusty\nlanguage: cpp\n\nmatrix:\n  include:\n    - compiler: gcc\n      addons:\n        apt:\n          packages:\n            - lcov\n      env: COMPILER=g++ C_COMPILER=gcc BUILD_TYPE=Coverage\n    - compiler: gcc\n      addons:\n        apt:\n          packages:\n            - g++-multilib\n            - libc6:i386\n      env:\n        - COMPILER=g++\n        - C_COMPILER=gcc\n        - BUILD_TYPE=Debug\n        - BUILD_32_BITS=ON\n        - EXTRA_FLAGS=\"-m32\"\n    - compiler: gcc\n      addons:\n        apt:\n          packages:\n            - g++-multilib\n            - libc6:i386\n      env:\n        - COMPILER=g++\n        - C_COMPILER=gcc\n        - BUILD_TYPE=Release\n        - BUILD_32_BITS=ON\n        - EXTRA_FLAGS=\"-m32\"\n    - compiler: gcc\n      env:\n        - INSTALL_GCC6_FROM_PPA=1\n        - COMPILER=g++-6 C_COMPILER=gcc-6  BUILD_TYPE=Debug\n        - ENABLE_SANITIZER=1\n        - EXTRA_FLAGS=\"-fno-omit-frame-pointer -g -O2 -fsanitize=undefined,address -fuse-ld=gold\"\n    # Clang w/ libc++\n    - compiler: clang\n      dist: xenial\n      addons:\n        apt:\n          packages:\n            clang-3.8\n      env:\n        - INSTALL_GCC6_FROM_PPA=1\n        - COMPILER=clang++-3.8 C_COMPILER=clang-3.8 BUILD_TYPE=Debug\n        - LIBCXX_BUILD=1\n        - EXTRA_CXX_FLAGS=\"-stdlib=libc++\"\n    - compiler: clang\n      dist: xenial\n      addons:\n        apt:\n          packages:\n            clang-3.8\n      env:\n        - INSTALL_GCC6_FROM_PPA=1\n        - COMPILER=clang++-3.8 C_COMPILER=clang-3.8 BUILD_TYPE=Release\n        - LIBCXX_BUILD=1\n        - EXTRA_CXX_FLAGS=\"-stdlib=libc++\"\n    # Clang w/ 32bit libc++\n    - compiler: clang\n      dist: xenial\n      addons:\n        apt:\n          packages:\n            - clang-3.8\n            - g++-multilib\n            - libc6:i386\n      env:\n        - INSTALL_GCC6_FROM_PPA=1\n        - COMPILER=clang++-3.8 C_COMPILER=clang-3.8 BUILD_TYPE=Debug\n        - LIBCXX_BUILD=1\n        - BUILD_32_BITS=ON\n        - EXTRA_FLAGS=\"-m32\"\n        - EXTRA_CXX_FLAGS=\"-stdlib=libc++\"\n    # Clang w/ 32bit libc++\n    - compiler: clang\n      dist: xenial\n      addons:\n        apt:\n          packages:\n            - clang-3.8\n            - g++-multilib\n            - libc6:i386\n      env:\n        - INSTALL_GCC6_FROM_PPA=1\n        - COMPILER=clang++-3.8 C_COMPILER=clang-3.8 BUILD_TYPE=Release\n        - LIBCXX_BUILD=1\n        - BUILD_32_BITS=ON\n        - EXTRA_FLAGS=\"-m32\"\n        - EXTRA_CXX_FLAGS=\"-stdlib=libc++\"\n    # Clang w/ libc++, ASAN, UBSAN\n    - compiler: clang\n      dist: xenial\n      addons:\n        apt:\n          packages:\n            clang-3.8\n      env:\n        - INSTALL_GCC6_FROM_PPA=1\n        - COMPILER=clang++-3.8 C_COMPILER=clang-3.8 BUILD_TYPE=Debug\n        - LIBCXX_BUILD=1 LIBCXX_SANITIZER=\"Undefined;Address\"\n        - ENABLE_SANITIZER=1\n        - EXTRA_FLAGS=\"-g -O2 -fno-omit-frame-pointer -fsanitize=undefined,address -fno-sanitize-recover=all\"\n        - EXTRA_CXX_FLAGS=\"-stdlib=libc++\"\n        - UBSAN_OPTIONS=print_stacktrace=1\n    # Clang w/ libc++ and MSAN\n    - compiler: clang\n      dist: xenial\n      addons:\n        apt:\n          packages:\n            clang-3.8\n      env:\n        - INSTALL_GCC6_FROM_PPA=1\n        - COMPILER=clang++-3.8 C_COMPILER=clang-3.8 BUILD_TYPE=Debug\n        - LIBCXX_BUILD=1 LIBCXX_SANITIZER=MemoryWithOrigins\n        - ENABLE_SANITIZER=1\n        - EXTRA_FLAGS=\"-g -O2 -fno-omit-frame-pointer -fsanitize=memory -fsanitize-memory-track-origins\"\n        - EXTRA_CXX_FLAGS=\"-stdlib=libc++\"\n    # Clang w/ libc++ and MSAN\n    - compiler: clang\n      dist: xenial\n      addons:\n        apt:\n          packages:\n            clang-3.8\n      env:\n        - INSTALL_GCC6_FROM_PPA=1\n        - COMPILER=clang++-3.8 C_COMPILER=clang-3.8 BUILD_TYPE=RelWithDebInfo\n        - LIBCXX_BUILD=1 LIBCXX_SANITIZER=Thread\n        - ENABLE_SANITIZER=1\n        - EXTRA_FLAGS=\"-g -O2 -fno-omit-frame-pointer -fsanitize=thread -fno-sanitize-recover=all\"\n        - EXTRA_CXX_FLAGS=\"-stdlib=libc++\"\n    - os: osx\n      osx_image: xcode8.3\n      compiler: clang\n      env:\n        - COMPILER=clang++\n        - BUILD_TYPE=Release\n        - BUILD_32_BITS=ON\n        - EXTRA_FLAGS=\"-m32\"\n\nbefore_script:\n  - if [ -n \"${LIBCXX_BUILD}\" ]; then\n      source .libcxx-setup.sh;\n    fi\n  - if [ -n \"${ENABLE_SANITIZER}\" ]; then\n      export EXTRA_OPTIONS=\"-DBENCHMARK_ENABLE_ASSEMBLY_TESTS=OFF\";\n    else\n      export EXTRA_OPTIONS=\"\";\n    fi\n  - mkdir -p build && cd build\n\nbefore_install:\n  - if [ -z \"$BUILD_32_BITS\" ]; then\n      export BUILD_32_BITS=OFF && echo disabling 32 bit build;\n    fi\n  - if [ -n \"${INSTALL_GCC6_FROM_PPA}\" ]; then\n      sudo add-apt-repository -y \"ppa:ubuntu-toolchain-r/test\";\n      sudo apt-get update --option Acquire::Retries=100 --option Acquire::http::Timeout=\"60\";\n    fi\n\ninstall:\n  - if [ -n \"${INSTALL_GCC6_FROM_PPA}\" ]; then\n      travis_wait sudo -E apt-get -yq --no-install-suggests --no-install-recommends install g++-6;\n    fi\n  - if [ \"${TRAVIS_OS_NAME}\" == \"linux\" -a \"${BUILD_32_BITS}\" == \"OFF\" ]; then\n      travis_wait sudo -E apt-get -y --no-install-suggests --no-install-recommends install llvm-3.9-tools;\n      sudo cp /usr/lib/llvm-3.9/bin/FileCheck /usr/local/bin/;\n    fi\n  - if [ \"${BUILD_TYPE}\" == \"Coverage\" -a \"${TRAVIS_OS_NAME}\" == \"linux\" ]; then\n      PATH=~/.local/bin:${PATH};\n      pip install --user --upgrade pip;\n      travis_wait pip install --user cpp-coveralls;\n    fi\n  - if [ \"${C_COMPILER}\" == \"gcc-7\" -a \"${TRAVIS_OS_NAME}\" == \"osx\" ]; then\n      rm -f /usr/local/include/c++;\n      brew update;\n      travis_wait brew install gcc@7;\n    fi\n  - if [ \"${TRAVIS_OS_NAME}\" == \"linux\" ]; then\n      sudo apt-get update -qq;\n      sudo apt-get install -qq unzip cmake3;\n      wget https://github.com/bazelbuild/bazel/releases/download/3.2.0/bazel-3.2.0-installer-linux-x86_64.sh --output-document bazel-installer.sh;\n      travis_wait sudo bash bazel-installer.sh;\n    fi\n  - if [ \"${TRAVIS_OS_NAME}\" == \"osx\" ]; then\n      curl -L -o bazel-installer.sh https://github.com/bazelbuild/bazel/releases/download/3.2.0/bazel-3.2.0-installer-darwin-x86_64.sh;\n      travis_wait sudo bash bazel-installer.sh;\n    fi\n\nscript:\n  - cmake -DCMAKE_C_COMPILER=${C_COMPILER} -DCMAKE_CXX_COMPILER=${COMPILER} -DCMAKE_BUILD_TYPE=${BUILD_TYPE} -DCMAKE_C_FLAGS=\"${EXTRA_FLAGS}\" -DCMAKE_CXX_FLAGS=\"${EXTRA_FLAGS} ${EXTRA_CXX_FLAGS}\" -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON -DBENCHMARK_BUILD_32_BITS=${BUILD_32_BITS} ${EXTRA_OPTIONS} ..\n  - make\n  - ctest -C ${BUILD_TYPE} --output-on-failure\n  - bazel test -c dbg --define google_benchmark.have_regex=posix --announce_rc --verbose_failures --test_output=errors --keep_going //test/...\n\nafter_success:\n  - if [ \"${BUILD_TYPE}\" == \"Coverage\" -a \"${TRAVIS_OS_NAME}\" == \"linux\" ]; then\n      coveralls --include src --include include --gcov-options '\\-lp' --root .. --build-root .;\n    fi\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/.ycm_extra_conf.py",
    "content": "import os\nimport ycm_core\n\n# These are the compilation flags that will be used in case there's no\n# compilation database set (by default, one is not set).\n# CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR.\nflags = [\n'-Wall',\n'-Werror',\n'-pedantic-errors',\n'-std=c++0x',\n'-fno-strict-aliasing',\n'-O3',\n'-DNDEBUG',\n# ...and the same thing goes for the magic -x option which specifies the\n# language that the files to be compiled are written in. This is mostly\n# relevant for c++ headers.\n# For a C project, you would set this to 'c' instead of 'c++'.\n'-x', 'c++',\n'-I', 'include',\n'-isystem', '/usr/include',\n'-isystem', '/usr/local/include',\n]\n\n\n# Set this to the absolute path to the folder (NOT the file!) containing the\n# compile_commands.json file to use that instead of 'flags'. See here for\n# more details: http://clang.llvm.org/docs/JSONCompilationDatabase.html\n#\n# Most projects will NOT need to set this to anything; you can just change the\n# 'flags' list of compilation flags. Notice that YCM itself uses that approach.\ncompilation_database_folder = ''\n\nif os.path.exists( compilation_database_folder ):\n  database = ycm_core.CompilationDatabase( compilation_database_folder )\nelse:\n  database = None\n\nSOURCE_EXTENSIONS = [ '.cc' ]\n\ndef DirectoryOfThisScript():\n  return os.path.dirname( os.path.abspath( __file__ ) )\n\n\ndef MakeRelativePathsInFlagsAbsolute( flags, working_directory ):\n  if not working_directory:\n    return list( flags )\n  new_flags = []\n  make_next_absolute = False\n  path_flags = [ '-isystem', '-I', '-iquote', '--sysroot=' ]\n  for flag in flags:\n    new_flag = flag\n\n    if make_next_absolute:\n      make_next_absolute = False\n      if not flag.startswith( '/' ):\n        new_flag = os.path.join( working_directory, flag )\n\n    for path_flag in path_flags:\n      if flag == path_flag:\n        make_next_absolute = True\n        break\n\n      if flag.startswith( path_flag ):\n        path = flag[ len( path_flag ): ]\n        new_flag = path_flag + os.path.join( working_directory, path )\n        break\n\n    if new_flag:\n      new_flags.append( new_flag )\n  return new_flags\n\n\ndef IsHeaderFile( filename ):\n  extension = os.path.splitext( filename )[ 1 ]\n  return extension in [ '.h', '.hxx', '.hpp', '.hh' ]\n\n\ndef GetCompilationInfoForFile( filename ):\n  # The compilation_commands.json file generated by CMake does not have entries\n  # for header files. So we do our best by asking the db for flags for a\n  # corresponding source file, if any. If one exists, the flags for that file\n  # should be good enough.\n  if IsHeaderFile( filename ):\n    basename = os.path.splitext( filename )[ 0 ]\n    for extension in SOURCE_EXTENSIONS:\n      replacement_file = basename + extension\n      if os.path.exists( replacement_file ):\n        compilation_info = database.GetCompilationInfoForFile(\n          replacement_file )\n        if compilation_info.compiler_flags_:\n          return compilation_info\n    return None\n  return database.GetCompilationInfoForFile( filename )\n\n\ndef FlagsForFile( filename, **kwargs ):\n  if database:\n    # Bear in mind that compilation_info.compiler_flags_ does NOT return a\n    # python list, but a \"list-like\" StringVec object\n    compilation_info = GetCompilationInfoForFile( filename )\n    if not compilation_info:\n      return None\n\n    final_flags = MakeRelativePathsInFlagsAbsolute(\n      compilation_info.compiler_flags_,\n      compilation_info.compiler_working_dir_ )\n  else:\n    relative_to = DirectoryOfThisScript()\n    final_flags = MakeRelativePathsInFlagsAbsolute( flags, relative_to )\n\n  return {\n    'flags': final_flags,\n    'do_cache': True\n  }\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/AUTHORS",
    "content": "# This is the official list of benchmark authors for copyright purposes.\n# This file is distinct from the CONTRIBUTORS files.\n# See the latter for an explanation.\n#\n# Names should be added to this file as:\n#\tName or Organization <email address>\n# The email address is not required for organizations.\n#\n# Please keep the list sorted.\n\nAlbert Pretorius <pretoalb@gmail.com>\nAlex Steele <steeleal123@gmail.com>\nAndriy Berestovskyy <berestovskyy@gmail.com>\nArne Beer <arne@twobeer.de>\nCarto\nCezary Skrzyński <czars1988@gmail.com>\nChristian Wassermann <christian_wassermann@web.de>\nChristopher Seymour <chris.j.seymour@hotmail.com>\nColin Braley <braley.colin@gmail.com>\nDaniel Harvey <danielharvey458@gmail.com>\nDavid Coeurjolly <david.coeurjolly@liris.cnrs.fr>\nDeniz Evrenci <denizevrenci@gmail.com>\nDirac Research \nDominik Czarnota <dominik.b.czarnota@gmail.com>\nDominik Korman <kormandominik@gmail.com>\nDonald Aingworth <donalds_junk_mail@yahoo.com>\nEric Backus <eric_backus@alum.mit.edu>\nEric Fiselier <eric@efcs.ca>\nEugene Zhuk <eugene.zhuk@gmail.com>\nEvgeny Safronov <division494@gmail.com>\nFederico Ficarelli <federico.ficarelli@gmail.com>\nFelix Homann <linuxaudio@showlabor.de>\nGergő Szitár <szitar.gergo@gmail.com>\nGoogle Inc.\nHenrique Bucher <hbucher@gmail.com>\nInternational Business Machines Corporation\nIsmael Jimenez Martinez <ismael.jimenez.martinez@gmail.com>\nJern-Kuan Leong <jernkuan@gmail.com>\nJianXiong Zhou <zhoujianxiong2@gmail.com>\nJoao Paulo Magalhaes <joaoppmagalhaes@gmail.com>\nJordan Williams <jwillikers@protonmail.com>\nJussi Knuuttila <jussi.knuuttila@gmail.com>\nKaito Udagawa <umireon@gmail.com>\nKishan Kumar <kumar.kishan@outlook.com>\nLei Xu <eddyxu@gmail.com>\nMarcel Jacobse <mjacobse@uni-bremen.de>\nMatt Clarkson <mattyclarkson@gmail.com>\nMaxim Vafin <maxvafin@gmail.com>\nMike Apodaca <gatorfax@gmail.com>\nMongoDB Inc.\nNick Hutchinson <nshutchinson@gmail.com>\nNorman Heino <norman.heino@gmail.com>\nOleksandr Sochka <sasha.sochka@gmail.com>\nOri Livneh <ori.livneh@gmail.com>\nPaul Redmond <paul.redmond@gmail.com>\nRaghu Raja <raghu@enfabrica.net>\nRadoslav Yovchev <radoslav.tm@gmail.com>\nRainer Orth <ro@cebitec.uni-bielefeld.de>\nRoman Lebedev <lebedev.ri@gmail.com>\nSayan Bhattacharjee <aero.sayan@gmail.com>\nShapr3D <google-contributors@shapr3d.com>\nShuo Chen <chenshuo@chenshuo.com>\nStaffan Tjernstrom <staffantj@gmail.com>\nSteinar H. Gunderson <sgunderson@bigfoot.com>\nStripe, Inc.\nTobias Schmidt <tobias.schmidt@in.tum.de>\nYixuan Qiu <yixuanq@gmail.com>\nYusuke Suzuki <utatane.tea@gmail.com>\nZbigniew Skowron <zbychs@gmail.com>\nMin-Yih Hsu <yihshyng223@gmail.com>\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/BUILD.bazel",
    "content": "licenses([\"notice\"])\n\nconfig_setting(\n    name = \"qnx\",\n    constraint_values = [\"@platforms//os:qnx\"],\n    values = {\n        \"cpu\": \"x64_qnx\",\n    },\n    visibility = [\":__subpackages__\"],\n)\n\nconfig_setting(\n    name = \"windows\",\n    constraint_values = [\"@platforms//os:windows\"],\n    values = {\n        \"cpu\": \"x64_windows\",\n    },\n    visibility = [\":__subpackages__\"],\n)\n\nconfig_setting(\n    name = \"macos\",\n    constraint_values = [\"@platforms//os:macos\"],\n    visibility = [\"//visibility:public\"],\n)\n\nconfig_setting(\n    name = \"perfcounters\",\n    define_values = {\n        \"pfm\": \"1\",\n    },\n    visibility = [\":__subpackages__\"],\n)\n\ncc_library(\n    name = \"benchmark\",\n    srcs = glob(\n        [\n            \"src/*.cc\",\n            \"src/*.h\",\n        ],\n        exclude = [\"src/benchmark_main.cc\"],\n    ),\n    hdrs = [\n        \"include/benchmark/benchmark.h\",\n        \"include/benchmark/export.h\",\n    ],\n    linkopts = select({\n        \":windows\": [\"-DEFAULTLIB:shlwapi.lib\"],\n        \"//conditions:default\": [\"-pthread\"],\n    }),\n    copts = select({\n        \":windows\": [],\n        \"//conditions:default\": [\"-Werror=old-style-cast\"],\n    }),\n    strip_include_prefix = \"include\",\n    visibility = [\"//visibility:public\"],\n    # Only static linking is allowed; no .so will be produced.\n    # Using `defines` (i.e. not `local_defines`) means that no\n    # dependent rules need to bother about defining the macro.\n    linkstatic = True,\n    defines = [\n        \"BENCHMARK_STATIC_DEFINE\",\n    ] + select({\n        \":perfcounters\": [\"HAVE_LIBPFM\"],\n        \"//conditions:default\": [],\n    }),\n    deps = select({\n        \":perfcounters\": [\"@libpfm//:libpfm\"],\n        \"//conditions:default\": [],\n    }),\n)\n\ncc_library(\n    name = \"benchmark_main\",\n    srcs = [\"src/benchmark_main.cc\"],\n    hdrs = [\"include/benchmark/benchmark.h\", \"include/benchmark/export.h\"],\n    strip_include_prefix = \"include\",\n    visibility = [\"//visibility:public\"],\n    deps = [\":benchmark\"],\n)\n\ncc_library(\n    name = \"benchmark_internal_headers\",\n    hdrs = glob([\"src/*.h\"]),\n    visibility = [\"//test:__pkg__\"],\n)\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/CMakeLists.txt",
    "content": "# Require CMake 3.10. If available, use the policies up to CMake 3.22.\ncmake_minimum_required (VERSION 3.10...3.22)\n\nproject (benchmark VERSION 1.8.2 LANGUAGES CXX)\n\noption(BENCHMARK_ENABLE_TESTING \"Enable testing of the benchmark library.\" OFF)\noption(BENCHMARK_ENABLE_EXCEPTIONS \"Enable the use of exceptions in the benchmark library.\" ON)\noption(BENCHMARK_ENABLE_LTO \"Enable link time optimisation of the benchmark library.\" OFF)\noption(BENCHMARK_USE_LIBCXX \"Build and test using libc++ as the standard library.\" OFF)\noption(BENCHMARK_ENABLE_WERROR \"Build Release candidates with -Werror.\" ON)\noption(BENCHMARK_FORCE_WERROR \"Build Release candidates with -Werror regardless of compiler issues.\" OFF)\n\nif(\"${CMAKE_CXX_COMPILER_ID}\" STREQUAL \"PGI\")\n  # PGC++ maybe reporting false positives.\n  set(BENCHMARK_ENABLE_WERROR OFF)\nendif()\nif(\"${CMAKE_CXX_COMPILER_ID}\" STREQUAL \"NVHPC\")\n  set(BENCHMARK_ENABLE_WERROR OFF)\nendif()\nif(BENCHMARK_FORCE_WERROR)\n  set(BENCHMARK_ENABLE_WERROR ON)\nendif(BENCHMARK_FORCE_WERROR)\n\nif(NOT MSVC)\n  option(BENCHMARK_BUILD_32_BITS \"Build a 32 bit version of the library.\" OFF)\nelse()\n  set(BENCHMARK_BUILD_32_BITS OFF CACHE BOOL \"Build a 32 bit version of the library - unsupported when using MSVC)\" FORCE)\nendif()\noption(BENCHMARK_ENABLE_INSTALL \"Enable installation of benchmark. (Projects embedding benchmark may want to turn this OFF.)\" ON)\noption(BENCHMARK_ENABLE_DOXYGEN \"Build documentation with Doxygen.\" OFF)\noption(BENCHMARK_INSTALL_DOCS \"Enable installation of documentation.\" ON)\n\n# Allow unmet dependencies to be met using CMake's ExternalProject mechanics, which\n# may require downloading the source code.\noption(BENCHMARK_DOWNLOAD_DEPENDENCIES \"Allow the downloading and in-tree building of unmet dependencies\" OFF)\n\n# This option can be used to disable building and running unit tests which depend on gtest\n# in cases where it is not possible to build or find a valid version of gtest.\noption(BENCHMARK_ENABLE_GTEST_TESTS \"Enable building the unit tests which depend on gtest\" OFF)\noption(BENCHMARK_USE_BUNDLED_GTEST \"Use bundled GoogleTest. If disabled, the find_package(GTest) will be used.\" OFF)\n\noption(BENCHMARK_ENABLE_LIBPFM \"Enable performance counters provided by libpfm\" OFF)\n\n# Export only public symbols\nset(CMAKE_CXX_VISIBILITY_PRESET hidden)\nset(CMAKE_VISIBILITY_INLINES_HIDDEN ON)\n\nif(MSVC)\n    # As of CMake 3.18, CMAKE_SYSTEM_PROCESSOR is not set properly for MSVC and\n    # cross-compilation (e.g. Host=x86_64, target=aarch64) requires using the\n    # undocumented, but working variable.\n    # See https://gitlab.kitware.com/cmake/cmake/-/issues/15170\n    set(CMAKE_SYSTEM_PROCESSOR ${MSVC_CXX_ARCHITECTURE_ID})\n    if(${CMAKE_SYSTEM_PROCESSOR} MATCHES \"ARM\")\n      set(CMAKE_CROSSCOMPILING TRUE)\n    endif()\nendif()\n\nset(ENABLE_ASSEMBLY_TESTS_DEFAULT OFF)\nfunction(should_enable_assembly_tests)\n  if(CMAKE_BUILD_TYPE)\n    string(TOLOWER ${CMAKE_BUILD_TYPE} CMAKE_BUILD_TYPE_LOWER)\n    if (${CMAKE_BUILD_TYPE_LOWER} MATCHES \"coverage\")\n      # FIXME: The --coverage flag needs to be removed when building assembly\n      # tests for this to work.\n      return()\n    endif()\n  endif()\n  if (MSVC)\n    return()\n  elseif(NOT CMAKE_SYSTEM_PROCESSOR MATCHES \"x86_64\")\n    return()\n  elseif(NOT CMAKE_SIZEOF_VOID_P EQUAL 8)\n    # FIXME: Make these work on 32 bit builds\n    return()\n  elseif(BENCHMARK_BUILD_32_BITS)\n     # FIXME: Make these work on 32 bit builds\n    return()\n  endif()\n  find_program(LLVM_FILECHECK_EXE FileCheck)\n  if (LLVM_FILECHECK_EXE)\n    set(LLVM_FILECHECK_EXE \"${LLVM_FILECHECK_EXE}\" CACHE PATH \"llvm filecheck\" FORCE)\n    message(STATUS \"LLVM FileCheck Found: ${LLVM_FILECHECK_EXE}\")\n  else()\n    message(STATUS \"Failed to find LLVM FileCheck\")\n    return()\n  endif()\n  set(ENABLE_ASSEMBLY_TESTS_DEFAULT ON PARENT_SCOPE)\nendfunction()\nshould_enable_assembly_tests()\n\n# This option disables the building and running of the assembly verification tests\noption(BENCHMARK_ENABLE_ASSEMBLY_TESTS \"Enable building and running the assembly tests\"\n    ${ENABLE_ASSEMBLY_TESTS_DEFAULT})\n\n# Make sure we can import out CMake functions\nlist(APPEND CMAKE_MODULE_PATH \"${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules\")\nlist(APPEND CMAKE_MODULE_PATH \"${CMAKE_CURRENT_SOURCE_DIR}/cmake\")\n\n\n# Read the git tags to determine the project version\ninclude(GetGitVersion)\nget_git_version(GIT_VERSION)\n\n# If no git version can be determined, use the version\n# from the project() command\nif (\"${GIT_VERSION}\" STREQUAL \"0.0.0\")\n  set(VERSION \"${benchmark_VERSION}\")\nelse()\n  set(VERSION \"${GIT_VERSION}\")\nendif()\n# Tell the user what versions we are using\nmessage(STATUS \"Google Benchmark version: ${VERSION}\")\n\n# The version of the libraries\nset(GENERIC_LIB_VERSION ${VERSION})\nstring(SUBSTRING ${VERSION} 0 1 GENERIC_LIB_SOVERSION)\n\n# Import our CMake modules\ninclude(AddCXXCompilerFlag)\ninclude(CheckCXXCompilerFlag)\ninclude(CheckLibraryExists)\ninclude(CXXFeatureCheck)\n\ncheck_library_exists(rt shm_open \"\" HAVE_LIB_RT)\n\nif (BENCHMARK_BUILD_32_BITS)\n  add_required_cxx_compiler_flag(-m32)\nendif()\n\nif (MSVC)\n  set(BENCHMARK_CXX_STANDARD 14)\nelse()\n  set(BENCHMARK_CXX_STANDARD 11)\nendif()\n\nset(CMAKE_CXX_STANDARD ${BENCHMARK_CXX_STANDARD})\nset(CMAKE_CXX_STANDARD_REQUIRED YES)\nset(CMAKE_CXX_EXTENSIONS OFF)\n\nif (MSVC)\n  # Turn compiler warnings up to 11\n  string(REGEX REPLACE \"[-/]W[1-4]\" \"\" CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS}\")\n  set(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} /W4\")\n  add_definitions(-D_CRT_SECURE_NO_WARNINGS)\n\n  if (NOT BENCHMARK_ENABLE_EXCEPTIONS)\n    add_cxx_compiler_flag(-EHs-)\n    add_cxx_compiler_flag(-EHa-)\n    add_definitions(-D_HAS_EXCEPTIONS=0)\n  endif()\n  # Link time optimisation\n  if (BENCHMARK_ENABLE_LTO)\n    set(CMAKE_CXX_FLAGS_RELEASE \"${CMAKE_CXX_FLAGS_RELEASE} /GL\")\n    set(CMAKE_STATIC_LINKER_FLAGS_RELEASE \"${CMAKE_STATIC_LINKER_FLAGS_RELEASE} /LTCG\")\n    set(CMAKE_SHARED_LINKER_FLAGS_RELEASE \"${CMAKE_SHARED_LINKER_FLAGS_RELEASE} /LTCG\")\n    set(CMAKE_EXE_LINKER_FLAGS_RELEASE \"${CMAKE_EXE_LINKER_FLAGS_RELEASE} /LTCG\")\n\n    set(CMAKE_CXX_FLAGS_RELWITHDEBINFO \"${CMAKE_CXX_FLAGS_RELWITHDEBINFO} /GL\")\n    string(REGEX REPLACE \"[-/]INCREMENTAL\" \"/INCREMENTAL:NO\" CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO \"${CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO}\")\n    set(CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO \"${CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO} /LTCG\")\n    string(REGEX REPLACE \"[-/]INCREMENTAL\" \"/INCREMENTAL:NO\" CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO \"${CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO}\")\n    set(CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO \"${CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO} /LTCG\")\n    string(REGEX REPLACE \"[-/]INCREMENTAL\" \"/INCREMENTAL:NO\" CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO \"${CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO}\")\n    set(CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO \"${CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO} /LTCG\")\n\n    set(CMAKE_CXX_FLAGS_MINSIZEREL \"${CMAKE_CXX_FLAGS_MINSIZEREL} /GL\")\n    set(CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL \"${CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL} /LTCG\")\n    set(CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL \"${CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL} /LTCG\")\n    set(CMAKE_EXE_LINKER_FLAGS_MINSIZEREL \"${CMAKE_EXE_LINKER_FLAGS_MINSIZEREL} /LTCG\")\n  endif()\nelse()\n  # Turn compiler warnings up to 11\n  add_cxx_compiler_flag(-Wall)\n  add_cxx_compiler_flag(-Wextra)\n  add_cxx_compiler_flag(-Wshadow)\n  add_cxx_compiler_flag(-Wfloat-equal)\n  add_cxx_compiler_flag(-Wold-style-cast)\n  if(BENCHMARK_ENABLE_WERROR)\n      add_cxx_compiler_flag(-Werror)\n  endif()\n  if (NOT BENCHMARK_ENABLE_TESTING)\n    # Disable warning when compiling tests as gtest does not use 'override'.\n    add_cxx_compiler_flag(-Wsuggest-override)\n  endif()\n  add_cxx_compiler_flag(-pedantic)\n  add_cxx_compiler_flag(-pedantic-errors)\n  add_cxx_compiler_flag(-Wshorten-64-to-32)\n  add_cxx_compiler_flag(-fstrict-aliasing)\n  # Disable warnings regarding deprecated parts of the library while building\n  # and testing those parts of the library.\n  add_cxx_compiler_flag(-Wno-deprecated-declarations)\n  if (CMAKE_CXX_COMPILER_ID STREQUAL \"Intel\")\n    # Intel silently ignores '-Wno-deprecated-declarations',\n    # warning no. 1786 must be explicitly disabled.\n    # See #631 for rationale.\n    add_cxx_compiler_flag(-wd1786)\n  endif()\n  # Disable deprecation warnings for release builds (when -Werror is enabled).\n  if(BENCHMARK_ENABLE_WERROR)\n      add_cxx_compiler_flag(-Wno-deprecated)\n  endif()\n  if (NOT BENCHMARK_ENABLE_EXCEPTIONS)\n    add_cxx_compiler_flag(-fno-exceptions)\n  endif()\n\n  if (HAVE_CXX_FLAG_FSTRICT_ALIASING)\n    if (NOT CMAKE_CXX_COMPILER_ID STREQUAL \"Intel\") #ICC17u2: Many false positives for Wstrict-aliasing\n      add_cxx_compiler_flag(-Wstrict-aliasing)\n    endif()\n  endif()\n  # ICC17u2: overloaded virtual function \"benchmark::Fixture::SetUp\" is only partially overridden\n  # (because of deprecated overload)\n  add_cxx_compiler_flag(-wd654)\n  add_cxx_compiler_flag(-Wthread-safety)\n  if (HAVE_CXX_FLAG_WTHREAD_SAFETY)\n    cxx_feature_check(THREAD_SAFETY_ATTRIBUTES \"-DINCLUDE_DIRECTORIES=${PROJECT_SOURCE_DIR}/include\")\n  endif()\n\n  # On most UNIX like platforms g++ and clang++ define _GNU_SOURCE as a\n  # predefined macro, which turns on all of the wonderful libc extensions.\n  # However g++ doesn't do this in Cygwin so we have to define it ourselves\n  # since we depend on GNU/POSIX/BSD extensions.\n  if (CYGWIN)\n    add_definitions(-D_GNU_SOURCE=1)\n  endif()\n\n  if (QNXNTO)\n    add_definitions(-D_QNX_SOURCE)\n  endif()\n\n  # Link time optimisation\n  if (BENCHMARK_ENABLE_LTO)\n    add_cxx_compiler_flag(-flto)\n    add_cxx_compiler_flag(-Wno-lto-type-mismatch)\n    if (\"${CMAKE_CXX_COMPILER_ID}\" STREQUAL \"GNU\")\n      find_program(GCC_AR gcc-ar)\n      if (GCC_AR)\n        set(CMAKE_AR ${GCC_AR})\n      endif()\n      find_program(GCC_RANLIB gcc-ranlib)\n      if (GCC_RANLIB)\n        set(CMAKE_RANLIB ${GCC_RANLIB})\n      endif()\n    elseif(\"${CMAKE_CXX_COMPILER_ID}\" MATCHES \"Clang\")\n      include(llvm-toolchain)\n    endif()\n  endif()\n\n  # Coverage build type\n  set(BENCHMARK_CXX_FLAGS_COVERAGE \"${CMAKE_CXX_FLAGS_DEBUG}\"\n    CACHE STRING \"Flags used by the C++ compiler during coverage builds.\"\n    FORCE)\n  set(BENCHMARK_EXE_LINKER_FLAGS_COVERAGE \"${CMAKE_EXE_LINKER_FLAGS_DEBUG}\"\n    CACHE STRING \"Flags used for linking binaries during coverage builds.\"\n    FORCE)\n  set(BENCHMARK_SHARED_LINKER_FLAGS_COVERAGE \"${CMAKE_SHARED_LINKER_FLAGS_DEBUG}\"\n    CACHE STRING \"Flags used by the shared libraries linker during coverage builds.\"\n    FORCE)\n  mark_as_advanced(\n    BENCHMARK_CXX_FLAGS_COVERAGE\n    BENCHMARK_EXE_LINKER_FLAGS_COVERAGE\n    BENCHMARK_SHARED_LINKER_FLAGS_COVERAGE)\n  set(CMAKE_BUILD_TYPE \"${CMAKE_BUILD_TYPE}\" CACHE STRING\n    \"Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel Coverage.\")\n  add_cxx_compiler_flag(--coverage COVERAGE)\nendif()\n\nif (BENCHMARK_USE_LIBCXX)\n  if (\"${CMAKE_CXX_COMPILER_ID}\" MATCHES \"Clang\")\n    add_cxx_compiler_flag(-stdlib=libc++)\n  elseif (\"${CMAKE_CXX_COMPILER_ID}\" STREQUAL \"GNU\" OR\n          \"${CMAKE_CXX_COMPILER_ID}\" STREQUAL \"Intel\")\n    add_cxx_compiler_flag(-nostdinc++)\n    message(WARNING \"libc++ header path must be manually specified using CMAKE_CXX_FLAGS\")\n    # Adding -nodefaultlibs directly to CMAKE_<TYPE>_LINKER_FLAGS will break\n    # configuration checks such as 'find_package(Threads)'\n    list(APPEND BENCHMARK_CXX_LINKER_FLAGS -nodefaultlibs)\n    # -lc++ cannot be added directly to CMAKE_<TYPE>_LINKER_FLAGS because\n    # linker flags appear before all linker inputs and -lc++ must appear after.\n    list(APPEND BENCHMARK_CXX_LIBRARIES c++)\n  else()\n    message(FATAL_ERROR \"-DBENCHMARK_USE_LIBCXX:BOOL=ON is not supported for compiler\")\n  endif()\nendif(BENCHMARK_USE_LIBCXX)\n\nset(EXTRA_CXX_FLAGS \"\")\nif (WIN32 AND \"${CMAKE_CXX_COMPILER_ID}\" MATCHES \"Clang\")\n  # Clang on Windows fails to compile the regex feature check under C++11\n  set(EXTRA_CXX_FLAGS \"-DCMAKE_CXX_STANDARD=14\")\nendif()\n\n# C++ feature checks\n# Determine the correct regular expression engine to use\ncxx_feature_check(STD_REGEX ${EXTRA_CXX_FLAGS})\ncxx_feature_check(GNU_POSIX_REGEX ${EXTRA_CXX_FLAGS})\ncxx_feature_check(POSIX_REGEX ${EXTRA_CXX_FLAGS})\nif(NOT HAVE_STD_REGEX AND NOT HAVE_GNU_POSIX_REGEX AND NOT HAVE_POSIX_REGEX)\n  message(FATAL_ERROR \"Failed to determine the source files for the regular expression backend\")\nendif()\nif (NOT BENCHMARK_ENABLE_EXCEPTIONS AND HAVE_STD_REGEX\n        AND NOT HAVE_GNU_POSIX_REGEX AND NOT HAVE_POSIX_REGEX)\n  message(WARNING \"Using std::regex with exceptions disabled is not fully supported\")\nendif()\n\ncxx_feature_check(STEADY_CLOCK)\n# Ensure we have pthreads\nset(THREADS_PREFER_PTHREAD_FLAG ON)\nfind_package(Threads REQUIRED)\ncxx_feature_check(PTHREAD_AFFINITY)\n\nif (BENCHMARK_ENABLE_LIBPFM)\n  find_package(PFM)\nendif()\n\n# Set up directories\ninclude_directories(${PROJECT_SOURCE_DIR}/include)\n\n# Build the targets\nadd_subdirectory(src)\n\nif (BENCHMARK_ENABLE_TESTING)\n  enable_testing()\n  if (BENCHMARK_ENABLE_GTEST_TESTS AND\n      NOT (TARGET gtest AND TARGET gtest_main AND\n           TARGET gmock AND TARGET gmock_main))\n    if (BENCHMARK_USE_BUNDLED_GTEST)\n      include(GoogleTest)\n    else()\n      find_package(GTest CONFIG REQUIRED)\n      add_library(gtest ALIAS GTest::gtest)\n      add_library(gtest_main ALIAS GTest::gtest_main)\n      add_library(gmock ALIAS GTest::gmock)\n      add_library(gmock_main ALIAS GTest::gmock_main)\n    endif()\n  endif()\n  add_subdirectory(test)\nendif()\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/CONTRIBUTING.md",
    "content": "# How to contribute #\n\nWe'd love to accept your patches and contributions to this project.  There are\na just a few small guidelines you need to follow.\n\n\n## Contributor License Agreement ##\n\nContributions to any Google project must be accompanied by a Contributor\nLicense Agreement.  This is not a copyright **assignment**, it simply gives\nGoogle permission to use and redistribute your contributions as part of the\nproject.\n\n  * If you are an individual writing original source code and you're sure you\n    own the intellectual property, then you'll need to sign an [individual\n    CLA][].\n\n  * If you work for a company that wants to allow you to contribute your work,\n    then you'll need to sign a [corporate CLA][].\n\nYou generally only need to submit a CLA once, so if you've already submitted\none (even if it was for a different project), you probably don't need to do it\nagain.\n\n[individual CLA]: https://developers.google.com/open-source/cla/individual\n[corporate CLA]: https://developers.google.com/open-source/cla/corporate\n\nOnce your CLA is submitted (or if you already submitted one for\nanother Google project), make a commit adding yourself to the\n[AUTHORS][] and [CONTRIBUTORS][] files. This commit can be part\nof your first [pull request][].\n\n[AUTHORS]: AUTHORS\n[CONTRIBUTORS]: CONTRIBUTORS\n\n\n## Submitting a patch ##\n\n  1. It's generally best to start by opening a new issue describing the bug or\n     feature you're intending to fix.  Even if you think it's relatively minor,\n     it's helpful to know what people are working on.  Mention in the initial\n     issue that you are planning to work on that bug or feature so that it can\n     be assigned to you.\n\n  1. Follow the normal process of [forking][] the project, and setup a new\n     branch to work in.  It's important that each group of changes be done in\n     separate branches in order to ensure that a pull request only includes the\n     commits related to that bug or feature.\n\n  1. Do your best to have [well-formed commit messages][] for each change.\n     This provides consistency throughout the project, and ensures that commit\n     messages are able to be formatted properly by various git tools.\n\n  1. Finally, push the commits to your fork and submit a [pull request][].\n\n[forking]: https://help.github.com/articles/fork-a-repo\n[well-formed commit messages]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html\n[pull request]: https://help.github.com/articles/creating-a-pull-request\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/CONTRIBUTORS",
    "content": "# People who have agreed to one of the CLAs and can contribute patches.\n# The AUTHORS file lists the copyright holders; this file\n# lists people.  For example, Google employees are listed here\n# but not in AUTHORS, because Google holds the copyright.\n#\n# Names should be added to this file only after verifying that\n# the individual or the individual's organization has agreed to\n# the appropriate Contributor License Agreement, found here:\n#\n# https://developers.google.com/open-source/cla/individual\n# https://developers.google.com/open-source/cla/corporate\n#\n# The agreement for individuals can be filled out on the web.\n#\n# When adding J Random Contributor's name to this file,\n# either J's name or J's organization's name should be\n# added to the AUTHORS file, depending on whether the\n# individual or corporate CLA was used.\n#\n# Names should be added to this file as:\n#     Name <email address>\n#\n# Please keep the list sorted.\n\nAbhina Sreeskantharajan <abhina.sreeskantharajan@ibm.com>\nAlbert Pretorius <pretoalb@gmail.com>\nAlex Steele <steelal123@gmail.com>\nAndriy Berestovskyy <berestovskyy@gmail.com>\nArne Beer <arne@twobeer.de>\nBátor Tallér <bator.taller@shapr3d.com>\nBilly Robert O'Neal III <billy.oneal@gmail.com> <bion@microsoft.com>\nCezary Skrzyński <czars1988@gmail.com>\nChris Kennelly <ckennelly@google.com> <ckennelly@ckennelly.com>\nChristian Wassermann <christian_wassermann@web.de>\nChristopher Seymour <chris.j.seymour@hotmail.com>\nColin Braley <braley.colin@gmail.com>\nCyrille Faucheux <cyrille.faucheux@gmail.com>\nDaniel Harvey <danielharvey458@gmail.com>\nDavid Coeurjolly <david.coeurjolly@liris.cnrs.fr>\nDeniz Evrenci <denizevrenci@gmail.com>\nDominic Hamon <dma@stripysock.com> <dominic@google.com>\nDominik Czarnota <dominik.b.czarnota@gmail.com>\nDominik Korman <kormandominik@gmail.com>\nDonald Aingworth <donalds_junk_mail@yahoo.com>\nEric Backus <eric_backus@alum.mit.edu>\nEric Fiselier <eric@efcs.ca>\nEugene Zhuk <eugene.zhuk@gmail.com>\nEvgeny Safronov <division494@gmail.com>\nFanbo Meng <fanbo.meng@ibm.com>\nFederico Ficarelli <federico.ficarelli@gmail.com>\nFelix Homann <linuxaudio@showlabor.de>\nGeoffrey Martin-Noble <gcmn@google.com> <gmngeoffrey@gmail.com>\nGergő Szitár <szitar.gergo@gmail.com>\nHannes Hauswedell <h2@fsfe.org>\nHenrique Bucher <hbucher@gmail.com>\nIsmael Jimenez Martinez <ismael.jimenez.martinez@gmail.com>\nJern-Kuan Leong <jernkuan@gmail.com>\nJianXiong Zhou <zhoujianxiong2@gmail.com>\nJoao Paulo Magalhaes <joaoppmagalhaes@gmail.com>\nJohn Millikin <jmillikin@stripe.com>\nJordan Williams <jwillikers@protonmail.com>\nJussi Knuuttila <jussi.knuuttila@gmail.com>\nKai Wolf <kai.wolf@gmail.com>\nKaito Udagawa <umireon@gmail.com>\nKishan Kumar <kumar.kishan@outlook.com>\nLei Xu <eddyxu@gmail.com>\nMarcel Jacobse <mjacobse@uni-bremen.de>\nMatt Clarkson <mattyclarkson@gmail.com>\nMaxim Vafin <maxvafin@gmail.com>\nMike Apodaca <gatorfax@gmail.com>\nNick Hutchinson <nshutchinson@gmail.com>\nNorman Heino <norman.heino@gmail.com>\nOleksandr Sochka <sasha.sochka@gmail.com>\nOri Livneh <ori.livneh@gmail.com>\nPascal Leroy <phl@google.com>\nPaul Redmond <paul.redmond@gmail.com>\nPierre Phaneuf <pphaneuf@google.com>\nRadoslav Yovchev <radoslav.tm@gmail.com>\nRainer Orth <ro@cebitec.uni-bielefeld.de>\nRaghu Raja <raghu@enfabrica.net>\nRaul Marin <rmrodriguez@cartodb.com>\nRay Glover <ray.glover@uk.ibm.com>\nRobert Guo <robert.guo@mongodb.com>\nRoman Lebedev <lebedev.ri@gmail.com>\nSayan Bhattacharjee <aero.sayan@gmail.com>\nShuo Chen <chenshuo@chenshuo.com>\nSteven Wan <wan.yu@ibm.com>\nTobias Schmidt <tobias.schmidt@in.tum.de>\nTobias Ulvgård <tobias.ulvgard@dirac.se>\nTom Madams <tom.ej.madams@gmail.com> <tmadams@google.com>\nYixuan Qiu <yixuanq@gmail.com>\nYusuke Suzuki <utatane.tea@gmail.com>\nZbigniew Skowron <zbychs@gmail.com>\nMin-Yih Hsu <yihshyng223@gmail.com>\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/LICENSE",
    "content": "\n                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/MODULE.bazel",
    "content": "module(name = \"com_github_google_benchmark\", version=\"1.8.2\")\n\nbazel_dep(name = \"bazel_skylib\", version = \"1.4.1\")\nbazel_dep(name = \"platforms\", version = \"0.0.6\")\nbazel_dep(name = \"rules_foreign_cc\", version = \"0.9.0\")\nbazel_dep(name = \"rules_cc\", version = \"0.0.6\")\nbazel_dep(name = \"rules_python\", version = \"0.23.1\")\nbazel_dep(name = \"googletest\", version = \"1.12.1\", repo_name = \"com_google_googletest\")\nbazel_dep(name = \"libpfm\", version = \"4.11.0\")\n\n# Register a toolchain for Python 3.9 to be able to build numpy. Python\n# versions >=3.10 are problematic.\n# A second reason for this is to be able to build Python hermetically instead\n# of relying on the changing default version from rules_python.\n\npython = use_extension(\"@rules_python//python/extensions:python.bzl\", \"python\")\npython.toolchain(python_version = \"3.9\")\n\n# Extract the interpreter from the hermetic toolchain above, so we can use that\n# instead of the system interpreter for the pip compiplation step below.\ninterpreter = use_extension(\"@rules_python//python/extensions:interpreter.bzl\", \"interpreter\")\ninterpreter.install(\n    name = \"interpreter\",\n    python_name = \"python_3_9\",\n)\nuse_repo(interpreter, \"interpreter\")\n\npip = use_extension(\"@rules_python//python/extensions:pip.bzl\", \"pip\")\npip.parse(\n    name=\"tools_pip_deps\",\n    incompatible_generate_aliases = True,\n    python_interpreter_target=\"@interpreter//:python\",\n    requirements_lock=\"//tools:requirements.txt\")\nuse_repo(pip, \"tools_pip_deps\")\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/README.md",
    "content": "# Benchmark\n\n[![build-and-test](https://github.com/google/benchmark/workflows/build-and-test/badge.svg)](https://github.com/google/benchmark/actions?query=workflow%3Abuild-and-test)\n[![bazel](https://github.com/google/benchmark/actions/workflows/bazel.yml/badge.svg)](https://github.com/google/benchmark/actions/workflows/bazel.yml)\n[![pylint](https://github.com/google/benchmark/workflows/pylint/badge.svg)](https://github.com/google/benchmark/actions?query=workflow%3Apylint)\n[![test-bindings](https://github.com/google/benchmark/workflows/test-bindings/badge.svg)](https://github.com/google/benchmark/actions?query=workflow%3Atest-bindings)\n[![Coverage Status](https://coveralls.io/repos/google/benchmark/badge.svg)](https://coveralls.io/r/google/benchmark)\n\n[![Discord](https://discordapp.com/api/guilds/1125694995928719494/widget.png?style=shield)](https://discord.gg/cz7UX7wKC2)\n\nA library to benchmark code snippets, similar to unit tests. Example:\n\n```c++\n#include <benchmark/benchmark.h>\n\nstatic void BM_SomeFunction(benchmark::State& state) {\n  // Perform setup here\n  for (auto _ : state) {\n    // This code gets timed\n    SomeFunction();\n  }\n}\n// Register the function as a benchmark\nBENCHMARK(BM_SomeFunction);\n// Run the benchmark\nBENCHMARK_MAIN();\n```\n\n## Getting Started\n\nTo get started, see [Requirements](#requirements) and\n[Installation](#installation). See [Usage](#usage) for a full example and the\n[User Guide](docs/user_guide.md) for a more comprehensive feature overview.\n\nIt may also help to read the [Google Test documentation](https://github.com/google/googletest/blob/main/docs/primer.md)\nas some of the structural aspects of the APIs are similar.\n\n## Resources\n\n[Discussion group](https://groups.google.com/d/forum/benchmark-discuss)\n\nIRC channels:\n* [libera](https://libera.chat) #benchmark\n\n[Additional Tooling Documentation](docs/tools.md)\n\n[Assembly Testing Documentation](docs/AssemblyTests.md)\n\n[Building and installing Python bindings](docs/python_bindings.md)\n\n## Requirements\n\nThe library can be used with C++03. However, it requires C++11 to build,\nincluding compiler and standard library support.\n\nThe following minimum versions are required to build the library:\n\n* GCC 4.8\n* Clang 3.4\n* Visual Studio 14 2015\n* Intel 2015 Update 1\n\nSee [Platform-Specific Build Instructions](docs/platform_specific_build_instructions.md).\n\n## Installation\n\nThis describes the installation process using cmake. As pre-requisites, you'll\nneed git and cmake installed.\n\n_See [dependencies.md](docs/dependencies.md) for more details regarding supported\nversions of build tools._\n\n```bash\n# Check out the library.\n$ git clone https://github.com/google/benchmark.git\n# Go to the library root directory\n$ cd benchmark\n# Make a build directory to place the build output.\n$ cmake -E make_directory \"build\"\n# Generate build system files with cmake, and download any dependencies.\n$ cmake -E chdir \"build\" cmake -DBENCHMARK_DOWNLOAD_DEPENDENCIES=on -DCMAKE_BUILD_TYPE=Release ../\n# or, starting with CMake 3.13, use a simpler form:\n# cmake -DCMAKE_BUILD_TYPE=Release -S . -B \"build\"\n# Build the library.\n$ cmake --build \"build\" --config Release\n```\nThis builds the `benchmark` and `benchmark_main` libraries and tests.\nOn a unix system, the build directory should now look something like this:\n\n```\n/benchmark\n  /build\n    /src\n      /libbenchmark.a\n      /libbenchmark_main.a\n    /test\n      ...\n```\n\nNext, you can run the tests to check the build.\n\n```bash\n$ cmake -E chdir \"build\" ctest --build-config Release\n```\n\nIf you want to install the library globally, also run:\n\n```\nsudo cmake --build \"build\" --config Release --target install\n```\n\nNote that Google Benchmark requires Google Test to build and run the tests. This\ndependency can be provided two ways:\n\n* Checkout the Google Test sources into `benchmark/googletest`.\n* Otherwise, if `-DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON` is specified during\n  configuration as above, the library will automatically download and build\n  any required dependencies.\n\nIf you do not wish to build and run the tests, add `-DBENCHMARK_ENABLE_GTEST_TESTS=OFF`\nto `CMAKE_ARGS`.\n\n### Debug vs Release\n\nBy default, benchmark builds as a debug library. You will see a warning in the\noutput when this is the case. To build it as a release library instead, add\n`-DCMAKE_BUILD_TYPE=Release` when generating the build system files, as shown\nabove. The use of `--config Release` in build commands is needed to properly\nsupport multi-configuration tools (like Visual Studio for example) and can be\nskipped for other build systems (like Makefile).\n\nTo enable link-time optimisation, also add `-DBENCHMARK_ENABLE_LTO=true` when\ngenerating the build system files.\n\nIf you are using gcc, you might need to set `GCC_AR` and `GCC_RANLIB` cmake\ncache variables, if autodetection fails.\n\nIf you are using clang, you may need to set `LLVMAR_EXECUTABLE`,\n`LLVMNM_EXECUTABLE` and `LLVMRANLIB_EXECUTABLE` cmake cache variables.\n\nTo enable sanitizer checks (eg., `asan` and `tsan`), add:\n```\n -DCMAKE_C_FLAGS=\"-g -O2 -fno-omit-frame-pointer -fsanitize=address -fsanitize=thread -fno-sanitize-recover=all\"\n -DCMAKE_CXX_FLAGS=\"-g -O2 -fno-omit-frame-pointer -fsanitize=address -fsanitize=thread -fno-sanitize-recover=all \"  \n```\n\n### Stable and Experimental Library Versions\n\nThe main branch contains the latest stable version of the benchmarking library;\nthe API of which can be considered largely stable, with source breaking changes\nbeing made only upon the release of a new major version.\n\nNewer, experimental, features are implemented and tested on the\n[`v2` branch](https://github.com/google/benchmark/tree/v2). Users who wish\nto use, test, and provide feedback on the new features are encouraged to try\nthis branch. However, this branch provides no stability guarantees and reserves\nthe right to change and break the API at any time.\n\n## Usage\n\n### Basic usage\n\nDefine a function that executes the code to measure, register it as a benchmark\nfunction using the `BENCHMARK` macro, and ensure an appropriate `main` function\nis available:\n\n```c++\n#include <benchmark/benchmark.h>\n\nstatic void BM_StringCreation(benchmark::State& state) {\n  for (auto _ : state)\n    std::string empty_string;\n}\n// Register the function as a benchmark\nBENCHMARK(BM_StringCreation);\n\n// Define another benchmark\nstatic void BM_StringCopy(benchmark::State& state) {\n  std::string x = \"hello\";\n  for (auto _ : state)\n    std::string copy(x);\n}\nBENCHMARK(BM_StringCopy);\n\nBENCHMARK_MAIN();\n```\n\nTo run the benchmark, compile and link against the `benchmark` library\n(libbenchmark.a/.so). If you followed the build steps above, this library will \nbe under the build directory you created.\n\n```bash\n# Example on linux after running the build steps above. Assumes the\n# `benchmark` and `build` directories are under the current directory.\n$ g++ mybenchmark.cc -std=c++11 -isystem benchmark/include \\\n  -Lbenchmark/build/src -lbenchmark -lpthread -o mybenchmark\n```\n\nAlternatively, link against the `benchmark_main` library and remove\n`BENCHMARK_MAIN();` above to get the same behavior.\n\nThe compiled executable will run all benchmarks by default. Pass the `--help`\nflag for option information or see the [User Guide](docs/user_guide.md).\n\n### Usage with CMake\n\nIf using CMake, it is recommended to link against the project-provided\n`benchmark::benchmark` and `benchmark::benchmark_main` targets using\n`target_link_libraries`.\nIt is possible to use ```find_package``` to import an installed version of the\nlibrary.\n```cmake\nfind_package(benchmark REQUIRED)\n```\nAlternatively, ```add_subdirectory``` will incorporate the library directly in\nto one's CMake project.\n```cmake\nadd_subdirectory(benchmark)\n```\nEither way, link to the library as follows.\n```cmake\ntarget_link_libraries(MyTarget benchmark::benchmark)\n```\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/WORKSPACE",
    "content": "workspace(name = \"com_github_google_benchmark\")\n\nload(\"//:bazel/benchmark_deps.bzl\", \"benchmark_deps\")\n\nbenchmark_deps()\n\nload(\"@rules_foreign_cc//foreign_cc:repositories.bzl\", \"rules_foreign_cc_dependencies\")\n\nrules_foreign_cc_dependencies()\n\nload(\"@rules_python//python:pip.bzl\", pip3_install=\"pip_install\")\n\npip3_install(\n   name = \"tools_pip_deps\",\n   requirements = \"//tools:requirements.txt\",\n)\n\nnew_local_repository(\n    name = \"python_headers\",\n    build_file = \"@//bindings/python:python_headers.BUILD\",\n    path = \"<PYTHON_INCLUDE_PATH>\",  # May be overwritten by setup.py.\n)\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/WORKSPACE.bzlmod",
    "content": "# This file marks the root of the Bazel workspace.\n# See MODULE.bazel for dependencies and setup.\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/_config.yml",
    "content": "theme: jekyll-theme-midnight\nmarkdown: GFM\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/appveyor.yml",
    "content": "version: '{build}'\n\nimage: Visual Studio 2017\n\nconfiguration:\n  - Debug\n  - Release\n\nenvironment:\n  matrix:\n    - compiler: msvc-15-seh\n      generator: \"Visual Studio 15 2017\"\n\n    - compiler: msvc-15-seh\n      generator: \"Visual Studio 15 2017 Win64\"\n\n    - compiler: msvc-14-seh\n      generator: \"Visual Studio 14 2015\"\n\n    - compiler: msvc-14-seh\n      generator: \"Visual Studio 14 2015 Win64\"\n\n    - compiler: gcc-5.3.0-posix\n      generator: \"MinGW Makefiles\"\n      cxx_path: 'C:\\mingw-w64\\i686-5.3.0-posix-dwarf-rt_v4-rev0\\mingw32\\bin'\n      APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2015\n\nmatrix:\n  fast_finish: true\n\ninstall:\n  # git bash conflicts with MinGW makefiles\n  - if \"%generator%\"==\"MinGW Makefiles\" (set \"PATH=%PATH:C:\\Program Files\\Git\\usr\\bin;=%\")\n  - if not \"%cxx_path%\"==\"\" (set \"PATH=%PATH%;%cxx_path%\")\n\nbuild_script:\n  - md _build -Force\n  - cd _build\n  - echo %configuration%\n  - cmake -G \"%generator%\" \"-DCMAKE_BUILD_TYPE=%configuration%\" -DBENCHMARK_DOWNLOAD_DEPENDENCIES=ON ..\n  - cmake --build . --config %configuration%\n\ntest_script:\n  - ctest --build-config %configuration% --timeout 300 --output-on-failure\n\nartifacts:\n  - path: '_build/CMakeFiles/*.log'\n    name: logs\n  - path: '_build/Testing/**/*.xml'\n    name: test_results\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/bazel/benchmark_deps.bzl",
    "content": "load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\nload(\"@bazel_tools//tools/build_defs/repo:git.bzl\", \"new_git_repository\")\n\ndef benchmark_deps():\n    \"\"\"Loads dependencies required to build Google Benchmark.\"\"\"\n\n    if \"bazel_skylib\" not in native.existing_rules():\n        http_archive(\n            name = \"bazel_skylib\",\n            sha256 = \"f7be3474d42aae265405a592bb7da8e171919d74c16f082a5457840f06054728\",\n            urls = [\n                \"https://mirror.bazel.build/github.com/bazelbuild/bazel-skylib/releases/download/1.2.1/bazel-skylib-1.2.1.tar.gz\",\n                \"https://github.com/bazelbuild/bazel-skylib/releases/download/1.2.1/bazel-skylib-1.2.1.tar.gz\",\n            ],\n        )\n\n    if \"rules_foreign_cc\" not in native.existing_rules():\n        http_archive(\n            name = \"rules_foreign_cc\",\n            sha256 = \"bcd0c5f46a49b85b384906daae41d277b3dc0ff27c7c752cc51e43048a58ec83\",\n            strip_prefix = \"rules_foreign_cc-0.7.1\",\n            url = \"https://github.com/bazelbuild/rules_foreign_cc/archive/0.7.1.tar.gz\",\n        )\n\n    if \"rules_python\" not in native.existing_rules():\n        http_archive(\n            name = \"rules_python\",\n            url = \"https://github.com/bazelbuild/rules_python/releases/download/0.1.0/rules_python-0.1.0.tar.gz\",\n            sha256 = \"b6d46438523a3ec0f3cead544190ee13223a52f6a6765a29eae7b7cc24cc83a0\",\n        )\n\n    if \"com_google_absl\" not in native.existing_rules():\n        http_archive(\n            name = \"com_google_absl\",\n            sha256 = \"f41868f7a938605c92936230081175d1eae87f6ea2c248f41077c8f88316f111\",\n            strip_prefix = \"abseil-cpp-20200225.2\",\n            urls = [\"https://github.com/abseil/abseil-cpp/archive/20200225.2.tar.gz\"],\n        )\n\n    if \"com_google_googletest\" not in native.existing_rules():\n        new_git_repository(\n            name = \"com_google_googletest\",\n            remote = \"https://github.com/google/googletest.git\",\n            tag = \"release-1.11.0\",\n        )\n\n    if \"nanobind\" not in native.existing_rules():\n        new_git_repository(\n            name = \"nanobind\",\n            remote = \"https://github.com/wjakob/nanobind.git\",\n            commit = \"1ffbfe836c9dac599496a170274ee0075094a607\", # v0.2.0\n            shallow_since = \"1677873085 +0100\",\n            build_file = \"@//bindings/python:nanobind.BUILD\",\n            recursive_init_submodules = True,\n        )\n\n    if \"libpfm\" not in native.existing_rules():\n        # Downloaded from v4.9.0 tag at https://sourceforge.net/p/perfmon2/libpfm4/ref/master/tags/\n        http_archive(\n            name = \"libpfm\",\n            build_file = str(Label(\"//tools:libpfm.BUILD.bazel\")),\n            sha256 = \"5da5f8872bde14b3634c9688d980f68bda28b510268723cc12973eedbab9fecc\",\n            type = \"tar.gz\",\n            strip_prefix = \"libpfm-4.11.0\",\n            urls = [\"https://sourceforge.net/projects/perfmon2/files/libpfm4/libpfm-4.11.0.tar.gz/download\"],\n        )\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/bindings/python/BUILD",
    "content": "exports_files(glob([\"*.BUILD\"]))\nexports_files([\"build_defs.bzl\"])\n\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/bindings/python/build_defs.bzl",
    "content": "_SHARED_LIB_SUFFIX = {\n    \"//conditions:default\": \".so\",\n    \"//:windows\": \".dll\",\n}\n\ndef py_extension(name, srcs, hdrs = [], copts = [], features = [], deps = []):\n    for shared_lib_suffix in _SHARED_LIB_SUFFIX.values():\n        shared_lib_name = name + shared_lib_suffix\n        native.cc_binary(\n            name = shared_lib_name,\n            linkshared = True,\n            linkstatic = True,\n            srcs = srcs + hdrs,\n            copts = copts,\n            features = features,\n            deps = deps,\n        )\n\n    return native.py_library(\n        name = name,\n        data = select({\n            platform: [name + shared_lib_suffix]\n            for platform, shared_lib_suffix in _SHARED_LIB_SUFFIX.items()\n        }),\n    )\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/bindings/python/google_benchmark/BUILD",
    "content": "load(\"//bindings/python:build_defs.bzl\", \"py_extension\")\n\npy_library(\n    name = \"google_benchmark\",\n    srcs = [\"__init__.py\"],\n    visibility = [\"//visibility:public\"],\n    deps = [\n        \":_benchmark\",\n    ],\n)\n\npy_extension(\n    name = \"_benchmark\",\n    srcs = [\"benchmark.cc\"],\n    copts = [\n        \"-fexceptions\",\n        \"-fno-strict-aliasing\",\n    ],\n    features = [\n        \"-use_header_modules\",\n        \"-parse_headers\",\n    ],\n    deps = [\n        \"//:benchmark\",\n        \"@nanobind\",\n        \"@python_headers\",\n    ],\n)\n\npy_test(\n    name = \"example\",\n    srcs = [\"example.py\"],\n    python_version = \"PY3\",\n    srcs_version = \"PY3\",\n    visibility = [\"//visibility:public\"],\n    deps = [\n        \":google_benchmark\",\n    ],\n)\n\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/bindings/python/google_benchmark/__init__.py",
    "content": "# Copyright 2020 Google Inc. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Python benchmarking utilities.\n\nExample usage:\n  import google_benchmark as benchmark\n\n  @benchmark.register\n  def my_benchmark(state):\n      ...  # Code executed outside `while` loop is not timed.\n\n      while state:\n        ...  # Code executed within `while` loop is timed.\n\n  if __name__ == '__main__':\n    benchmark.main()\n\"\"\"\nimport atexit\n\nfrom absl import app\nfrom google_benchmark import _benchmark\nfrom google_benchmark._benchmark import (\n    Counter,\n    kNanosecond,\n    kMicrosecond,\n    kMillisecond,\n    kSecond,\n    oNone,\n    o1,\n    oN,\n    oNSquared,\n    oNCubed,\n    oLogN,\n    oNLogN,\n    oAuto,\n    oLambda,\n    State,\n)\n\n\n__all__ = [\n    \"register\",\n    \"main\",\n    \"Counter\",\n    \"kNanosecond\",\n    \"kMicrosecond\",\n    \"kMillisecond\",\n    \"kSecond\",\n    \"oNone\",\n    \"o1\",\n    \"oN\",\n    \"oNSquared\",\n    \"oNCubed\",\n    \"oLogN\",\n    \"oNLogN\",\n    \"oAuto\",\n    \"oLambda\",\n    \"State\",\n]\n\n__version__ = \"1.8.2\"\n\n\nclass __OptionMaker:\n    \"\"\"A stateless class to collect benchmark options.\n\n    Collect all decorator calls like @option.range(start=0, limit=1<<5).\n    \"\"\"\n\n    class Options:\n        \"\"\"Pure data class to store options calls, along with the benchmarked function.\"\"\"\n\n        def __init__(self, func):\n            self.func = func\n            self.builder_calls = []\n\n    @classmethod\n    def make(cls, func_or_options):\n        \"\"\"Make Options from Options or the benchmarked function.\"\"\"\n        if isinstance(func_or_options, cls.Options):\n            return func_or_options\n        return cls.Options(func_or_options)\n\n    def __getattr__(self, builder_name):\n        \"\"\"Append option call in the Options.\"\"\"\n\n        # The function that get returned on @option.range(start=0, limit=1<<5).\n        def __builder_method(*args, **kwargs):\n\n            # The decorator that get called, either with the benchmared function\n            # or the previous Options\n            def __decorator(func_or_options):\n                options = self.make(func_or_options)\n                options.builder_calls.append((builder_name, args, kwargs))\n                # The decorator returns Options so it is not technically a decorator\n                # and needs a final call to @register\n                return options\n\n            return __decorator\n\n        return __builder_method\n\n\n# Alias for nicer API.\n# We have to instantiate an object, even if stateless, to be able to use __getattr__\n# on option.range\noption = __OptionMaker()\n\n\ndef register(undefined=None, *, name=None):\n    \"\"\"Register function for benchmarking.\"\"\"\n    if undefined is None:\n        # Decorator is called without parenthesis so we return a decorator\n        return lambda f: register(f, name=name)\n\n    # We have either the function to benchmark (simple case) or an instance of Options\n    # (@option._ case).\n    options = __OptionMaker.make(undefined)\n\n    if name is None:\n        name = options.func.__name__\n\n    # We register the benchmark and reproduce all the @option._ calls onto the\n    # benchmark builder pattern\n    benchmark = _benchmark.RegisterBenchmark(name, options.func)\n    for name, args, kwargs in options.builder_calls[::-1]:\n        getattr(benchmark, name)(*args, **kwargs)\n\n    # return the benchmarked function because the decorator does not modify it\n    return options.func\n\n\ndef _flags_parser(argv):\n    argv = _benchmark.Initialize(argv)\n    return app.parse_flags_with_usage(argv)\n\n\ndef _run_benchmarks(argv):\n    if len(argv) > 1:\n        raise app.UsageError(\"Too many command-line arguments.\")\n    return _benchmark.RunSpecifiedBenchmarks()\n\n\ndef main(argv=None):\n    return app.run(_run_benchmarks, argv=argv, flags_parser=_flags_parser)\n\n\n# Methods for use with custom main function.\ninitialize = _benchmark.Initialize\nrun_benchmarks = _benchmark.RunSpecifiedBenchmarks\natexit.register(_benchmark.ClearRegisteredBenchmarks)\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/bindings/python/google_benchmark/benchmark.cc",
    "content": "// Benchmark for Python.\n\n#include \"benchmark/benchmark.h\"\n\n#include \"nanobind/nanobind.h\"\n#include \"nanobind/operators.h\"\n#include \"nanobind/stl/bind_map.h\"\n#include \"nanobind/stl/string.h\"\n#include \"nanobind/stl/vector.h\"\n\nNB_MAKE_OPAQUE(benchmark::UserCounters);\n\nnamespace {\nnamespace nb = nanobind;\n\nstd::vector<std::string> Initialize(const std::vector<std::string>& argv) {\n  // The `argv` pointers here become invalid when this function returns, but\n  // benchmark holds the pointer to `argv[0]`. We create a static copy of it\n  // so it persists, and replace the pointer below.\n  static std::string executable_name(argv[0]);\n  std::vector<char*> ptrs;\n  ptrs.reserve(argv.size());\n  for (auto& arg : argv) {\n    ptrs.push_back(const_cast<char*>(arg.c_str()));\n  }\n  ptrs[0] = const_cast<char*>(executable_name.c_str());\n  int argc = static_cast<int>(argv.size());\n  benchmark::Initialize(&argc, ptrs.data());\n  std::vector<std::string> remaining_argv;\n  remaining_argv.reserve(argc);\n  for (int i = 0; i < argc; ++i) {\n    remaining_argv.emplace_back(ptrs[i]);\n  }\n  return remaining_argv;\n}\n\nbenchmark::internal::Benchmark* RegisterBenchmark(const std::string& name,\n                                                  nb::callable f) {\n  return benchmark::RegisterBenchmark(\n      name, [f](benchmark::State& state) { f(&state); });\n}\n\nNB_MODULE(_benchmark, m) {\n\n  using benchmark::TimeUnit;\n  nb::enum_<TimeUnit>(m, \"TimeUnit\")\n      .value(\"kNanosecond\", TimeUnit::kNanosecond)\n      .value(\"kMicrosecond\", TimeUnit::kMicrosecond)\n      .value(\"kMillisecond\", TimeUnit::kMillisecond)\n      .value(\"kSecond\", TimeUnit::kSecond)\n      .export_values();\n\n  using benchmark::BigO;\n  nb::enum_<BigO>(m, \"BigO\")\n      .value(\"oNone\", BigO::oNone)\n      .value(\"o1\", BigO::o1)\n      .value(\"oN\", BigO::oN)\n      .value(\"oNSquared\", BigO::oNSquared)\n      .value(\"oNCubed\", BigO::oNCubed)\n      .value(\"oLogN\", BigO::oLogN)\n      .value(\"oNLogN\", BigO::oNLogN)\n      .value(\"oAuto\", BigO::oAuto)\n      .value(\"oLambda\", BigO::oLambda)\n      .export_values();\n\n  using benchmark::internal::Benchmark;\n  nb::class_<Benchmark>(m, \"Benchmark\")\n      // For methods returning a pointer to the current object, reference\n      // return policy is used to ask nanobind not to take ownership of the\n      // returned object and avoid calling delete on it.\n      // https://pybind11.readthedocs.io/en/stable/advanced/functions.html#return-value-policies\n      //\n      // For methods taking a const std::vector<...>&, a copy is created\n      // because a it is bound to a Python list.\n      // https://pybind11.readthedocs.io/en/stable/advanced/cast/stl.html\n      .def(\"unit\", &Benchmark::Unit, nb::rv_policy::reference)\n      .def(\"arg\", &Benchmark::Arg, nb::rv_policy::reference)\n      .def(\"args\", &Benchmark::Args, nb::rv_policy::reference)\n      .def(\"range\", &Benchmark::Range, nb::rv_policy::reference,\n           nb::arg(\"start\"), nb::arg(\"limit\"))\n      .def(\"dense_range\", &Benchmark::DenseRange,\n           nb::rv_policy::reference, nb::arg(\"start\"),\n           nb::arg(\"limit\"), nb::arg(\"step\") = 1)\n      .def(\"ranges\", &Benchmark::Ranges, nb::rv_policy::reference)\n      .def(\"args_product\", &Benchmark::ArgsProduct,\n           nb::rv_policy::reference)\n      .def(\"arg_name\", &Benchmark::ArgName, nb::rv_policy::reference)\n      .def(\"arg_names\", &Benchmark::ArgNames,\n           nb::rv_policy::reference)\n      .def(\"range_pair\", &Benchmark::RangePair,\n           nb::rv_policy::reference, nb::arg(\"lo1\"), nb::arg(\"hi1\"),\n           nb::arg(\"lo2\"), nb::arg(\"hi2\"))\n      .def(\"range_multiplier\", &Benchmark::RangeMultiplier,\n           nb::rv_policy::reference)\n      .def(\"min_time\", &Benchmark::MinTime, nb::rv_policy::reference)\n      .def(\"min_warmup_time\", &Benchmark::MinWarmUpTime,\n           nb::rv_policy::reference)\n      .def(\"iterations\", &Benchmark::Iterations,\n           nb::rv_policy::reference)\n      .def(\"repetitions\", &Benchmark::Repetitions,\n           nb::rv_policy::reference)\n      .def(\"report_aggregates_only\", &Benchmark::ReportAggregatesOnly,\n           nb::rv_policy::reference, nb::arg(\"value\") = true)\n      .def(\"display_aggregates_only\", &Benchmark::DisplayAggregatesOnly,\n           nb::rv_policy::reference, nb::arg(\"value\") = true)\n      .def(\"measure_process_cpu_time\", &Benchmark::MeasureProcessCPUTime,\n           nb::rv_policy::reference)\n      .def(\"use_real_time\", &Benchmark::UseRealTime,\n           nb::rv_policy::reference)\n      .def(\"use_manual_time\", &Benchmark::UseManualTime,\n           nb::rv_policy::reference)\n      .def(\n          \"complexity\",\n          (Benchmark * (Benchmark::*)(benchmark::BigO)) & Benchmark::Complexity,\n          nb::rv_policy::reference,\n          nb::arg(\"complexity\") = benchmark::oAuto);\n\n  using benchmark::Counter;\n  nb::class_<Counter> py_counter(m, \"Counter\");\n\n  nb::enum_<Counter::Flags>(py_counter, \"Flags\")\n      .value(\"kDefaults\", Counter::Flags::kDefaults)\n      .value(\"kIsRate\", Counter::Flags::kIsRate)\n      .value(\"kAvgThreads\", Counter::Flags::kAvgThreads)\n      .value(\"kAvgThreadsRate\", Counter::Flags::kAvgThreadsRate)\n      .value(\"kIsIterationInvariant\", Counter::Flags::kIsIterationInvariant)\n      .value(\"kIsIterationInvariantRate\",\n             Counter::Flags::kIsIterationInvariantRate)\n      .value(\"kAvgIterations\", Counter::Flags::kAvgIterations)\n      .value(\"kAvgIterationsRate\", Counter::Flags::kAvgIterationsRate)\n      .value(\"kInvert\", Counter::Flags::kInvert)\n      .export_values()\n      .def(nb::self | nb::self);\n\n  nb::enum_<Counter::OneK>(py_counter, \"OneK\")\n      .value(\"kIs1000\", Counter::OneK::kIs1000)\n      .value(\"kIs1024\", Counter::OneK::kIs1024)\n      .export_values();\n\n  py_counter\n      .def(nb::init<double, Counter::Flags, Counter::OneK>(),\n           nb::arg(\"value\") = 0., nb::arg(\"flags\") = Counter::kDefaults,\n           nb::arg(\"k\") = Counter::kIs1000)\n      .def(\"__init__\", ([](Counter *c, double value) { new (c) Counter(value); }))\n      .def_rw(\"value\", &Counter::value)\n      .def_rw(\"flags\", &Counter::flags)\n      .def_rw(\"oneK\", &Counter::oneK)\n      .def(nb::init_implicit<double>());\n\n  nb::implicitly_convertible<nb::int_, Counter>();\n\n  nb::bind_map<benchmark::UserCounters>(m, \"UserCounters\");\n\n  using benchmark::State;\n  nb::class_<State>(m, \"State\")\n      .def(\"__bool__\", &State::KeepRunning)\n      .def_prop_ro(\"keep_running\", &State::KeepRunning)\n      .def(\"pause_timing\", &State::PauseTiming)\n      .def(\"resume_timing\", &State::ResumeTiming)\n      .def(\"skip_with_error\", &State::SkipWithError)\n      .def_prop_ro(\"error_occurred\", &State::error_occurred)\n      .def(\"set_iteration_time\", &State::SetIterationTime)\n      .def_prop_rw(\"bytes_processed\", &State::bytes_processed,\n                    &State::SetBytesProcessed)\n      .def_prop_rw(\"complexity_n\", &State::complexity_length_n,\n                    &State::SetComplexityN)\n      .def_prop_rw(\"items_processed\", &State::items_processed,\n                   &State::SetItemsProcessed)\n      .def(\"set_label\", &State::SetLabel)\n      .def(\"range\", &State::range, nb::arg(\"pos\") = 0)\n      .def_prop_ro(\"iterations\", &State::iterations)\n      .def_prop_ro(\"name\", &State::name)\n      .def_rw(\"counters\", &State::counters)\n      .def_prop_ro(\"thread_index\", &State::thread_index)\n      .def_prop_ro(\"threads\", &State::threads);\n\n  m.def(\"Initialize\", Initialize);\n  m.def(\"RegisterBenchmark\", RegisterBenchmark,\n        nb::rv_policy::reference);\n  m.def(\"RunSpecifiedBenchmarks\",\n        []() { benchmark::RunSpecifiedBenchmarks(); });\n  m.def(\"ClearRegisteredBenchmarks\", benchmark::ClearRegisteredBenchmarks);\n};\n}  // namespace\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/bindings/python/google_benchmark/example.py",
    "content": "# Copyright 2020 Google Inc. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Example of Python using C++ benchmark framework.\n\nTo run this example, you must first install the `google_benchmark` Python package.\n\nTo install using `setup.py`, download and extract the `google_benchmark` source.\nIn the extracted directory, execute:\n  python setup.py install\n\"\"\"\n\nimport random\nimport time\n\nimport google_benchmark as benchmark\nfrom google_benchmark import Counter\n\n\n@benchmark.register\ndef empty(state):\n    while state:\n        pass\n\n\n@benchmark.register\ndef sum_million(state):\n    while state:\n        sum(range(1_000_000))\n\n@benchmark.register\ndef pause_timing(state):\n    \"\"\"Pause timing every iteration.\"\"\"\n    while state:\n        # Construct a list of random ints every iteration without timing it\n        state.pause_timing()\n        random_list = [random.randint(0, 100) for _ in range(100)]\n        state.resume_timing()\n        # Time the in place sorting algorithm\n        random_list.sort()\n\n\n@benchmark.register\ndef skipped(state):\n    if True:  # Test some predicate here.\n        state.skip_with_error(\"some error\")\n        return  # NOTE: You must explicitly return, or benchmark will continue.\n\n    ...  # Benchmark code would be here.\n\n\n@benchmark.register\ndef manual_timing(state):\n    while state:\n        # Manually count Python CPU time\n        start = time.perf_counter()  # perf_counter_ns() in Python 3.7+\n        # Something to benchmark\n        time.sleep(0.01)\n        end = time.perf_counter()\n        state.set_iteration_time(end - start)\n\n\n@benchmark.register\ndef custom_counters(state):\n    \"\"\"Collect custom metric using benchmark.Counter.\"\"\"\n    num_foo = 0.0\n    while state:\n        # Benchmark some code here\n        pass\n        # Collect some custom metric named foo\n        num_foo += 0.13\n\n    # Automatic Counter from numbers.\n    state.counters[\"foo\"] = num_foo\n    # Set a counter as a rate.\n    state.counters[\"foo_rate\"] = Counter(num_foo, Counter.kIsRate)\n    #  Set a counter as an inverse of rate.\n    state.counters[\"foo_inv_rate\"] = Counter(num_foo, Counter.kIsRate | Counter.kInvert)\n    # Set a counter as a thread-average quantity.\n    state.counters[\"foo_avg\"] = Counter(num_foo, Counter.kAvgThreads)\n    # There's also a combined flag:\n    state.counters[\"foo_avg_rate\"] = Counter(num_foo, Counter.kAvgThreadsRate)\n\n\n@benchmark.register\n@benchmark.option.measure_process_cpu_time()\n@benchmark.option.use_real_time()\ndef with_options(state):\n    while state:\n        sum(range(1_000_000))\n\n\n@benchmark.register(name=\"sum_million_microseconds\")\n@benchmark.option.unit(benchmark.kMicrosecond)\ndef with_options2(state):\n    while state:\n        sum(range(1_000_000))\n\n\n@benchmark.register\n@benchmark.option.arg(100)\n@benchmark.option.arg(1000)\ndef passing_argument(state):\n    while state:\n        sum(range(state.range(0)))\n\n\n@benchmark.register\n@benchmark.option.range(8, limit=8 << 10)\ndef using_range(state):\n    while state:\n        sum(range(state.range(0)))\n\n\n@benchmark.register\n@benchmark.option.range_multiplier(2)\n@benchmark.option.range(1 << 10, 1 << 18)\n@benchmark.option.complexity(benchmark.oN)\ndef computing_complexity(state):\n    while state:\n        sum(range(state.range(0)))\n    state.complexity_n = state.range(0)\n\n\nif __name__ == \"__main__\":\n    benchmark.main()\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/bindings/python/nanobind.BUILD",
    "content": "\nconfig_setting(\n    name = \"msvc_compiler\",\n    flag_values = {\"@bazel_tools//tools/cpp:compiler\": \"msvc-cl\"},\n)\n\ncc_library(\n    name = \"nanobind\",\n    hdrs = glob(\n        include = [\n            \"include/nanobind/*.h\",\n            \"include/nanobind/stl/*.h\",\n            \"include/nanobind/detail/*.h\",\n        ],\n        exclude = [],\n    ),\n    srcs = [\n        \"include/nanobind/stl/detail/nb_dict.h\",\n        \"include/nanobind/stl/detail/nb_list.h\",\n        \"include/nanobind/stl/detail/traits.h\",\n        \"ext/robin_map/include/tsl/robin_map.h\",\n        \"ext/robin_map/include/tsl/robin_hash.h\",\n        \"ext/robin_map/include/tsl/robin_growth_policy.h\",\n        \"ext/robin_map/include/tsl/robin_set.h\",\n        \"src/buffer.h\",\n        \"src/common.cpp\",\n        \"src/error.cpp\",\n        \"src/implicit.cpp\",\n        \"src/nb_enum.cpp\",\n        \"src/nb_func.cpp\",\n        \"src/nb_internals.cpp\",\n        \"src/nb_internals.h\",\n        \"src/nb_ndarray.cpp\",\n        \"src/nb_type.cpp\",\n        \"src/trampoline.cpp\",\n    ],\n    copts = select({\n        \":msvc_compiler\": [],\n        \"//conditions:default\": [\n        \"-fexceptions\",\n        \"-Os\",  # size optimization\n        \"-flto\", # enable LTO\n        ],\n    }),\n    linkopts = select({\n        \"@com_github_google_benchmark//:macos\": [\n        \"-undefined dynamic_lookup\",\n        \"-Wl,-no_fixup_chains\",\n        \"-Wl,-dead_strip\",\n        ],\n        \"//conditions:default\": [],\n    }),\n    includes = [\"include\", \"ext/robin_map/include\"],\n    deps = [\"@python_headers\"],\n    visibility = [\"//visibility:public\"],\n)\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/bindings/python/python_headers.BUILD",
    "content": "cc_library(\n    name = \"python_headers\",\n    hdrs = glob([\"**/*.h\"]),\n    includes = [\".\"],\n    visibility = [\"//visibility:public\"],\n)\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/bindings/python/requirements.txt",
    "content": "absl-py>=0.7.1\n\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/cmake/Config.cmake.in",
    "content": "@PACKAGE_INIT@\n\ninclude (CMakeFindDependencyMacro)\n\nfind_dependency (Threads)\n\ninclude(\"${CMAKE_CURRENT_LIST_DIR}/@targets_export_name@.cmake\")\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/cmake/GoogleTest.cmake.in",
    "content": "cmake_minimum_required(VERSION 2.8.12)\n\nproject(googletest-download NONE)\n\n# Enable ExternalProject CMake module\ninclude(ExternalProject)\n\noption(ALLOW_DOWNLOADING_GOOGLETEST \"If googletest src tree is not found in location specified by GOOGLETEST_PATH, do fetch the archive from internet\" OFF)\nset(GOOGLETEST_PATH \"/usr/src/googletest\" CACHE PATH\n                    \"Path to the googletest root tree. Should contain googletest and googlemock subdirs. And CMakeLists.txt in root, and in both of these subdirs\")\n\n# Download and install GoogleTest\n\nmessage(STATUS \"Looking for Google Test sources\")\nmessage(STATUS \"Looking for Google Test sources in ${GOOGLETEST_PATH}\")\nif(EXISTS \"${GOOGLETEST_PATH}\"            AND IS_DIRECTORY \"${GOOGLETEST_PATH}\"            AND EXISTS \"${GOOGLETEST_PATH}/CMakeLists.txt\" AND\n   EXISTS \"${GOOGLETEST_PATH}/googletest\" AND IS_DIRECTORY \"${GOOGLETEST_PATH}/googletest\" AND EXISTS \"${GOOGLETEST_PATH}/googletest/CMakeLists.txt\" AND\n   EXISTS \"${GOOGLETEST_PATH}/googlemock\" AND IS_DIRECTORY \"${GOOGLETEST_PATH}/googlemock\" AND EXISTS \"${GOOGLETEST_PATH}/googlemock/CMakeLists.txt\")\n  message(STATUS \"Found Google Test in ${GOOGLETEST_PATH}\")\n\n  ExternalProject_Add(\n    googletest\n    PREFIX            \"${CMAKE_BINARY_DIR}\"\n    DOWNLOAD_DIR      \"${CMAKE_BINARY_DIR}/download\"\n    SOURCE_DIR        \"${GOOGLETEST_PATH}\" # use existing src dir.\n    BINARY_DIR        \"${CMAKE_BINARY_DIR}/build\"\n    CONFIGURE_COMMAND \"\"\n    BUILD_COMMAND     \"\"\n    INSTALL_COMMAND   \"\"\n    TEST_COMMAND      \"\"\n  )\nelse()\n  if(NOT ALLOW_DOWNLOADING_GOOGLETEST)\n    message(SEND_ERROR \"Did not find Google Test sources! Either pass correct path in GOOGLETEST_PATH, or enable BENCHMARK_DOWNLOAD_DEPENDENCIES, or disable BENCHMARK_USE_BUNDLED_GTEST, or disable BENCHMARK_ENABLE_GTEST_TESTS / BENCHMARK_ENABLE_TESTING.\")\n    return()\n  else()\n    message(WARNING \"Did not find Google Test sources! Fetching from web...\")\n    ExternalProject_Add(\n      googletest\n      GIT_REPOSITORY    https://github.com/google/googletest.git\n      GIT_TAG           \"release-1.11.0\"\n      PREFIX            \"${CMAKE_BINARY_DIR}\"\n      STAMP_DIR         \"${CMAKE_BINARY_DIR}/stamp\"\n      DOWNLOAD_DIR      \"${CMAKE_BINARY_DIR}/download\"\n      SOURCE_DIR        \"${CMAKE_BINARY_DIR}/src\"\n      BINARY_DIR        \"${CMAKE_BINARY_DIR}/build\"\n      CONFIGURE_COMMAND \"\"\n      BUILD_COMMAND     \"\"\n      INSTALL_COMMAND   \"\"\n      TEST_COMMAND      \"\"\n    )\n  endif()\nendif()\n\nExternalProject_Get_Property(googletest SOURCE_DIR BINARY_DIR)\nfile(WRITE googletest-paths.cmake\n\"set(GOOGLETEST_SOURCE_DIR \\\"${SOURCE_DIR}\\\")\nset(GOOGLETEST_BINARY_DIR \\\"${BINARY_DIR}\\\")\n\")\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/cmake/benchmark.pc.in",
    "content": "prefix=@CMAKE_INSTALL_PREFIX@\nexec_prefix=${prefix}\nlibdir=@CMAKE_INSTALL_FULL_LIBDIR@\nincludedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@\n\nName: @PROJECT_NAME@\nDescription: Google microbenchmark framework\nVersion: @VERSION@\n\nLibs: -L${libdir} -lbenchmark\nLibs.private: -lpthread\nCflags: -I${includedir}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/cmake/gnu_posix_regex.cpp",
    "content": "#include <gnuregex.h>\n#include <string>\nint main() {\n  std::string str = \"test0159\";\n  regex_t re;\n  int ec = regcomp(&re, \"^[a-z]+[0-9]+$\", REG_EXTENDED | REG_NOSUB);\n  if (ec != 0) {\n    return ec;\n  }\n  return regexec(&re, str.c_str(), 0, nullptr, 0) ? -1 : 0;\n}\n\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/cmake/posix_regex.cpp",
    "content": "#include <regex.h>\n#include <string>\nint main() {\n  std::string str = \"test0159\";\n  regex_t re;\n  int ec = regcomp(&re, \"^[a-z]+[0-9]+$\", REG_EXTENDED | REG_NOSUB);\n  if (ec != 0) {\n    return ec;\n  }\n  int ret = regexec(&re, str.c_str(), 0, nullptr, 0) ? -1 : 0;\n  regfree(&re);\n  return ret;\n}\n\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/cmake/pthread_affinity.cpp",
    "content": "#include <pthread.h>\nint main() {\n  cpu_set_t set;\n  CPU_ZERO(&set);\n  for (int i = 0; i < CPU_SETSIZE; ++i) {\n    CPU_SET(i, &set);\n    CPU_CLR(i, &set);\n  }\n  pthread_t self = pthread_self();\n  int ret;\n  ret = pthread_getaffinity_np(self, sizeof(set), &set);\n  if (ret != 0) return ret;\n  ret = pthread_setaffinity_np(self, sizeof(set), &set);\n  if (ret != 0) return ret;\n  return 0;\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/cmake/std_regex.cpp",
    "content": "#include <regex>\n#include <string>\nint main() {\n  const std::string str = \"test0159\";\n  std::regex re;\n  re = std::regex(\"^[a-z]+[0-9]+$\",\n       std::regex_constants::extended | std::regex_constants::nosubs);\n  return std::regex_search(str, re) ? 0 : -1;\n}\n\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/cmake/steady_clock.cpp",
    "content": "#include <chrono>\n\nint main() {\n    typedef std::chrono::steady_clock Clock;\n    Clock::time_point tp = Clock::now();\n    ((void)tp);\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/cmake/thread_safety_attributes.cpp",
    "content": "#define HAVE_THREAD_SAFETY_ATTRIBUTES\n#include \"../src/mutex.h\"\n\nint main() {}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/docs/AssemblyTests.md",
    "content": "# Assembly Tests\n\nThe Benchmark library provides a number of functions whose primary\npurpose in to affect assembly generation, including `DoNotOptimize`\nand `ClobberMemory`. In addition there are other functions,\nsuch as `KeepRunning`, for which generating good assembly is paramount.\n\nFor these functions it's important to have tests that verify the\ncorrectness and quality of the implementation. This requires testing\nthe code generated by the compiler.\n\nThis document describes how the Benchmark library tests compiler output,\nas well as how to properly write new tests.\n\n\n## Anatomy of a Test\n\nWriting a test has two steps:\n\n* Write the code you want to generate assembly for.\n* Add `// CHECK` lines to match against the verified assembly.\n\nExample:\n```c++\n\n// CHECK-LABEL: test_add:\nextern \"C\" int test_add() {\n    extern int ExternInt;\n    return ExternInt + 1;\n\n    // CHECK: movl ExternInt(%rip), %eax\n    // CHECK: addl %eax\n    // CHECK: ret\n}\n\n```\n\n#### LLVM Filecheck\n\n[LLVM's Filecheck](https://llvm.org/docs/CommandGuide/FileCheck.html)\nis used to test the generated assembly against the `// CHECK` lines\nspecified in the tests source file. Please see the documentation\nlinked above for information on how to write `CHECK` directives.\n\n#### Tips and Tricks:\n\n* Tests should match the minimal amount of output required to establish\ncorrectness. `CHECK` directives don't have to match on the exact next line\nafter the previous match, so tests should omit checks for unimportant\nbits of assembly. ([`CHECK-NEXT`](https://llvm.org/docs/CommandGuide/FileCheck.html#the-check-next-directive)\ncan be used to ensure a match occurs exactly after the previous match).\n\n* The tests are compiled with `-O3 -g0`. So we're only testing the\noptimized output.\n\n* The assembly output is further cleaned up using `tools/strip_asm.py`.\nThis removes comments, assembler directives, and unused labels before\nthe test is run.\n\n* The generated and stripped assembly file for a test is output under\n`<build-directory>/test/<test-name>.s`\n\n* Filecheck supports using [`CHECK` prefixes](https://llvm.org/docs/CommandGuide/FileCheck.html#cmdoption-check-prefixes)\nto specify lines that should only match in certain situations.\nThe Benchmark tests use `CHECK-CLANG` and `CHECK-GNU` for lines that\nare only expected to match Clang or GCC's output respectively. Normal\n`CHECK` lines match against all compilers. (Note: `CHECK-NOT` and\n`CHECK-LABEL` are NOT prefixes. They are versions of non-prefixed\n`CHECK` lines)\n\n* Use `extern \"C\"` to disable name mangling for specific functions. This\nmakes them easier to name in the `CHECK` lines.\n\n\n## Problems Writing Portable Tests\n\nWriting tests which check the code generated by a compiler are\ninherently non-portable. Different compilers and even different compiler\nversions may generate entirely different code. The Benchmark tests\nmust tolerate this.\n\nLLVM Filecheck provides a number of mechanisms to help write\n\"more portable\" tests; including [matching using regular expressions](https://llvm.org/docs/CommandGuide/FileCheck.html#filecheck-pattern-matching-syntax),\nallowing the creation of [named variables](https://llvm.org/docs/CommandGuide/FileCheck.html#filecheck-variables)\nfor later matching, and [checking non-sequential matches](https://llvm.org/docs/CommandGuide/FileCheck.html#the-check-dag-directive).\n\n#### Capturing Variables\n\nFor example, say GCC stores a variable in a register but Clang stores\nit in memory. To write a test that tolerates both cases we \"capture\"\nthe destination of the store, and then use the captured expression\nto write the remainder of the test.\n\n```c++\n// CHECK-LABEL: test_div_no_op_into_shr:\nextern \"C\" void test_div_no_op_into_shr(int value) {\n    int divisor = 2;\n    benchmark::DoNotOptimize(divisor); // hide the value from the optimizer\n    return value / divisor;\n\n    // CHECK: movl $2, [[DEST:.*]]\n    // CHECK: idivl [[DEST]]\n    // CHECK: ret\n}\n```\n\n#### Using Regular Expressions to Match Differing Output\n\nOften tests require testing assembly lines which may subtly differ\nbetween compilers or compiler versions. A common example of this\nis matching stack frame addresses. In this case regular expressions\ncan be used to match the differing bits of output. For example:\n\n<!-- {% raw %} -->\n```c++\nint ExternInt;\nstruct Point { int x, y, z; };\n\n// CHECK-LABEL: test_store_point:\nextern \"C\" void test_store_point() {\n    Point p{ExternInt, ExternInt, ExternInt};\n    benchmark::DoNotOptimize(p);\n\n    // CHECK: movl ExternInt(%rip), %eax\n    // CHECK: movl %eax, -{{[0-9]+}}(%rsp)\n    // CHECK: movl %eax, -{{[0-9]+}}(%rsp)\n    // CHECK: movl %eax, -{{[0-9]+}}(%rsp)\n    // CHECK: ret\n}\n```\n<!-- {% endraw %} -->\n\n## Current Requirements and Limitations\n\nThe tests require Filecheck to be installed along the `PATH` of the\nbuild machine. Otherwise the tests will be disabled.\n\nAdditionally, as mentioned in the previous section, codegen tests are\ninherently non-portable. Currently the tests are limited to:\n\n* x86_64 targets.\n* Compiled with GCC or Clang\n\nFurther work could be done, at least on a limited basis, to extend the\ntests to other architectures and compilers (using `CHECK` prefixes).\n\nFurthermore, the tests fail for builds which specify additional flags\nthat modify code generation, including `--coverage` or `-fsanitize=`.\n\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/docs/_config.yml",
    "content": "theme: jekyll-theme-minimal\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/docs/dependencies.md",
    "content": "# Build tool dependency policy\n\nWe follow the [Foundational C++ support policy](https://opensource.google/documentation/policies/cplusplus-support) for our build tools. In\nparticular the [\"Build Systems\" section](https://opensource.google/documentation/policies/cplusplus-support#build-systems).\n\n## CMake\n\nThe current supported version is CMake 3.10 as of 2023-08-10. Most modern\ndistributions include newer versions, for example:\n\n* Ubuntu 20.04 provides CMake 3.16.3\n* Debian 11.4 provides CMake 3.18.4\n* Ubuntu 22.04 provides CMake 3.22.1\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/docs/index.md",
    "content": "# Benchmark\n\n* [Assembly Tests](AssemblyTests.md)\n* [Dependencies](dependencies.md)\n* [Perf Counters](perf_counters.md)\n* [Platform Specific Build Instructions](platform_specific_build_instructions.md)\n* [Python Bindings](python_bindings.md)\n* [Random Interleaving](random_interleaving.md)\n* [Reducing Variance](reducing_variance.md)\n* [Releasing](releasing.md)\n* [Tools](tools.md)\n* [User Guide](user_guide.md)\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/docs/perf_counters.md",
    "content": "<a name=\"perf-counters\" />\n\n# User-Requested Performance Counters\n\nWhen running benchmarks, the user may choose to request collection of\nperformance counters. This may be useful in investigation scenarios - narrowing\ndown the cause of a regression; or verifying that the underlying cause of a\nperformance improvement matches expectations.\n\nThis feature is available if:\n\n* The benchmark is run on an architecture featuring a Performance Monitoring\n  Unit (PMU),\n* The benchmark is compiled with support for collecting counters. Currently,\n  this requires [libpfm](http://perfmon2.sourceforge.net/), which is built as a\n  dependency via Bazel.\n\nThe feature does not require modifying benchmark code. Counter collection is\nhandled at the boundaries where timer collection is also handled. \n\nTo opt-in:\n* If using a Bazel build, add `--define pfm=1` to your build flags\n* If using CMake:\n  * Install `libpfm4-dev`, e.g. `apt-get install libpfm4-dev`.\n  * Enable the CMake flag `BENCHMARK_ENABLE_LIBPFM` in `CMakeLists.txt`.\n\nTo use, pass a comma-separated list of counter names through the\n`--benchmark_perf_counters` flag. The names are decoded through libpfm - meaning,\nthey are platform specific, but some (e.g. `CYCLES` or `INSTRUCTIONS`) are\nmapped by libpfm to platform-specifics - see libpfm\n[documentation](http://perfmon2.sourceforge.net/docs.html) for more details.\n\nThe counter values are reported back through the [User Counters](../README.md#custom-counters)\nmechanism, meaning, they are available in all the formats (e.g. JSON) supported\nby User Counters.\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/docs/platform_specific_build_instructions.md",
    "content": "# Platform Specific Build Instructions\n\n## Building with GCC\n\nWhen the library is built using GCC it is necessary to link with the pthread\nlibrary due to how GCC implements `std::thread`. Failing to link to pthread will\nlead to runtime exceptions (unless you're using libc++), not linker errors. See\n[issue #67](https://github.com/google/benchmark/issues/67) for more details. You\ncan link to pthread by adding `-pthread` to your linker command. Note, you can\nalso use `-lpthread`, but there are potential issues with ordering of command\nline parameters if you use that.\n\nOn QNX, the pthread library is part of libc and usually included automatically\n(see\n[`pthread_create()`](https://www.qnx.com/developers/docs/7.1/index.html#com.qnx.doc.neutrino.lib_ref/topic/p/pthread_create.html)).\nThere's no separate pthread library to link.\n\n## Building with Visual Studio 2015 or 2017\n\nThe `shlwapi` library (`-lshlwapi`) is required to support a call to `CPUInfo` which reads the registry. Either add `shlwapi.lib` under `[ Configuration Properties > Linker > Input ]`, or use the following:\n\n```\n// Alternatively, can add libraries using linker options.\n#ifdef _WIN32\n#pragma comment ( lib, \"Shlwapi.lib\" )\n#ifdef _DEBUG\n#pragma comment ( lib, \"benchmarkd.lib\" )\n#else\n#pragma comment ( lib, \"benchmark.lib\" )\n#endif\n#endif\n```\n\nCan also use the graphical version of CMake:\n* Open `CMake GUI`.\n* Under `Where to build the binaries`, same path as source plus `build`.\n* Under `CMAKE_INSTALL_PREFIX`, same path as source plus `install`.\n* Click `Configure`, `Generate`, `Open Project`.\n* If build fails, try deleting entire directory and starting again, or unticking options to build less.\n\n## Building with Intel 2015 Update 1 or Intel System Studio Update 4\n\nSee instructions for building with Visual Studio. Once built, right click on the solution and change the build to Intel.\n\n## Building on Solaris\n\nIf you're running benchmarks on solaris, you'll want the kstat library linked in\ntoo (`-lkstat`)."
  },
  {
    "path": "3rd/benchmark-1.8.2/docs/python_bindings.md",
    "content": "# Building and installing Python bindings\n\nPython bindings are available as wheels on [PyPI](https://pypi.org/project/google-benchmark/) for importing and \nusing Google Benchmark directly in Python. \nCurrently, pre-built wheels exist for macOS (both ARM64 and Intel x86), Linux x86-64 and 64-bit Windows.\nSupported Python versions are Python 3.7 - 3.10.\n\nTo install Google Benchmark's Python bindings, run:\n\n```bash\npython -m pip install --upgrade pip  # for manylinux2014 support\npython -m pip install google-benchmark\n```\n\nIn order to keep your system Python interpreter clean, it is advisable to run these commands in a virtual\nenvironment. See the [official Python documentation](https://docs.python.org/3/library/venv.html) \non how to create virtual environments.\n\nTo build a wheel directly from source, you can follow these steps:\n```bash\ngit clone https://github.com/google/benchmark.git\ncd benchmark\n# create a virtual environment and activate it\npython3 -m venv venv --system-site-packages\nsource venv/bin/activate  # .\\venv\\Scripts\\Activate.ps1 on Windows\n\n# upgrade Python's system-wide packages\npython -m pip install --upgrade pip setuptools wheel\n# builds the wheel and stores it in the directory \"wheelhouse\".\npython -m pip wheel . -w wheelhouse\n```\n\nNB: Building wheels from source requires Bazel. For platform-specific instructions on how to install Bazel,\nrefer to the [Bazel installation docs](https://bazel.build/install).\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/docs/random_interleaving.md",
    "content": "<a name=\"interleaving\" />\n\n# Random Interleaving\n\n[Random Interleaving](https://github.com/google/benchmark/issues/1051) is a\ntechnique to lower run-to-run variance. It randomly interleaves repetitions of a\nmicrobenchmark with repetitions from other microbenchmarks in the same benchmark\ntest. Data shows it is able to lower run-to-run variance by\n[40%](https://github.com/google/benchmark/issues/1051) on average.\n\nTo use, you mainly need to set `--benchmark_enable_random_interleaving=true`,\nand optionally specify non-zero repetition count `--benchmark_repetitions=9`\nand optionally decrease the per-repetition time `--benchmark_min_time=0.1`.\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/docs/reducing_variance.md",
    "content": "# Reducing Variance\n\n<a name=\"disabling-cpu-frequency-scaling\" />\n\n## Disabling CPU Frequency Scaling\n\nIf you see this error:\n\n```\n***WARNING*** CPU scaling is enabled, the benchmark real time measurements may be noisy and will incur extra overhead.\n```\n\nyou might want to disable the CPU frequency scaling while running the\nbenchmark, as well as consider other ways to stabilize the performance of\nyour system while benchmarking.\n\nSee [Reducing Variance](reducing_variance.md) for more information.\n\nExactly how to do this depends on the Linux distribution,\ndesktop environment, and installed programs.  Specific details are a moving\ntarget, so we will not attempt to exhaustively document them here.\n\nOne simple option is to use the `cpupower` program to change the\nperformance governor to \"performance\".  This tool is maintained along with\nthe Linux kernel and provided by your distribution.\n\nIt must be run as root, like this:\n\n```bash\nsudo cpupower frequency-set --governor performance\n```\n\nAfter this you can verify that all CPUs are using the performance governor\nby running this command:\n\n```bash\ncpupower frequency-info -o proc\n```\n\nThe benchmarks you subsequently run will have less variance.\n\n<a name=\"reducing-variance\" />\n\n## Reducing Variance in Benchmarks\n\nThe Linux CPU frequency governor [discussed\nabove](user_guide#disabling-cpu-frequency-scaling) is not the only source\nof noise in benchmarks.  Some, but not all, of the sources of variance\ninclude:\n\n1. On multi-core machines not all CPUs/CPU cores/CPU threads run the same\n   speed, so running a benchmark one time and then again may give a\n   different result depending on which CPU it ran on.\n2. CPU scaling features that run on the CPU, like Intel's Turbo Boost and\n   AMD Turbo Core and Precision Boost, can temporarily change the CPU\n   frequency even when the using the \"performance\" governor on Linux.\n3. Context switching between CPUs, or scheduling competition on the CPU the\n   benchmark is running on.\n4. Intel Hyperthreading or AMD SMT causing the same issue as above.\n5. Cache effects caused by code running on other CPUs.\n6. Non-uniform memory architectures (NUMA).\n\nThese can cause variance in benchmarks results within a single run\n(`--benchmark_repetitions=N`) or across multiple runs of the benchmark\nprogram.\n\nReducing sources of variance is OS and architecture dependent, which is one\nreason some companies maintain machines dedicated to performance testing.\n\nSome of the easier and and effective ways of reducing variance on a typical\nLinux workstation are:\n\n1. Use the performance governor as [discussed\nabove](user_guide#disabling-cpu-frequency-scaling).\n1. Disable processor boosting by:\n   ```sh\n   echo 0 | sudo tee /sys/devices/system/cpu/cpufreq/boost\n   ```\n   See the Linux kernel's\n   [boost.txt](https://www.kernel.org/doc/Documentation/cpu-freq/boost.txt)\n   for more information.\n2. Set the benchmark program's task affinity to a fixed cpu.  For example:\n   ```sh\n   taskset -c 0 ./mybenchmark\n   ```\n3. Disabling Hyperthreading/SMT.  This can be done in the Bios or using the\n   `/sys` file system (see the LLVM project's [Benchmarking\n   tips](https://llvm.org/docs/Benchmarking.html)).\n4. Close other programs that do non-trivial things based on timers, such as\n   your web browser, desktop environment, etc.\n5. Reduce the working set of your benchmark to fit within the L1 cache, but\n   do be aware that this may lead you to optimize for an unrelistic\n   situation.\n\nFurther resources on this topic:\n\n1. The LLVM project's [Benchmarking\n   tips](https://llvm.org/docs/Benchmarking.html).\n1. The Arch Wiki [Cpu frequency\nscaling](https://wiki.archlinux.org/title/CPU_frequency_scaling) page.\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/docs/releasing.md",
    "content": "# How to release\n\n* Make sure you're on main and synced to HEAD\n* Ensure the project builds and tests run\n    * `parallel -j0 exec ::: test/*_test` can help ensure everything at least\n      passes\n* Prepare release notes\n    * `git log $(git describe --abbrev=0 --tags)..HEAD` gives you the list of\n      commits between the last annotated tag and HEAD\n    * Pick the most interesting.\n* Create one last commit that updates the version saved in `CMakeLists.txt`, `MODULE.bazel`\n  and the `__version__` variable in `bindings/python/google_benchmark/__init__.py`to the\n  release version you're creating. (This version will be used if benchmark is installed\n  from the archive you'll be creating in the next step.)\n\n```\nproject (benchmark VERSION 1.8.0 LANGUAGES CXX)\n```\n\n```\nmodule(name = \"com_github_google_benchmark\", version=\"1.8.0\")\n```\n\n```python\n# bindings/python/google_benchmark/__init__.py\n\n# ...\n\n__version__ = \"1.8.0\"  # <-- change this to the release version you are creating\n\n# ...\n```\n\n* Create a release through github's interface\n    * Note this will create a lightweight tag.\n    * Update this to an annotated tag:\n      * `git pull --tags`\n      * `git tag -a -f <tag> <tag>`\n      * `git push --force --tags origin`\n* Confirm that the \"Build and upload Python wheels\" action runs to completion\n    * run it manually if it hasn't run\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/docs/tools.md",
    "content": "# Benchmark Tools\n\n## compare.py\n\nThe `compare.py` can be used to compare the result of benchmarks.\n\n### Dependencies\nThe utility relies on the [scipy](https://www.scipy.org) package which can be installed using pip:\n```bash\npip3 install -r requirements.txt\n```\n\n### Displaying aggregates only\n\nThe switch `-a` / `--display_aggregates_only` can be used to control the\ndisplayment of the normal iterations vs the aggregates. When passed, it will\nbe passthrough to the benchmark binaries to be run, and will be accounted for\nin the tool itself; only the aggregates will be displayed, but not normal runs.\nIt only affects the display, the separate runs will still be used to calculate\nthe U test.\n\n### Modes of operation\n\nThere are three modes of operation:\n\n1. Just compare two benchmarks\nThe program is invoked like:\n\n``` bash\n$ compare.py benchmarks <benchmark_baseline> <benchmark_contender> [benchmark options]...\n```\nWhere `<benchmark_baseline>` and `<benchmark_contender>` either specify a benchmark executable file, or a JSON output file. The type of the input file is automatically detected. If a benchmark executable is specified then the benchmark is run to obtain the results. Otherwise the results are simply loaded from the output file.\n\n`[benchmark options]` will be passed to the benchmarks invocations. They can be anything that binary accepts, be it either normal `--benchmark_*` parameters, or some custom parameters your binary takes.\n\nExample output:\n```\n$ ./compare.py benchmarks ./a.out ./a.out\nRUNNING: ./a.out --benchmark_out=/tmp/tmprBT5nW\nRun on (8 X 4000 MHz CPU s)\n2017-11-07 21:16:44\n------------------------------------------------------\nBenchmark               Time           CPU Iterations\n------------------------------------------------------\nBM_memcpy/8            36 ns         36 ns   19101577   211.669MB/s\nBM_memcpy/64           76 ns         76 ns    9412571   800.199MB/s\nBM_memcpy/512          84 ns         84 ns    8249070   5.64771GB/s\nBM_memcpy/1024        116 ns        116 ns    6181763   8.19505GB/s\nBM_memcpy/8192        643 ns        643 ns    1062855   11.8636GB/s\nBM_copy/8             222 ns        222 ns    3137987   34.3772MB/s\nBM_copy/64           1608 ns       1608 ns     432758   37.9501MB/s\nBM_copy/512         12589 ns      12589 ns      54806   38.7867MB/s\nBM_copy/1024        25169 ns      25169 ns      27713   38.8003MB/s\nBM_copy/8192       201165 ns     201112 ns       3486   38.8466MB/s\nRUNNING: ./a.out --benchmark_out=/tmp/tmpt1wwG_\nRun on (8 X 4000 MHz CPU s)\n2017-11-07 21:16:53\n------------------------------------------------------\nBenchmark               Time           CPU Iterations\n------------------------------------------------------\nBM_memcpy/8            36 ns         36 ns   19397903   211.255MB/s\nBM_memcpy/64           73 ns         73 ns    9691174   839.635MB/s\nBM_memcpy/512          85 ns         85 ns    8312329   5.60101GB/s\nBM_memcpy/1024        118 ns        118 ns    6438774   8.11608GB/s\nBM_memcpy/8192        656 ns        656 ns    1068644   11.6277GB/s\nBM_copy/8             223 ns        223 ns    3146977   34.2338MB/s\nBM_copy/64           1611 ns       1611 ns     435340   37.8751MB/s\nBM_copy/512         12622 ns      12622 ns      54818   38.6844MB/s\nBM_copy/1024        25257 ns      25239 ns      27779   38.6927MB/s\nBM_copy/8192       205013 ns     205010 ns       3479    38.108MB/s\nComparing ./a.out to ./a.out\nBenchmark                 Time             CPU      Time Old      Time New       CPU Old       CPU New\n------------------------------------------------------------------------------------------------------\nBM_memcpy/8            +0.0020         +0.0020            36            36            36            36\nBM_memcpy/64           -0.0468         -0.0470            76            73            76            73\nBM_memcpy/512          +0.0081         +0.0083            84            85            84            85\nBM_memcpy/1024         +0.0098         +0.0097           116           118           116           118\nBM_memcpy/8192         +0.0200         +0.0203           643           656           643           656\nBM_copy/8              +0.0046         +0.0042           222           223           222           223\nBM_copy/64             +0.0020         +0.0020          1608          1611          1608          1611\nBM_copy/512            +0.0027         +0.0026         12589         12622         12589         12622\nBM_copy/1024           +0.0035         +0.0028         25169         25257         25169         25239\nBM_copy/8192           +0.0191         +0.0194        201165        205013        201112        205010\n```\n\nWhat it does is for the every benchmark from the first run it looks for the benchmark with exactly the same name in the second run, and then compares the results. If the names differ, the benchmark is omitted from the diff.\nAs you can note, the values in `Time` and `CPU` columns are calculated as `(new - old) / |old|`.\n\n2. Compare two different filters of one benchmark\nThe program is invoked like:\n\n``` bash\n$ compare.py filters <benchmark> <filter_baseline> <filter_contender> [benchmark options]...\n```\nWhere `<benchmark>` either specify a benchmark executable file, or a JSON output file. The type of the input file is automatically detected. If a benchmark executable is specified then the benchmark is run to obtain the results. Otherwise the results are simply loaded from the output file.\n\nWhere `<filter_baseline>` and `<filter_contender>` are the same regex filters that you would pass to the `[--benchmark_filter=<regex>]` parameter of the benchmark binary.\n\n`[benchmark options]` will be passed to the benchmarks invocations. They can be anything that binary accepts, be it either normal `--benchmark_*` parameters, or some custom parameters your binary takes.\n\nExample output:\n```\n$ ./compare.py filters ./a.out BM_memcpy BM_copy\nRUNNING: ./a.out --benchmark_filter=BM_memcpy --benchmark_out=/tmp/tmpBWKk0k\nRun on (8 X 4000 MHz CPU s)\n2017-11-07 21:37:28\n------------------------------------------------------\nBenchmark               Time           CPU Iterations\n------------------------------------------------------\nBM_memcpy/8            36 ns         36 ns   17891491   211.215MB/s\nBM_memcpy/64           74 ns         74 ns    9400999   825.646MB/s\nBM_memcpy/512          87 ns         87 ns    8027453   5.46126GB/s\nBM_memcpy/1024        111 ns        111 ns    6116853    8.5648GB/s\nBM_memcpy/8192        657 ns        656 ns    1064679   11.6247GB/s\nRUNNING: ./a.out --benchmark_filter=BM_copy --benchmark_out=/tmp/tmpAvWcOM\nRun on (8 X 4000 MHz CPU s)\n2017-11-07 21:37:33\n----------------------------------------------------\nBenchmark             Time           CPU Iterations\n----------------------------------------------------\nBM_copy/8           227 ns        227 ns    3038700   33.6264MB/s\nBM_copy/64         1640 ns       1640 ns     426893   37.2154MB/s\nBM_copy/512       12804 ns      12801 ns      55417   38.1444MB/s\nBM_copy/1024      25409 ns      25407 ns      27516   38.4365MB/s\nBM_copy/8192     202986 ns     202990 ns       3454   38.4871MB/s\nComparing BM_memcpy to BM_copy (from ./a.out)\nBenchmark                               Time             CPU      Time Old      Time New       CPU Old       CPU New\n--------------------------------------------------------------------------------------------------------------------\n[BM_memcpy vs. BM_copy]/8            +5.2829         +5.2812            36           227            36           227\n[BM_memcpy vs. BM_copy]/64          +21.1719        +21.1856            74          1640            74          1640\n[BM_memcpy vs. BM_copy]/512        +145.6487       +145.6097            87         12804            87         12801\n[BM_memcpy vs. BM_copy]/1024       +227.1860       +227.1776           111         25409           111         25407\n[BM_memcpy vs. BM_copy]/8192       +308.1664       +308.2898           657        202986           656        202990\n```\n\nAs you can see, it applies filter to the benchmarks, both when running the benchmark, and before doing the diff. And to make the diff work, the matches are replaced with some common string. Thus, you can compare two different benchmark families within one benchmark binary.\nAs you can note, the values in `Time` and `CPU` columns are calculated as `(new - old) / |old|`.\n\n3. Compare filter one from benchmark one to filter two from benchmark two:\nThe program is invoked like:\n\n``` bash\n$ compare.py filters <benchmark_baseline> <filter_baseline> <benchmark_contender> <filter_contender> [benchmark options]...\n```\n\nWhere `<benchmark_baseline>` and `<benchmark_contender>` either specify a benchmark executable file, or a JSON output file. The type of the input file is automatically detected. If a benchmark executable is specified then the benchmark is run to obtain the results. Otherwise the results are simply loaded from the output file.\n\nWhere `<filter_baseline>` and `<filter_contender>` are the same regex filters that you would pass to the `[--benchmark_filter=<regex>]` parameter of the benchmark binary.\n\n`[benchmark options]` will be passed to the benchmarks invocations. They can be anything that binary accepts, be it either normal `--benchmark_*` parameters, or some custom parameters your binary takes.\n\nExample output:\n```\n$ ./compare.py benchmarksfiltered ./a.out BM_memcpy ./a.out BM_copy\nRUNNING: ./a.out --benchmark_filter=BM_memcpy --benchmark_out=/tmp/tmp_FvbYg\nRun on (8 X 4000 MHz CPU s)\n2017-11-07 21:38:27\n------------------------------------------------------\nBenchmark               Time           CPU Iterations\n------------------------------------------------------\nBM_memcpy/8            37 ns         37 ns   18953482   204.118MB/s\nBM_memcpy/64           74 ns         74 ns    9206578   828.245MB/s\nBM_memcpy/512          91 ns         91 ns    8086195   5.25476GB/s\nBM_memcpy/1024        120 ns        120 ns    5804513   7.95662GB/s\nBM_memcpy/8192        664 ns        664 ns    1028363   11.4948GB/s\nRUNNING: ./a.out --benchmark_filter=BM_copy --benchmark_out=/tmp/tmpDfL5iE\nRun on (8 X 4000 MHz CPU s)\n2017-11-07 21:38:32\n----------------------------------------------------\nBenchmark             Time           CPU Iterations\n----------------------------------------------------\nBM_copy/8           230 ns        230 ns    2985909   33.1161MB/s\nBM_copy/64         1654 ns       1653 ns     419408   36.9137MB/s\nBM_copy/512       13122 ns      13120 ns      53403   37.2156MB/s\nBM_copy/1024      26679 ns      26666 ns      26575   36.6218MB/s\nBM_copy/8192     215068 ns     215053 ns       3221   36.3283MB/s\nComparing BM_memcpy (from ./a.out) to BM_copy (from ./a.out)\nBenchmark                               Time             CPU      Time Old      Time New       CPU Old       CPU New\n--------------------------------------------------------------------------------------------------------------------\n[BM_memcpy vs. BM_copy]/8            +5.1649         +5.1637            37           230            37           230\n[BM_memcpy vs. BM_copy]/64          +21.4352        +21.4374            74          1654            74          1653\n[BM_memcpy vs. BM_copy]/512        +143.6022       +143.5865            91         13122            91         13120\n[BM_memcpy vs. BM_copy]/1024       +221.5903       +221.4790           120         26679           120         26666\n[BM_memcpy vs. BM_copy]/8192       +322.9059       +323.0096           664        215068           664        215053\n```\nThis is a mix of the previous two modes, two (potentially different) benchmark binaries are run, and a different filter is applied to each one.\nAs you can note, the values in `Time` and `CPU` columns are calculated as `(new - old) / |old|`.\n\n### U test\n\nIf there is a sufficient repetition count of the benchmarks, the tool can do\na [U Test](https://en.wikipedia.org/wiki/Mann%E2%80%93Whitney_U_test), of the\nnull hypothesis that it is equally likely that a randomly selected value from\none sample will be less than or greater than a randomly selected value from a\nsecond sample.\n\nIf the calculated p-value is below this value is lower than the significance\nlevel alpha, then the result is said to be statistically significant and the\nnull hypothesis is rejected. Which in other words means that the two benchmarks\naren't identical.\n\n**WARNING**: requires **LARGE** (no less than 9) number of repetitions to be\nmeaningful!\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/docs/user_guide.md",
    "content": "# User Guide\n\n## Command Line\n\n[Output Formats](#output-formats)\n\n[Output Files](#output-files)\n\n[Running Benchmarks](#running-benchmarks)\n\n[Running a Subset of Benchmarks](#running-a-subset-of-benchmarks)\n\n[Result Comparison](#result-comparison)\n\n[Extra Context](#extra-context)\n\n## Library\n\n[Runtime and Reporting Considerations](#runtime-and-reporting-considerations)\n\n[Setup/Teardown](#setupteardown)\n\n[Passing Arguments](#passing-arguments)\n\n[Custom Benchmark Name](#custom-benchmark-name)\n\n[Calculating Asymptotic Complexity](#asymptotic-complexity)\n\n[Templated Benchmarks](#templated-benchmarks)\n\n[Fixtures](#fixtures)\n\n[Custom Counters](#custom-counters)\n\n[Multithreaded Benchmarks](#multithreaded-benchmarks)\n\n[CPU Timers](#cpu-timers)\n\n[Manual Timing](#manual-timing)\n\n[Setting the Time Unit](#setting-the-time-unit)\n\n[Random Interleaving](random_interleaving.md)\n\n[User-Requested Performance Counters](perf_counters.md)\n\n[Preventing Optimization](#preventing-optimization)\n\n[Reporting Statistics](#reporting-statistics)\n\n[Custom Statistics](#custom-statistics)\n\n[Memory Usage](#memory-usage)\n\n[Using RegisterBenchmark](#using-register-benchmark)\n\n[Exiting with an Error](#exiting-with-an-error)\n\n[A Faster `KeepRunning` Loop](#a-faster-keep-running-loop)\n\n## Benchmarking Tips\n\n[Disabling CPU Frequency Scaling](#disabling-cpu-frequency-scaling)\n\n[Reducing Variance in Benchmarks](reducing_variance.md)\n\n<a name=\"output-formats\" />\n\n## Output Formats\n\nThe library supports multiple output formats. Use the\n`--benchmark_format=<console|json|csv>` flag (or set the\n`BENCHMARK_FORMAT=<console|json|csv>` environment variable) to set\nthe format type. `console` is the default format.\n\nThe Console format is intended to be a human readable format. By default\nthe format generates color output. Context is output on stderr and the\ntabular data on stdout. Example tabular output looks like:\n\n```\nBenchmark                               Time(ns)    CPU(ns) Iterations\n----------------------------------------------------------------------\nBM_SetInsert/1024/1                        28928      29349      23853  133.097kB/s   33.2742k items/s\nBM_SetInsert/1024/8                        32065      32913      21375  949.487kB/s   237.372k items/s\nBM_SetInsert/1024/10                       33157      33648      21431  1.13369MB/s   290.225k items/s\n```\n\nThe JSON format outputs human readable json split into two top level attributes.\nThe `context` attribute contains information about the run in general, including\ninformation about the CPU and the date.\nThe `benchmarks` attribute contains a list of every benchmark run. Example json\noutput looks like:\n\n```json\n{\n  \"context\": {\n    \"date\": \"2015/03/17-18:40:25\",\n    \"num_cpus\": 40,\n    \"mhz_per_cpu\": 2801,\n    \"cpu_scaling_enabled\": false,\n    \"build_type\": \"debug\"\n  },\n  \"benchmarks\": [\n    {\n      \"name\": \"BM_SetInsert/1024/1\",\n      \"iterations\": 94877,\n      \"real_time\": 29275,\n      \"cpu_time\": 29836,\n      \"bytes_per_second\": 134066,\n      \"items_per_second\": 33516\n    },\n    {\n      \"name\": \"BM_SetInsert/1024/8\",\n      \"iterations\": 21609,\n      \"real_time\": 32317,\n      \"cpu_time\": 32429,\n      \"bytes_per_second\": 986770,\n      \"items_per_second\": 246693\n    },\n    {\n      \"name\": \"BM_SetInsert/1024/10\",\n      \"iterations\": 21393,\n      \"real_time\": 32724,\n      \"cpu_time\": 33355,\n      \"bytes_per_second\": 1199226,\n      \"items_per_second\": 299807\n    }\n  ]\n}\n```\n\nThe CSV format outputs comma-separated values. The `context` is output on stderr\nand the CSV itself on stdout. Example CSV output looks like:\n\n```\nname,iterations,real_time,cpu_time,bytes_per_second,items_per_second,label\n\"BM_SetInsert/1024/1\",65465,17890.7,8407.45,475768,118942,\n\"BM_SetInsert/1024/8\",116606,18810.1,9766.64,3.27646e+06,819115,\n\"BM_SetInsert/1024/10\",106365,17238.4,8421.53,4.74973e+06,1.18743e+06,\n```\n\n<a name=\"output-files\" />\n\n## Output Files\n\nWrite benchmark results to a file with the `--benchmark_out=<filename>` option\n(or set `BENCHMARK_OUT`). Specify the output format with\n`--benchmark_out_format={json|console|csv}` (or set\n`BENCHMARK_OUT_FORMAT={json|console|csv}`). Note that the 'csv' reporter is\ndeprecated and the saved `.csv` file\n[is not parsable](https://github.com/google/benchmark/issues/794) by csv\nparsers.\n\nSpecifying `--benchmark_out` does not suppress the console output.\n\n<a name=\"running-benchmarks\" />\n\n## Running Benchmarks\n\nBenchmarks are executed by running the produced binaries. Benchmarks binaries,\nby default, accept options that may be specified either through their command\nline interface or by setting environment variables before execution. For every\n`--option_flag=<value>` CLI switch, a corresponding environment variable\n`OPTION_FLAG=<value>` exist and is used as default if set (CLI switches always\n prevails). A complete list of CLI options is available running benchmarks\n with the `--help` switch.\n\n<a name=\"running-a-subset-of-benchmarks\" />\n\n## Running a Subset of Benchmarks\n\nThe `--benchmark_filter=<regex>` option (or `BENCHMARK_FILTER=<regex>`\nenvironment variable) can be used to only run the benchmarks that match\nthe specified `<regex>`. For example:\n\n```bash\n$ ./run_benchmarks.x --benchmark_filter=BM_memcpy/32\nRun on (1 X 2300 MHz CPU )\n2016-06-25 19:34:24\nBenchmark              Time           CPU Iterations\n----------------------------------------------------\nBM_memcpy/32          11 ns         11 ns   79545455\nBM_memcpy/32k       2181 ns       2185 ns     324074\nBM_memcpy/32          12 ns         12 ns   54687500\nBM_memcpy/32k       1834 ns       1837 ns     357143\n```\n\n## Disabling Benchmarks\n\nIt is possible to temporarily disable benchmarks by renaming the benchmark\nfunction to have the prefix \"DISABLED_\". This will cause the benchmark to\nbe skipped at runtime.\n\n<a name=\"result-comparison\" />\n\n## Result comparison\n\nIt is possible to compare the benchmarking results.\nSee [Additional Tooling Documentation](tools.md)\n\n<a name=\"extra-context\" />\n\n## Extra Context\n\nSometimes it's useful to add extra context to the content printed before the\nresults. By default this section includes information about the CPU on which\nthe benchmarks are running. If you do want to add more context, you can use\nthe `benchmark_context` command line flag:\n\n```bash\n$ ./run_benchmarks --benchmark_context=pwd=`pwd`\nRun on (1 x 2300 MHz CPU)\npwd: /home/user/benchmark/\nBenchmark              Time           CPU Iterations\n----------------------------------------------------\nBM_memcpy/32          11 ns         11 ns   79545455\nBM_memcpy/32k       2181 ns       2185 ns     324074\n```\n\nYou can get the same effect with the API:\n\n```c++\n  benchmark::AddCustomContext(\"foo\", \"bar\");\n```\n\nNote that attempts to add a second value with the same key will fail with an\nerror message.\n\n<a name=\"runtime-and-reporting-considerations\" />\n\n## Runtime and Reporting Considerations\n\nWhen the benchmark binary is executed, each benchmark function is run serially.\nThe number of iterations to run is determined dynamically by running the\nbenchmark a few times and measuring the time taken and ensuring that the\nultimate result will be statistically stable. As such, faster benchmark\nfunctions will be run for more iterations than slower benchmark functions, and\nthe number of iterations is thus reported.\n\nIn all cases, the number of iterations for which the benchmark is run is\ngoverned by the amount of time the benchmark takes. Concretely, the number of\niterations is at least one, not more than 1e9, until CPU time is greater than\nthe minimum time, or the wallclock time is 5x minimum time. The minimum time is\nset per benchmark by calling `MinTime` on the registered benchmark object.\n\nFurthermore warming up a benchmark might be necessary in order to get\nstable results because of e.g caching effects of the code under benchmark.\nWarming up means running the benchmark a given amount of time, before\nresults are actually taken into account. The amount of time for which\nthe warmup should be run can be set per benchmark by calling\n`MinWarmUpTime` on the registered benchmark object or for all benchmarks\nusing the `--benchmark_min_warmup_time` command-line option. Note that\n`MinWarmUpTime` will overwrite the value of `--benchmark_min_warmup_time`\nfor the single benchmark. How many iterations the warmup run of each\nbenchmark takes is determined the same way as described in the paragraph\nabove. Per default the warmup phase is set to 0 seconds and is therefore\ndisabled.\n\nAverage timings are then reported over the iterations run. If multiple\nrepetitions are requested using the `--benchmark_repetitions` command-line\noption, or at registration time, the benchmark function will be run several\ntimes and statistical results across these repetitions will also be reported.\n\nAs well as the per-benchmark entries, a preamble in the report will include\ninformation about the machine on which the benchmarks are run.\n\n<a name=\"setup-teardown\" />\n\n## Setup/Teardown\n\nGlobal setup/teardown specific to each benchmark can be done by\npassing a callback to Setup/Teardown:\n\nThe setup/teardown callbacks will be invoked once for each benchmark. If the\nbenchmark is multi-threaded (will run in k threads), they will be invoked\nexactly once before each run with k threads.\n\nIf the benchmark uses different size groups of threads, the above will be true\nfor each size group.\n\nEg.,\n\n```c++\nstatic void DoSetup(const benchmark::State& state) {\n}\n\nstatic void DoTeardown(const benchmark::State& state) {\n}\n\nstatic void BM_func(benchmark::State& state) {...}\n\nBENCHMARK(BM_func)->Arg(1)->Arg(3)->Threads(16)->Threads(32)->Setup(DoSetup)->Teardown(DoTeardown);\n\n```\n\nIn this example, `DoSetup` and `DoTearDown` will be invoked 4 times each,\nspecifically, once for each of this family:\n - BM_func_Arg_1_Threads_16, BM_func_Arg_1_Threads_32\n - BM_func_Arg_3_Threads_16, BM_func_Arg_3_Threads_32\n\n<a name=\"passing-arguments\" />\n\n## Passing Arguments\n\nSometimes a family of benchmarks can be implemented with just one routine that\ntakes an extra argument to specify which one of the family of benchmarks to\nrun. For example, the following code defines a family of benchmarks for\nmeasuring the speed of `memcpy()` calls of different lengths:\n\n```c++\nstatic void BM_memcpy(benchmark::State& state) {\n  char* src = new char[state.range(0)];\n  char* dst = new char[state.range(0)];\n  memset(src, 'x', state.range(0));\n  for (auto _ : state)\n    memcpy(dst, src, state.range(0));\n  state.SetBytesProcessed(int64_t(state.iterations()) *\n                          int64_t(state.range(0)));\n  delete[] src;\n  delete[] dst;\n}\nBENCHMARK(BM_memcpy)->Arg(8)->Arg(64)->Arg(512)->Arg(4<<10)->Arg(8<<10);\n```\n\nThe preceding code is quite repetitive, and can be replaced with the following\nshort-hand. The following invocation will pick a few appropriate arguments in\nthe specified range and will generate a benchmark for each such argument.\n\n```c++\nBENCHMARK(BM_memcpy)->Range(8, 8<<10);\n```\n\nBy default the arguments in the range are generated in multiples of eight and\nthe command above selects [ 8, 64, 512, 4k, 8k ]. In the following code the\nrange multiplier is changed to multiples of two.\n\n```c++\nBENCHMARK(BM_memcpy)->RangeMultiplier(2)->Range(8, 8<<10);\n```\n\nNow arguments generated are [ 8, 16, 32, 64, 128, 256, 512, 1024, 2k, 4k, 8k ].\n\nThe preceding code shows a method of defining a sparse range.  The following\nexample shows a method of defining a dense range. It is then used to benchmark\nthe performance of `std::vector` initialization for uniformly increasing sizes.\n\n```c++\nstatic void BM_DenseRange(benchmark::State& state) {\n  for(auto _ : state) {\n    std::vector<int> v(state.range(0), state.range(0));\n    auto data = v.data();\n    benchmark::DoNotOptimize(data);\n    benchmark::ClobberMemory();\n  }\n}\nBENCHMARK(BM_DenseRange)->DenseRange(0, 1024, 128);\n```\n\nNow arguments generated are [ 0, 128, 256, 384, 512, 640, 768, 896, 1024 ].\n\nYou might have a benchmark that depends on two or more inputs. For example, the\nfollowing code defines a family of benchmarks for measuring the speed of set\ninsertion.\n\n```c++\nstatic void BM_SetInsert(benchmark::State& state) {\n  std::set<int> data;\n  for (auto _ : state) {\n    state.PauseTiming();\n    data = ConstructRandomSet(state.range(0));\n    state.ResumeTiming();\n    for (int j = 0; j < state.range(1); ++j)\n      data.insert(RandomNumber());\n  }\n}\nBENCHMARK(BM_SetInsert)\n    ->Args({1<<10, 128})\n    ->Args({2<<10, 128})\n    ->Args({4<<10, 128})\n    ->Args({8<<10, 128})\n    ->Args({1<<10, 512})\n    ->Args({2<<10, 512})\n    ->Args({4<<10, 512})\n    ->Args({8<<10, 512});\n```\n\nThe preceding code is quite repetitive, and can be replaced with the following\nshort-hand. The following macro will pick a few appropriate arguments in the\nproduct of the two specified ranges and will generate a benchmark for each such\npair.\n\n<!-- {% raw %} -->\n```c++\nBENCHMARK(BM_SetInsert)->Ranges({{1<<10, 8<<10}, {128, 512}});\n```\n<!-- {% endraw %} -->\n\nSome benchmarks may require specific argument values that cannot be expressed\nwith `Ranges`. In this case, `ArgsProduct` offers the ability to generate a\nbenchmark input for each combination in the product of the supplied vectors.\n\n<!-- {% raw %} -->\n```c++\nBENCHMARK(BM_SetInsert)\n    ->ArgsProduct({{1<<10, 3<<10, 8<<10}, {20, 40, 60, 80}})\n// would generate the same benchmark arguments as\nBENCHMARK(BM_SetInsert)\n    ->Args({1<<10, 20})\n    ->Args({3<<10, 20})\n    ->Args({8<<10, 20})\n    ->Args({3<<10, 40})\n    ->Args({8<<10, 40})\n    ->Args({1<<10, 40})\n    ->Args({1<<10, 60})\n    ->Args({3<<10, 60})\n    ->Args({8<<10, 60})\n    ->Args({1<<10, 80})\n    ->Args({3<<10, 80})\n    ->Args({8<<10, 80});\n```\n<!-- {% endraw %} -->\n\nFor the most common scenarios, helper methods for creating a list of\nintegers for a given sparse or dense range are provided.\n\n```c++\nBENCHMARK(BM_SetInsert)\n    ->ArgsProduct({\n      benchmark::CreateRange(8, 128, /*multi=*/2),\n      benchmark::CreateDenseRange(1, 4, /*step=*/1)\n    })\n// would generate the same benchmark arguments as\nBENCHMARK(BM_SetInsert)\n    ->ArgsProduct({\n      {8, 16, 32, 64, 128},\n      {1, 2, 3, 4}\n    });\n```\n\nFor more complex patterns of inputs, passing a custom function to `Apply` allows\nprogrammatic specification of an arbitrary set of arguments on which to run the\nbenchmark. The following example enumerates a dense range on one parameter,\nand a sparse range on the second.\n\n```c++\nstatic void CustomArguments(benchmark::internal::Benchmark* b) {\n  for (int i = 0; i <= 10; ++i)\n    for (int j = 32; j <= 1024*1024; j *= 8)\n      b->Args({i, j});\n}\nBENCHMARK(BM_SetInsert)->Apply(CustomArguments);\n```\n\n### Passing Arbitrary Arguments to a Benchmark\n\nIn C++11 it is possible to define a benchmark that takes an arbitrary number\nof extra arguments. The `BENCHMARK_CAPTURE(func, test_case_name, ...args)`\nmacro creates a benchmark that invokes `func`  with the `benchmark::State` as\nthe first argument followed by the specified `args...`.\nThe `test_case_name` is appended to the name of the benchmark and\nshould describe the values passed.\n\n```c++\ntemplate <class ...Args>\nvoid BM_takes_args(benchmark::State& state, Args&&... args) {\n  auto args_tuple = std::make_tuple(std::move(args)...);\n  for (auto _ : state) {\n    std::cout << std::get<0>(args_tuple) << \": \" << std::get<1>(args_tuple)\n              << '\\n';\n    [...]\n  }\n}\n// Registers a benchmark named \"BM_takes_args/int_string_test\" that passes\n// the specified values to `args`.\nBENCHMARK_CAPTURE(BM_takes_args, int_string_test, 42, std::string(\"abc\"));\n\n// Registers the same benchmark \"BM_takes_args/int_test\" that passes\n// the specified values to `args`.\nBENCHMARK_CAPTURE(BM_takes_args, int_test, 42, 43);\n```\n\nNote that elements of `...args` may refer to global variables. Users should\navoid modifying global state inside of a benchmark.\n\n<a name=\"asymptotic-complexity\" />\n\n## Calculating Asymptotic Complexity (Big O)\n\nAsymptotic complexity might be calculated for a family of benchmarks. The\nfollowing code will calculate the coefficient for the high-order term in the\nrunning time and the normalized root-mean square error of string comparison.\n\n```c++\nstatic void BM_StringCompare(benchmark::State& state) {\n  std::string s1(state.range(0), '-');\n  std::string s2(state.range(0), '-');\n  for (auto _ : state) {\n    auto comparison_result = s1.compare(s2);\n    benchmark::DoNotOptimize(comparison_result);\n  }\n  state.SetComplexityN(state.range(0));\n}\nBENCHMARK(BM_StringCompare)\n    ->RangeMultiplier(2)->Range(1<<10, 1<<18)->Complexity(benchmark::oN);\n```\n\nAs shown in the following invocation, asymptotic complexity might also be\ncalculated automatically.\n\n```c++\nBENCHMARK(BM_StringCompare)\n    ->RangeMultiplier(2)->Range(1<<10, 1<<18)->Complexity();\n```\n\nThe following code will specify asymptotic complexity with a lambda function,\nthat might be used to customize high-order term calculation.\n\n```c++\nBENCHMARK(BM_StringCompare)->RangeMultiplier(2)\n    ->Range(1<<10, 1<<18)->Complexity([](benchmark::IterationCount n)->double{return n; });\n```\n\n<a name=\"custom-benchmark-name\" />\n\n## Custom Benchmark Name\n\nYou can change the benchmark's name as follows:\n\n```c++\nBENCHMARK(BM_memcpy)->Name(\"memcpy\")->RangeMultiplier(2)->Range(8, 8<<10);\n```\n\nThe invocation will execute the benchmark as before using `BM_memcpy` but changes\nthe prefix in the report to `memcpy`.\n\n<a name=\"templated-benchmarks\" />\n\n## Templated Benchmarks\n\nThis example produces and consumes messages of size `sizeof(v)` `range_x`\ntimes. It also outputs throughput in the absence of multiprogramming.\n\n```c++\ntemplate <class Q> void BM_Sequential(benchmark::State& state) {\n  Q q;\n  typename Q::value_type v;\n  for (auto _ : state) {\n    for (int i = state.range(0); i--; )\n      q.push(v);\n    for (int e = state.range(0); e--; )\n      q.Wait(&v);\n  }\n  // actually messages, not bytes:\n  state.SetBytesProcessed(\n      static_cast<int64_t>(state.iterations())*state.range(0));\n}\n// C++03\nBENCHMARK_TEMPLATE(BM_Sequential, WaitQueue<int>)->Range(1<<0, 1<<10);\n\n// C++11 or newer, you can use the BENCHMARK macro with template parameters:\nBENCHMARK(BM_Sequential<WaitQueue<int>>)->Range(1<<0, 1<<10);\n\n```\n\nThree macros are provided for adding benchmark templates.\n\n```c++\n#ifdef BENCHMARK_HAS_CXX11\n#define BENCHMARK(func<...>) // Takes any number of parameters.\n#else // C++ < C++11\n#define BENCHMARK_TEMPLATE(func, arg1)\n#endif\n#define BENCHMARK_TEMPLATE1(func, arg1)\n#define BENCHMARK_TEMPLATE2(func, arg1, arg2)\n```\n\n<a name=\"fixtures\" />\n\n## Fixtures\n\nFixture tests are created by first defining a type that derives from\n`::benchmark::Fixture` and then creating/registering the tests using the\nfollowing macros:\n\n* `BENCHMARK_F(ClassName, Method)`\n* `BENCHMARK_DEFINE_F(ClassName, Method)`\n* `BENCHMARK_REGISTER_F(ClassName, Method)`\n\nFor Example:\n\n```c++\nclass MyFixture : public benchmark::Fixture {\npublic:\n  void SetUp(const ::benchmark::State& state) {\n  }\n\n  void TearDown(const ::benchmark::State& state) {\n  }\n};\n\nBENCHMARK_F(MyFixture, FooTest)(benchmark::State& st) {\n   for (auto _ : st) {\n     ...\n  }\n}\n\nBENCHMARK_DEFINE_F(MyFixture, BarTest)(benchmark::State& st) {\n   for (auto _ : st) {\n     ...\n  }\n}\n/* BarTest is NOT registered */\nBENCHMARK_REGISTER_F(MyFixture, BarTest)->Threads(2);\n/* BarTest is now registered */\n```\n\n### Templated Fixtures\n\nAlso you can create templated fixture by using the following macros:\n\n* `BENCHMARK_TEMPLATE_F(ClassName, Method, ...)`\n* `BENCHMARK_TEMPLATE_DEFINE_F(ClassName, Method, ...)`\n\nFor example:\n\n```c++\ntemplate<typename T>\nclass MyFixture : public benchmark::Fixture {};\n\nBENCHMARK_TEMPLATE_F(MyFixture, IntTest, int)(benchmark::State& st) {\n   for (auto _ : st) {\n     ...\n  }\n}\n\nBENCHMARK_TEMPLATE_DEFINE_F(MyFixture, DoubleTest, double)(benchmark::State& st) {\n   for (auto _ : st) {\n     ...\n  }\n}\n\nBENCHMARK_REGISTER_F(MyFixture, DoubleTest)->Threads(2);\n```\n\n<a name=\"custom-counters\" />\n\n## Custom Counters\n\nYou can add your own counters with user-defined names. The example below\nwill add columns \"Foo\", \"Bar\" and \"Baz\" in its output:\n\n```c++\nstatic void UserCountersExample1(benchmark::State& state) {\n  double numFoos = 0, numBars = 0, numBazs = 0;\n  for (auto _ : state) {\n    // ... count Foo,Bar,Baz events\n  }\n  state.counters[\"Foo\"] = numFoos;\n  state.counters[\"Bar\"] = numBars;\n  state.counters[\"Baz\"] = numBazs;\n}\n```\n\nThe `state.counters` object is a `std::map` with `std::string` keys\nand `Counter` values. The latter is a `double`-like class, via an implicit\nconversion to `double&`. Thus you can use all of the standard arithmetic\nassignment operators (`=,+=,-=,*=,/=`) to change the value of each counter.\n\nIn multithreaded benchmarks, each counter is set on the calling thread only.\nWhen the benchmark finishes, the counters from each thread will be summed;\nthe resulting sum is the value which will be shown for the benchmark.\n\nThe `Counter` constructor accepts three parameters: the value as a `double`\n; a bit flag which allows you to show counters as rates, and/or as per-thread\niteration, and/or as per-thread averages, and/or iteration invariants,\nand/or finally inverting the result; and a flag specifying the 'unit' - i.e.\nis 1k a 1000 (default, `benchmark::Counter::OneK::kIs1000`), or 1024\n(`benchmark::Counter::OneK::kIs1024`)?\n\n```c++\n  // sets a simple counter\n  state.counters[\"Foo\"] = numFoos;\n\n  // Set the counter as a rate. It will be presented divided\n  // by the duration of the benchmark.\n  // Meaning: per one second, how many 'foo's are processed?\n  state.counters[\"FooRate\"] = Counter(numFoos, benchmark::Counter::kIsRate);\n\n  // Set the counter as a rate. It will be presented divided\n  // by the duration of the benchmark, and the result inverted.\n  // Meaning: how many seconds it takes to process one 'foo'?\n  state.counters[\"FooInvRate\"] = Counter(numFoos, benchmark::Counter::kIsRate | benchmark::Counter::kInvert);\n\n  // Set the counter as a thread-average quantity. It will\n  // be presented divided by the number of threads.\n  state.counters[\"FooAvg\"] = Counter(numFoos, benchmark::Counter::kAvgThreads);\n\n  // There's also a combined flag:\n  state.counters[\"FooAvgRate\"] = Counter(numFoos,benchmark::Counter::kAvgThreadsRate);\n\n  // This says that we process with the rate of state.range(0) bytes every iteration:\n  state.counters[\"BytesProcessed\"] = Counter(state.range(0), benchmark::Counter::kIsIterationInvariantRate, benchmark::Counter::OneK::kIs1024);\n```\n\nWhen you're compiling in C++11 mode or later you can use `insert()` with\n`std::initializer_list`:\n\n<!-- {% raw %} -->\n```c++\n  // With C++11, this can be done:\n  state.counters.insert({{\"Foo\", numFoos}, {\"Bar\", numBars}, {\"Baz\", numBazs}});\n  // ... instead of:\n  state.counters[\"Foo\"] = numFoos;\n  state.counters[\"Bar\"] = numBars;\n  state.counters[\"Baz\"] = numBazs;\n```\n<!-- {% endraw %} -->\n\n### Counter Reporting\n\nWhen using the console reporter, by default, user counters are printed at\nthe end after the table, the same way as ``bytes_processed`` and\n``items_processed``. This is best for cases in which there are few counters,\nor where there are only a couple of lines per benchmark. Here's an example of\nthe default output:\n\n```\n------------------------------------------------------------------------------\nBenchmark                        Time           CPU Iterations UserCounters...\n------------------------------------------------------------------------------\nBM_UserCounter/threads:8      2248 ns      10277 ns      68808 Bar=16 Bat=40 Baz=24 Foo=8\nBM_UserCounter/threads:1      9797 ns       9788 ns      71523 Bar=2 Bat=5 Baz=3 Foo=1024m\nBM_UserCounter/threads:2      4924 ns       9842 ns      71036 Bar=4 Bat=10 Baz=6 Foo=2\nBM_UserCounter/threads:4      2589 ns      10284 ns      68012 Bar=8 Bat=20 Baz=12 Foo=4\nBM_UserCounter/threads:8      2212 ns      10287 ns      68040 Bar=16 Bat=40 Baz=24 Foo=8\nBM_UserCounter/threads:16     1782 ns      10278 ns      68144 Bar=32 Bat=80 Baz=48 Foo=16\nBM_UserCounter/threads:32     1291 ns      10296 ns      68256 Bar=64 Bat=160 Baz=96 Foo=32\nBM_UserCounter/threads:4      2615 ns      10307 ns      68040 Bar=8 Bat=20 Baz=12 Foo=4\nBM_Factorial                    26 ns         26 ns   26608979 40320\nBM_Factorial/real_time          26 ns         26 ns   26587936 40320\nBM_CalculatePiRange/1           16 ns         16 ns   45704255 0\nBM_CalculatePiRange/8           73 ns         73 ns    9520927 3.28374\nBM_CalculatePiRange/64         609 ns        609 ns    1140647 3.15746\nBM_CalculatePiRange/512       4900 ns       4901 ns     142696 3.14355\n```\n\nIf this doesn't suit you, you can print each counter as a table column by\npassing the flag `--benchmark_counters_tabular=true` to the benchmark\napplication. This is best for cases in which there are a lot of counters, or\na lot of lines per individual benchmark. Note that this will trigger a\nreprinting of the table header any time the counter set changes between\nindividual benchmarks. Here's an example of corresponding output when\n`--benchmark_counters_tabular=true` is passed:\n\n```\n---------------------------------------------------------------------------------------\nBenchmark                        Time           CPU Iterations    Bar   Bat   Baz   Foo\n---------------------------------------------------------------------------------------\nBM_UserCounter/threads:8      2198 ns       9953 ns      70688     16    40    24     8\nBM_UserCounter/threads:1      9504 ns       9504 ns      73787      2     5     3     1\nBM_UserCounter/threads:2      4775 ns       9550 ns      72606      4    10     6     2\nBM_UserCounter/threads:4      2508 ns       9951 ns      70332      8    20    12     4\nBM_UserCounter/threads:8      2055 ns       9933 ns      70344     16    40    24     8\nBM_UserCounter/threads:16     1610 ns       9946 ns      70720     32    80    48    16\nBM_UserCounter/threads:32     1192 ns       9948 ns      70496     64   160    96    32\nBM_UserCounter/threads:4      2506 ns       9949 ns      70332      8    20    12     4\n--------------------------------------------------------------\nBenchmark                        Time           CPU Iterations\n--------------------------------------------------------------\nBM_Factorial                    26 ns         26 ns   26392245 40320\nBM_Factorial/real_time          26 ns         26 ns   26494107 40320\nBM_CalculatePiRange/1           15 ns         15 ns   45571597 0\nBM_CalculatePiRange/8           74 ns         74 ns    9450212 3.28374\nBM_CalculatePiRange/64         595 ns        595 ns    1173901 3.15746\nBM_CalculatePiRange/512       4752 ns       4752 ns     147380 3.14355\nBM_CalculatePiRange/4k       37970 ns      37972 ns      18453 3.14184\nBM_CalculatePiRange/32k     303733 ns     303744 ns       2305 3.14162\nBM_CalculatePiRange/256k   2434095 ns    2434186 ns        288 3.1416\nBM_CalculatePiRange/1024k  9721140 ns    9721413 ns         71 3.14159\nBM_CalculatePi/threads:8      2255 ns       9943 ns      70936\n```\n\nNote above the additional header printed when the benchmark changes from\n``BM_UserCounter`` to ``BM_Factorial``. This is because ``BM_Factorial`` does\nnot have the same counter set as ``BM_UserCounter``.\n\n<a name=\"multithreaded-benchmarks\"/>\n\n## Multithreaded Benchmarks\n\nIn a multithreaded test (benchmark invoked by multiple threads simultaneously),\nit is guaranteed that none of the threads will start until all have reached\nthe start of the benchmark loop, and all will have finished before any thread\nexits the benchmark loop. (This behavior is also provided by the `KeepRunning()`\nAPI) As such, any global setup or teardown can be wrapped in a check against the thread\nindex:\n\n```c++\nstatic void BM_MultiThreaded(benchmark::State& state) {\n  if (state.thread_index() == 0) {\n    // Setup code here.\n  }\n  for (auto _ : state) {\n    // Run the test as normal.\n  }\n  if (state.thread_index() == 0) {\n    // Teardown code here.\n  }\n}\nBENCHMARK(BM_MultiThreaded)->Threads(2);\n```\n\nTo run the benchmark across a range of thread counts, instead of `Threads`, use\n`ThreadRange`. This takes two parameters (`min_threads` and `max_threads`) and\nruns the benchmark once for values in the inclusive range. For example:\n\n```c++\nBENCHMARK(BM_MultiThreaded)->ThreadRange(1, 8);\n```\n\nwill run `BM_MultiThreaded` with thread counts 1, 2, 4, and 8.\n\nIf the benchmarked code itself uses threads and you want to compare it to\nsingle-threaded code, you may want to use real-time (\"wallclock\") measurements\nfor latency comparisons:\n\n```c++\nBENCHMARK(BM_test)->Range(8, 8<<10)->UseRealTime();\n```\n\nWithout `UseRealTime`, CPU time is used by default.\n\n<a name=\"cpu-timers\" />\n\n## CPU Timers\n\nBy default, the CPU timer only measures the time spent by the main thread.\nIf the benchmark itself uses threads internally, this measurement may not\nbe what you are looking for. Instead, there is a way to measure the total\nCPU usage of the process, by all the threads.\n\n```c++\nvoid callee(int i);\n\nstatic void MyMain(int size) {\n#pragma omp parallel for\n  for(int i = 0; i < size; i++)\n    callee(i);\n}\n\nstatic void BM_OpenMP(benchmark::State& state) {\n  for (auto _ : state)\n    MyMain(state.range(0));\n}\n\n// Measure the time spent by the main thread, use it to decide for how long to\n// run the benchmark loop. Depending on the internal implementation detail may\n// measure to anywhere from near-zero (the overhead spent before/after work\n// handoff to worker thread[s]) to the whole single-thread time.\nBENCHMARK(BM_OpenMP)->Range(8, 8<<10);\n\n// Measure the user-visible time, the wall clock (literally, the time that\n// has passed on the clock on the wall), use it to decide for how long to\n// run the benchmark loop. This will always be meaningful, and will match the\n// time spent by the main thread in single-threaded case, in general decreasing\n// with the number of internal threads doing the work.\nBENCHMARK(BM_OpenMP)->Range(8, 8<<10)->UseRealTime();\n\n// Measure the total CPU consumption, use it to decide for how long to\n// run the benchmark loop. This will always measure to no less than the\n// time spent by the main thread in single-threaded case.\nBENCHMARK(BM_OpenMP)->Range(8, 8<<10)->MeasureProcessCPUTime();\n\n// A mixture of the last two. Measure the total CPU consumption, but use the\n// wall clock to decide for how long to run the benchmark loop.\nBENCHMARK(BM_OpenMP)->Range(8, 8<<10)->MeasureProcessCPUTime()->UseRealTime();\n```\n\n### Controlling Timers\n\nNormally, the entire duration of the work loop (`for (auto _ : state) {}`)\nis measured. But sometimes, it is necessary to do some work inside of\nthat loop, every iteration, but without counting that time to the benchmark time.\nThat is possible, although it is not recommended, since it has high overhead.\n\n<!-- {% raw %} -->\n```c++\nstatic void BM_SetInsert_With_Timer_Control(benchmark::State& state) {\n  std::set<int> data;\n  for (auto _ : state) {\n    state.PauseTiming(); // Stop timers. They will not count until they are resumed.\n    data = ConstructRandomSet(state.range(0)); // Do something that should not be measured\n    state.ResumeTiming(); // And resume timers. They are now counting again.\n    // The rest will be measured.\n    for (int j = 0; j < state.range(1); ++j)\n      data.insert(RandomNumber());\n  }\n}\nBENCHMARK(BM_SetInsert_With_Timer_Control)->Ranges({{1<<10, 8<<10}, {128, 512}});\n```\n<!-- {% endraw %} -->\n\n<a name=\"manual-timing\" />\n\n## Manual Timing\n\nFor benchmarking something for which neither CPU time nor real-time are\ncorrect or accurate enough, completely manual timing is supported using\nthe `UseManualTime` function.\n\nWhen `UseManualTime` is used, the benchmarked code must call\n`SetIterationTime` once per iteration of the benchmark loop to\nreport the manually measured time.\n\nAn example use case for this is benchmarking GPU execution (e.g. OpenCL\nor CUDA kernels, OpenGL or Vulkan or Direct3D draw calls), which cannot\nbe accurately measured using CPU time or real-time. Instead, they can be\nmeasured accurately using a dedicated API, and these measurement results\ncan be reported back with `SetIterationTime`.\n\n```c++\nstatic void BM_ManualTiming(benchmark::State& state) {\n  int microseconds = state.range(0);\n  std::chrono::duration<double, std::micro> sleep_duration {\n    static_cast<double>(microseconds)\n  };\n\n  for (auto _ : state) {\n    auto start = std::chrono::high_resolution_clock::now();\n    // Simulate some useful workload with a sleep\n    std::this_thread::sleep_for(sleep_duration);\n    auto end = std::chrono::high_resolution_clock::now();\n\n    auto elapsed_seconds =\n      std::chrono::duration_cast<std::chrono::duration<double>>(\n        end - start);\n\n    state.SetIterationTime(elapsed_seconds.count());\n  }\n}\nBENCHMARK(BM_ManualTiming)->Range(1, 1<<17)->UseManualTime();\n```\n\n<a name=\"setting-the-time-unit\" />\n\n## Setting the Time Unit\n\nIf a benchmark runs a few milliseconds it may be hard to visually compare the\nmeasured times, since the output data is given in nanoseconds per default. In\norder to manually set the time unit, you can specify it manually:\n\n```c++\nBENCHMARK(BM_test)->Unit(benchmark::kMillisecond);\n```\n\nAdditionally the default time unit can be set globally with the\n`--benchmark_time_unit={ns|us|ms|s}` command line argument. The argument only\naffects benchmarks where the time unit is not set explicitly.\n\n<a name=\"preventing-optimization\" />\n\n## Preventing Optimization\n\nTo prevent a value or expression from being optimized away by the compiler\nthe `benchmark::DoNotOptimize(...)` and `benchmark::ClobberMemory()`\nfunctions can be used.\n\n```c++\nstatic void BM_test(benchmark::State& state) {\n  for (auto _ : state) {\n      int x = 0;\n      for (int i=0; i < 64; ++i) {\n        benchmark::DoNotOptimize(x += i);\n      }\n  }\n}\n```\n\n`DoNotOptimize(<expr>)` forces the  *result* of `<expr>` to be stored in either\nmemory or a register. For GNU based compilers it acts as read/write barrier\nfor global memory. More specifically it forces the compiler to flush pending\nwrites to memory and reload any other values as necessary.\n\nNote that `DoNotOptimize(<expr>)` does not prevent optimizations on `<expr>`\nin any way. `<expr>` may even be removed entirely when the result is already\nknown. For example:\n\n```c++\n  /* Example 1: `<expr>` is removed entirely. */\n  int foo(int x) { return x + 42; }\n  while (...) DoNotOptimize(foo(0)); // Optimized to DoNotOptimize(42);\n\n  /*  Example 2: Result of '<expr>' is only reused */\n  int bar(int) __attribute__((const));\n  while (...) DoNotOptimize(bar(0)); // Optimized to:\n  // int __result__ = bar(0);\n  // while (...) DoNotOptimize(__result__);\n```\n\nThe second tool for preventing optimizations is `ClobberMemory()`. In essence\n`ClobberMemory()` forces the compiler to perform all pending writes to global\nmemory. Memory managed by block scope objects must be \"escaped\" using\n`DoNotOptimize(...)` before it can be clobbered. In the below example\n`ClobberMemory()` prevents the call to `v.push_back(42)` from being optimized\naway.\n\n```c++\nstatic void BM_vector_push_back(benchmark::State& state) {\n  for (auto _ : state) {\n    std::vector<int> v;\n    v.reserve(1);\n    auto data = v.data();           // Allow v.data() to be clobbered. Pass as non-const\n    benchmark::DoNotOptimize(data); // lvalue to avoid undesired compiler optimizations\n    v.push_back(42);\n    benchmark::ClobberMemory(); // Force 42 to be written to memory.\n  }\n}\n```\n\nNote that `ClobberMemory()` is only available for GNU or MSVC based compilers.\n\n<a name=\"reporting-statistics\" />\n\n## Statistics: Reporting the Mean, Median and Standard Deviation / Coefficient of variation of Repeated Benchmarks\n\nBy default each benchmark is run once and that single result is reported.\nHowever benchmarks are often noisy and a single result may not be representative\nof the overall behavior. For this reason it's possible to repeatedly rerun the\nbenchmark.\n\nThe number of runs of each benchmark is specified globally by the\n`--benchmark_repetitions` flag or on a per benchmark basis by calling\n`Repetitions` on the registered benchmark object. When a benchmark is run more\nthan once the mean, median, standard deviation and coefficient of variation\nof the runs will be reported.\n\nAdditionally the `--benchmark_report_aggregates_only={true|false}`,\n`--benchmark_display_aggregates_only={true|false}` flags or\n`ReportAggregatesOnly(bool)`, `DisplayAggregatesOnly(bool)` functions can be\nused to change how repeated tests are reported. By default the result of each\nrepeated run is reported. When `report aggregates only` option is `true`,\nonly the aggregates (i.e. mean, median, standard deviation and coefficient\nof variation, maybe complexity measurements if they were requested) of the runs\nis reported, to both the reporters - standard output (console), and the file.\nHowever when only the `display aggregates only` option is `true`,\nonly the aggregates are displayed in the standard output, while the file\noutput still contains everything.\nCalling `ReportAggregatesOnly(bool)` / `DisplayAggregatesOnly(bool)` on a\nregistered benchmark object overrides the value of the appropriate flag for that\nbenchmark.\n\n<a name=\"custom-statistics\" />\n\n## Custom Statistics\n\nWhile having these aggregates is nice, this may not be enough for everyone.\nFor example you may want to know what the largest observation is, e.g. because\nyou have some real-time constraints. This is easy. The following code will\nspecify a custom statistic to be calculated, defined by a lambda function.\n\n```c++\nvoid BM_spin_empty(benchmark::State& state) {\n  for (auto _ : state) {\n    for (int x = 0; x < state.range(0); ++x) {\n      benchmark::DoNotOptimize(x);\n    }\n  }\n}\n\nBENCHMARK(BM_spin_empty)\n  ->ComputeStatistics(\"max\", [](const std::vector<double>& v) -> double {\n    return *(std::max_element(std::begin(v), std::end(v)));\n  })\n  ->Arg(512);\n```\n\nWhile usually the statistics produce values in time units,\nyou can also produce percentages:\n\n```c++\nvoid BM_spin_empty(benchmark::State& state) {\n  for (auto _ : state) {\n    for (int x = 0; x < state.range(0); ++x) {\n      benchmark::DoNotOptimize(x);\n    }\n  }\n}\n\nBENCHMARK(BM_spin_empty)\n  ->ComputeStatistics(\"ratio\", [](const std::vector<double>& v) -> double {\n    return std::begin(v) / std::end(v);\n  }, benchmark::StatisticUnit::kPercentage)\n  ->Arg(512);\n```\n\n<a name=\"memory-usage\" />\n\n## Memory Usage\n\nIt's often useful to also track memory usage for benchmarks, alongside CPU\nperformance. For this reason, benchmark offers the `RegisterMemoryManager`\nmethod that allows a custom `MemoryManager` to be injected.\n\nIf set, the `MemoryManager::Start` and `MemoryManager::Stop` methods will be\ncalled at the start and end of benchmark runs to allow user code to fill out\na report on the number of allocations, bytes used, etc.\n\nThis data will then be reported alongside other performance data, currently\nonly when using JSON output.\n\n<a name=\"using-register-benchmark\" />\n\n## Using RegisterBenchmark(name, fn, args...)\n\nThe `RegisterBenchmark(name, func, args...)` function provides an alternative\nway to create and register benchmarks.\n`RegisterBenchmark(name, func, args...)` creates, registers, and returns a\npointer to a new benchmark with the specified `name` that invokes\n`func(st, args...)` where `st` is a `benchmark::State` object.\n\nUnlike the `BENCHMARK` registration macros, which can only be used at the global\nscope, the `RegisterBenchmark` can be called anywhere. This allows for\nbenchmark tests to be registered programmatically.\n\nAdditionally `RegisterBenchmark` allows any callable object to be registered\nas a benchmark. Including capturing lambdas and function objects.\n\nFor Example:\n```c++\nauto BM_test = [](benchmark::State& st, auto Inputs) { /* ... */ };\n\nint main(int argc, char** argv) {\n  for (auto& test_input : { /* ... */ })\n      benchmark::RegisterBenchmark(test_input.name(), BM_test, test_input);\n  benchmark::Initialize(&argc, argv);\n  benchmark::RunSpecifiedBenchmarks();\n  benchmark::Shutdown();\n}\n```\n\n<a name=\"exiting-with-an-error\" />\n\n## Exiting with an Error\n\nWhen errors caused by external influences, such as file I/O and network\ncommunication, occur within a benchmark the\n`State::SkipWithError(const std::string& msg)` function can be used to skip that run\nof benchmark and report the error. Note that only future iterations of the\n`KeepRunning()` are skipped. For the ranged-for version of the benchmark loop\nUsers must explicitly exit the loop, otherwise all iterations will be performed.\nUsers may explicitly return to exit the benchmark immediately.\n\nThe `SkipWithError(...)` function may be used at any point within the benchmark,\nincluding before and after the benchmark loop. Moreover, if `SkipWithError(...)`\nhas been used, it is not required to reach the benchmark loop and one may return\nfrom the benchmark function early.\n\nFor example:\n\n```c++\nstatic void BM_test(benchmark::State& state) {\n  auto resource = GetResource();\n  if (!resource.good()) {\n    state.SkipWithError(\"Resource is not good!\");\n    // KeepRunning() loop will not be entered.\n  }\n  while (state.KeepRunning()) {\n    auto data = resource.read_data();\n    if (!resource.good()) {\n      state.SkipWithError(\"Failed to read data!\");\n      break; // Needed to skip the rest of the iteration.\n    }\n    do_stuff(data);\n  }\n}\n\nstatic void BM_test_ranged_fo(benchmark::State & state) {\n  auto resource = GetResource();\n  if (!resource.good()) {\n    state.SkipWithError(\"Resource is not good!\");\n    return; // Early return is allowed when SkipWithError() has been used.\n  }\n  for (auto _ : state) {\n    auto data = resource.read_data();\n    if (!resource.good()) {\n      state.SkipWithError(\"Failed to read data!\");\n      break; // REQUIRED to prevent all further iterations.\n    }\n    do_stuff(data);\n  }\n}\n```\n<a name=\"a-faster-keep-running-loop\" />\n\n## A Faster KeepRunning Loop\n\nIn C++11 mode, a ranged-based for loop should be used in preference to\nthe `KeepRunning` loop for running the benchmarks. For example:\n\n```c++\nstatic void BM_Fast(benchmark::State &state) {\n  for (auto _ : state) {\n    FastOperation();\n  }\n}\nBENCHMARK(BM_Fast);\n```\n\nThe reason the ranged-for loop is faster than using `KeepRunning`, is\nbecause `KeepRunning` requires a memory load and store of the iteration count\never iteration, whereas the ranged-for variant is able to keep the iteration count\nin a register.\n\nFor example, an empty inner loop of using the ranged-based for method looks like:\n\n```asm\n# Loop Init\n  mov rbx, qword ptr [r14 + 104]\n  call benchmark::State::StartKeepRunning()\n  test rbx, rbx\n  je .LoopEnd\n.LoopHeader: # =>This Inner Loop Header: Depth=1\n  add rbx, -1\n  jne .LoopHeader\n.LoopEnd:\n```\n\nCompared to an empty `KeepRunning` loop, which looks like:\n\n```asm\n.LoopHeader: # in Loop: Header=BB0_3 Depth=1\n  cmp byte ptr [rbx], 1\n  jne .LoopInit\n.LoopBody: # =>This Inner Loop Header: Depth=1\n  mov rax, qword ptr [rbx + 8]\n  lea rcx, [rax + 1]\n  mov qword ptr [rbx + 8], rcx\n  cmp rax, qword ptr [rbx + 104]\n  jb .LoopHeader\n  jmp .LoopEnd\n.LoopInit:\n  mov rdi, rbx\n  call benchmark::State::StartKeepRunning()\n  jmp .LoopBody\n.LoopEnd:\n```\n\nUnless C++03 compatibility is required, the ranged-for variant of writing\nthe benchmark loop should be preferred.\n\n<a name=\"disabling-cpu-frequency-scaling\" />\n\n## Disabling CPU Frequency Scaling\n\nIf you see this error:\n\n```\n***WARNING*** CPU scaling is enabled, the benchmark real time measurements may\nbe noisy and will incur extra overhead.\n```\n\nyou might want to disable the CPU frequency scaling while running the\nbenchmark, as well as consider other ways to stabilize the performance of\nyour system while benchmarking.\n\nSee [Reducing Variance](reducing_variance.md) for more information.\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/include/benchmark/benchmark.h",
    "content": "// Copyright 2015 Google Inc. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// Support for registering benchmarks for functions.\n\n/* Example usage:\n// Define a function that executes the code to be measured a\n// specified number of times:\nstatic void BM_StringCreation(benchmark::State& state) {\n  for (auto _ : state)\n    std::string empty_string;\n}\n\n// Register the function as a benchmark\nBENCHMARK(BM_StringCreation);\n\n// Define another benchmark\nstatic void BM_StringCopy(benchmark::State& state) {\n  std::string x = \"hello\";\n  for (auto _ : state)\n    std::string copy(x);\n}\nBENCHMARK(BM_StringCopy);\n\n// Augment the main() program to invoke benchmarks if specified\n// via the --benchmark_filter command line flag.  E.g.,\n//       my_unittest --benchmark_filter=all\n//       my_unittest --benchmark_filter=BM_StringCreation\n//       my_unittest --benchmark_filter=String\n//       my_unittest --benchmark_filter='Copy|Creation'\nint main(int argc, char** argv) {\n  benchmark::Initialize(&argc, argv);\n  benchmark::RunSpecifiedBenchmarks();\n  benchmark::Shutdown();\n  return 0;\n}\n\n// Sometimes a family of microbenchmarks can be implemented with\n// just one routine that takes an extra argument to specify which\n// one of the family of benchmarks to run.  For example, the following\n// code defines a family of microbenchmarks for measuring the speed\n// of memcpy() calls of different lengths:\n\nstatic void BM_memcpy(benchmark::State& state) {\n  char* src = new char[state.range(0)]; char* dst = new char[state.range(0)];\n  memset(src, 'x', state.range(0));\n  for (auto _ : state)\n    memcpy(dst, src, state.range(0));\n  state.SetBytesProcessed(state.iterations() * state.range(0));\n  delete[] src; delete[] dst;\n}\nBENCHMARK(BM_memcpy)->Arg(8)->Arg(64)->Arg(512)->Arg(1<<10)->Arg(8<<10);\n\n// The preceding code is quite repetitive, and can be replaced with the\n// following short-hand.  The following invocation will pick a few\n// appropriate arguments in the specified range and will generate a\n// microbenchmark for each such argument.\nBENCHMARK(BM_memcpy)->Range(8, 8<<10);\n\n// You might have a microbenchmark that depends on two inputs.  For\n// example, the following code defines a family of microbenchmarks for\n// measuring the speed of set insertion.\nstatic void BM_SetInsert(benchmark::State& state) {\n  set<int> data;\n  for (auto _ : state) {\n    state.PauseTiming();\n    data = ConstructRandomSet(state.range(0));\n    state.ResumeTiming();\n    for (int j = 0; j < state.range(1); ++j)\n      data.insert(RandomNumber());\n  }\n}\nBENCHMARK(BM_SetInsert)\n   ->Args({1<<10, 128})\n   ->Args({2<<10, 128})\n   ->Args({4<<10, 128})\n   ->Args({8<<10, 128})\n   ->Args({1<<10, 512})\n   ->Args({2<<10, 512})\n   ->Args({4<<10, 512})\n   ->Args({8<<10, 512});\n\n// The preceding code is quite repetitive, and can be replaced with\n// the following short-hand.  The following macro will pick a few\n// appropriate arguments in the product of the two specified ranges\n// and will generate a microbenchmark for each such pair.\nBENCHMARK(BM_SetInsert)->Ranges({{1<<10, 8<<10}, {128, 512}});\n\n// For more complex patterns of inputs, passing a custom function\n// to Apply allows programmatic specification of an\n// arbitrary set of arguments to run the microbenchmark on.\n// The following example enumerates a dense range on\n// one parameter, and a sparse range on the second.\nstatic void CustomArguments(benchmark::internal::Benchmark* b) {\n  for (int i = 0; i <= 10; ++i)\n    for (int j = 32; j <= 1024*1024; j *= 8)\n      b->Args({i, j});\n}\nBENCHMARK(BM_SetInsert)->Apply(CustomArguments);\n\n// Templated microbenchmarks work the same way:\n// Produce then consume 'size' messages 'iters' times\n// Measures throughput in the absence of multiprogramming.\ntemplate <class Q> int BM_Sequential(benchmark::State& state) {\n  Q q;\n  typename Q::value_type v;\n  for (auto _ : state) {\n    for (int i = state.range(0); i--; )\n      q.push(v);\n    for (int e = state.range(0); e--; )\n      q.Wait(&v);\n  }\n  // actually messages, not bytes:\n  state.SetBytesProcessed(state.iterations() * state.range(0));\n}\nBENCHMARK_TEMPLATE(BM_Sequential, WaitQueue<int>)->Range(1<<0, 1<<10);\n\nUse `Benchmark::MinTime(double t)` to set the minimum time used to run the\nbenchmark. This option overrides the `benchmark_min_time` flag.\n\nvoid BM_test(benchmark::State& state) {\n ... body ...\n}\nBENCHMARK(BM_test)->MinTime(2.0); // Run for at least 2 seconds.\n\nIn a multithreaded test, it is guaranteed that none of the threads will start\nuntil all have reached the loop start, and all will have finished before any\nthread exits the loop body. As such, any global setup or teardown you want to\ndo can be wrapped in a check against the thread index:\n\nstatic void BM_MultiThreaded(benchmark::State& state) {\n  if (state.thread_index() == 0) {\n    // Setup code here.\n  }\n  for (auto _ : state) {\n    // Run the test as normal.\n  }\n  if (state.thread_index() == 0) {\n    // Teardown code here.\n  }\n}\nBENCHMARK(BM_MultiThreaded)->Threads(4);\n\n\nIf a benchmark runs a few milliseconds it may be hard to visually compare the\nmeasured times, since the output data is given in nanoseconds per default. In\norder to manually set the time unit, you can specify it manually:\n\nBENCHMARK(BM_test)->Unit(benchmark::kMillisecond);\n*/\n\n#ifndef BENCHMARK_BENCHMARK_H_\n#define BENCHMARK_BENCHMARK_H_\n\n// The _MSVC_LANG check should detect Visual Studio 2015 Update 3 and newer.\n#if __cplusplus >= 201103L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201103L)\n#define BENCHMARK_HAS_CXX11\n#endif\n\n// This _MSC_VER check should detect VS 2017 v15.3 and newer.\n#if __cplusplus >= 201703L || \\\n    (defined(_MSC_VER) && _MSC_VER >= 1911 && _MSVC_LANG >= 201703L)\n#define BENCHMARK_HAS_CXX17\n#endif\n\n#include <stdint.h>\n\n#include <algorithm>\n#include <cassert>\n#include <cstddef>\n#include <iosfwd>\n#include <limits>\n#include <map>\n#include <set>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"benchmark/export.h\"\n\n#if defined(BENCHMARK_HAS_CXX11)\n#include <atomic>\n#include <initializer_list>\n#include <type_traits>\n#include <utility>\n#endif\n\n#if defined(_MSC_VER)\n#include <intrin.h>  // for _ReadWriteBarrier\n#endif\n\n#ifndef BENCHMARK_HAS_CXX11\n#define BENCHMARK_DISALLOW_COPY_AND_ASSIGN(TypeName) \\\n  TypeName(const TypeName&);                         \\\n  TypeName& operator=(const TypeName&)\n#else\n#define BENCHMARK_DISALLOW_COPY_AND_ASSIGN(TypeName) \\\n  TypeName(const TypeName&) = delete;                \\\n  TypeName& operator=(const TypeName&) = delete\n#endif\n\n#ifdef BENCHMARK_HAS_CXX17\n#define BENCHMARK_UNUSED [[maybe_unused]]\n#elif defined(__GNUC__) || defined(__clang__)\n#define BENCHMARK_UNUSED __attribute__((unused))\n#else\n#define BENCHMARK_UNUSED\n#endif\n\n// Used to annotate functions, methods and classes so they\n// are not optimized by the compiler. Useful for tests\n// where you expect loops to stay in place churning cycles\n#if defined(__clang__)\n#define BENCHMARK_DONT_OPTIMIZE __attribute__((optnone))\n#elif defined(__GNUC__) || defined(__GNUG__)\n#define BENCHMARK_DONT_OPTIMIZE __attribute__((optimize(0)))\n#else\n// MSVC & Intel do not have a no-optimize attribute, only line pragmas\n#define BENCHMARK_DONT_OPTIMIZE\n#endif\n\n#if defined(__GNUC__) || defined(__clang__)\n#define BENCHMARK_ALWAYS_INLINE __attribute__((always_inline))\n#elif defined(_MSC_VER) && !defined(__clang__)\n#define BENCHMARK_ALWAYS_INLINE __forceinline\n#define __func__ __FUNCTION__\n#else\n#define BENCHMARK_ALWAYS_INLINE\n#endif\n\n#define BENCHMARK_INTERNAL_TOSTRING2(x) #x\n#define BENCHMARK_INTERNAL_TOSTRING(x) BENCHMARK_INTERNAL_TOSTRING2(x)\n\n// clang-format off\n#if (defined(__GNUC__) && !defined(__NVCC__) && !defined(__NVCOMPILER)) || defined(__clang__)\n#define BENCHMARK_BUILTIN_EXPECT(x, y) __builtin_expect(x, y)\n#define BENCHMARK_DEPRECATED_MSG(msg) __attribute__((deprecated(msg)))\n#define BENCHMARK_DISABLE_DEPRECATED_WARNING \\\n  _Pragma(\"GCC diagnostic push\")             \\\n  _Pragma(\"GCC diagnostic ignored \\\"-Wdeprecated-declarations\\\"\")\n#define BENCHMARK_RESTORE_DEPRECATED_WARNING _Pragma(\"GCC diagnostic pop\")\n#elif defined(__NVCOMPILER)\n#define BENCHMARK_BUILTIN_EXPECT(x, y) __builtin_expect(x, y)\n#define BENCHMARK_DEPRECATED_MSG(msg) __attribute__((deprecated(msg)))\n#define BENCHMARK_DISABLE_DEPRECATED_WARNING \\\n  _Pragma(\"diagnostic push\") \\\n  _Pragma(\"diag_suppress deprecated_entity_with_custom_message\")\n#define BENCHMARK_RESTORE_DEPRECATED_WARNING _Pragma(\"diagnostic pop\")\n#else\n#define BENCHMARK_BUILTIN_EXPECT(x, y) x\n#define BENCHMARK_DEPRECATED_MSG(msg)\n#define BENCHMARK_WARNING_MSG(msg)                           \\\n  __pragma(message(__FILE__ \"(\" BENCHMARK_INTERNAL_TOSTRING( \\\n      __LINE__) \") : warning note: \" msg))\n#define BENCHMARK_DISABLE_DEPRECATED_WARNING\n#define BENCHMARK_RESTORE_DEPRECATED_WARNING\n#endif\n// clang-format on\n\n#if defined(__GNUC__) && !defined(__clang__)\n#define BENCHMARK_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)\n#endif\n\n#ifndef __has_builtin\n#define __has_builtin(x) 0\n#endif\n\n#if defined(__GNUC__) || __has_builtin(__builtin_unreachable)\n#define BENCHMARK_UNREACHABLE() __builtin_unreachable()\n#elif defined(_MSC_VER)\n#define BENCHMARK_UNREACHABLE() __assume(false)\n#else\n#define BENCHMARK_UNREACHABLE() ((void)0)\n#endif\n\n#ifdef BENCHMARK_HAS_CXX11\n#define BENCHMARK_OVERRIDE override\n#else\n#define BENCHMARK_OVERRIDE\n#endif\n\n#if defined(_MSC_VER)\n#pragma warning(push)\n// C4251: <symbol> needs to have dll-interface to be used by clients of class\n#pragma warning(disable : 4251)\n#endif\n\nnamespace benchmark {\nclass BenchmarkReporter;\n\n// Default number of minimum benchmark running time in seconds.\nconst char kDefaultMinTimeStr[] = \"0.5s\";\n\nBENCHMARK_EXPORT void PrintDefaultHelp();\n\nBENCHMARK_EXPORT void Initialize(int* argc, char** argv,\n                                 void (*HelperPrinterf)() = PrintDefaultHelp);\nBENCHMARK_EXPORT void Shutdown();\n\n// Report to stdout all arguments in 'argv' as unrecognized except the first.\n// Returns true there is at least on unrecognized argument (i.e. 'argc' > 1).\nBENCHMARK_EXPORT bool ReportUnrecognizedArguments(int argc, char** argv);\n\n// Returns the current value of --benchmark_filter.\nBENCHMARK_EXPORT std::string GetBenchmarkFilter();\n\n// Sets a new value to --benchmark_filter. (This will override this flag's\n// current value).\n// Should be called after `benchmark::Initialize()`, as\n// `benchmark::Initialize()` will override the flag's value.\nBENCHMARK_EXPORT void SetBenchmarkFilter(std::string value);\n\n// Returns the current value of --v (command line value for verbosity).\nBENCHMARK_EXPORT int32_t GetBenchmarkVerbosity();\n\n// Creates a default display reporter. Used by the library when no display\n// reporter is provided, but also made available for external use in case a\n// custom reporter should respect the `--benchmark_format` flag as a fallback\nBENCHMARK_EXPORT BenchmarkReporter* CreateDefaultDisplayReporter();\n\n// Generate a list of benchmarks matching the specified --benchmark_filter flag\n// and if --benchmark_list_tests is specified return after printing the name\n// of each matching benchmark. Otherwise run each matching benchmark and\n// report the results.\n//\n// spec : Specify the benchmarks to run. If users do not specify this arg,\n//        then the value of FLAGS_benchmark_filter\n//        will be used.\n//\n// The second and third overload use the specified 'display_reporter' and\n//  'file_reporter' respectively. 'file_reporter' will write to the file\n//  specified\n//   by '--benchmark_output'. If '--benchmark_output' is not given the\n//  'file_reporter' is ignored.\n//\n// RETURNS: The number of matching benchmarks.\nBENCHMARK_EXPORT size_t RunSpecifiedBenchmarks();\nBENCHMARK_EXPORT size_t RunSpecifiedBenchmarks(std::string spec);\n\nBENCHMARK_EXPORT size_t\nRunSpecifiedBenchmarks(BenchmarkReporter* display_reporter);\nBENCHMARK_EXPORT size_t\nRunSpecifiedBenchmarks(BenchmarkReporter* display_reporter, std::string spec);\n\nBENCHMARK_EXPORT size_t RunSpecifiedBenchmarks(\n    BenchmarkReporter* display_reporter, BenchmarkReporter* file_reporter);\nBENCHMARK_EXPORT size_t\nRunSpecifiedBenchmarks(BenchmarkReporter* display_reporter,\n                       BenchmarkReporter* file_reporter, std::string spec);\n\n// TimeUnit is passed to a benchmark in order to specify the order of magnitude\n// for the measured time.\nenum TimeUnit { kNanosecond, kMicrosecond, kMillisecond, kSecond };\n\nBENCHMARK_EXPORT TimeUnit GetDefaultTimeUnit();\n\n// Sets the default time unit the benchmarks use\n// Has to be called before the benchmark loop to take effect\nBENCHMARK_EXPORT void SetDefaultTimeUnit(TimeUnit unit);\n\n// If a MemoryManager is registered (via RegisterMemoryManager()),\n// it can be used to collect and report allocation metrics for a run of the\n// benchmark.\nclass MemoryManager {\n public:\n  static const int64_t TombstoneValue;\n\n  struct Result {\n    Result()\n        : num_allocs(0),\n          max_bytes_used(0),\n          total_allocated_bytes(TombstoneValue),\n          net_heap_growth(TombstoneValue) {}\n\n    // The number of allocations made in total between Start and Stop.\n    int64_t num_allocs;\n\n    // The peak memory use between Start and Stop.\n    int64_t max_bytes_used;\n\n    // The total memory allocated, in bytes, between Start and Stop.\n    // Init'ed to TombstoneValue if metric not available.\n    int64_t total_allocated_bytes;\n\n    // The net changes in memory, in bytes, between Start and Stop.\n    // ie., total_allocated_bytes - total_deallocated_bytes.\n    // Init'ed to TombstoneValue if metric not available.\n    int64_t net_heap_growth;\n  };\n\n  virtual ~MemoryManager() {}\n\n  // Implement this to start recording allocation information.\n  virtual void Start() = 0;\n\n  // Implement this to stop recording and fill out the given Result structure.\n  virtual void Stop(Result& result) = 0;\n};\n\n// Register a MemoryManager instance that will be used to collect and report\n// allocation measurements for benchmark runs.\nBENCHMARK_EXPORT\nvoid RegisterMemoryManager(MemoryManager* memory_manager);\n\n// Add a key-value pair to output as part of the context stanza in the report.\nBENCHMARK_EXPORT\nvoid AddCustomContext(const std::string& key, const std::string& value);\n\nnamespace internal {\nclass Benchmark;\nclass BenchmarkImp;\nclass BenchmarkFamilies;\n\nBENCHMARK_EXPORT std::map<std::string, std::string>*& GetGlobalContext();\n\nBENCHMARK_EXPORT\nvoid UseCharPointer(char const volatile*);\n\n// Take ownership of the pointer and register the benchmark. Return the\n// registered benchmark.\nBENCHMARK_EXPORT Benchmark* RegisterBenchmarkInternal(Benchmark*);\n\n// Ensure that the standard streams are properly initialized in every TU.\nBENCHMARK_EXPORT int InitializeStreams();\nBENCHMARK_UNUSED static int stream_init_anchor = InitializeStreams();\n\n}  // namespace internal\n\n#if (!defined(__GNUC__) && !defined(__clang__)) || defined(__pnacl__) || \\\n    defined(__EMSCRIPTEN__)\n#define BENCHMARK_HAS_NO_INLINE_ASSEMBLY\n#endif\n\n// Force the compiler to flush pending writes to global memory. Acts as an\n// effective read/write barrier\n#ifdef BENCHMARK_HAS_CXX11\ninline BENCHMARK_ALWAYS_INLINE void ClobberMemory() {\n  std::atomic_signal_fence(std::memory_order_acq_rel);\n}\n#endif\n\n// The DoNotOptimize(...) function can be used to prevent a value or\n// expression from being optimized away by the compiler. This function is\n// intended to add little to no overhead.\n// See: https://youtu.be/nXaxk27zwlk?t=2441\n#ifndef BENCHMARK_HAS_NO_INLINE_ASSEMBLY\n#if !defined(__GNUC__) || defined(__llvm__) || defined(__INTEL_COMPILER)\ntemplate <class Tp>\nBENCHMARK_DEPRECATED_MSG(\n    \"The const-ref version of this method can permit \"\n    \"undesired compiler optimizations in benchmarks\")\ninline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) {\n  asm volatile(\"\" : : \"r,m\"(value) : \"memory\");\n}\n\ntemplate <class Tp>\ninline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp& value) {\n#if defined(__clang__)\n  asm volatile(\"\" : \"+r,m\"(value) : : \"memory\");\n#else\n  asm volatile(\"\" : \"+m,r\"(value) : : \"memory\");\n#endif\n}\n\n#ifdef BENCHMARK_HAS_CXX11\ntemplate <class Tp>\ninline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp&& value) {\n#if defined(__clang__)\n  asm volatile(\"\" : \"+r,m\"(value) : : \"memory\");\n#else\n  asm volatile(\"\" : \"+m,r\"(value) : : \"memory\");\n#endif\n}\n#endif\n#elif defined(BENCHMARK_HAS_CXX11) && (__GNUC__ >= 5)\n// Workaround for a bug with full argument copy overhead with GCC.\n// See: #1340 and https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105519\ntemplate <class Tp>\nBENCHMARK_DEPRECATED_MSG(\n    \"The const-ref version of this method can permit \"\n    \"undesired compiler optimizations in benchmarks\")\ninline BENCHMARK_ALWAYS_INLINE\n    typename std::enable_if<std::is_trivially_copyable<Tp>::value &&\n                            (sizeof(Tp) <= sizeof(Tp*))>::type\n    DoNotOptimize(Tp const& value) {\n  asm volatile(\"\" : : \"r,m\"(value) : \"memory\");\n}\n\ntemplate <class Tp>\nBENCHMARK_DEPRECATED_MSG(\n    \"The const-ref version of this method can permit \"\n    \"undesired compiler optimizations in benchmarks\")\ninline BENCHMARK_ALWAYS_INLINE\n    typename std::enable_if<!std::is_trivially_copyable<Tp>::value ||\n                            (sizeof(Tp) > sizeof(Tp*))>::type\n    DoNotOptimize(Tp const& value) {\n  asm volatile(\"\" : : \"m\"(value) : \"memory\");\n}\n\ntemplate <class Tp>\ninline BENCHMARK_ALWAYS_INLINE\n    typename std::enable_if<std::is_trivially_copyable<Tp>::value &&\n                            (sizeof(Tp) <= sizeof(Tp*))>::type\n    DoNotOptimize(Tp& value) {\n  asm volatile(\"\" : \"+m,r\"(value) : : \"memory\");\n}\n\ntemplate <class Tp>\ninline BENCHMARK_ALWAYS_INLINE\n    typename std::enable_if<!std::is_trivially_copyable<Tp>::value ||\n                            (sizeof(Tp) > sizeof(Tp*))>::type\n    DoNotOptimize(Tp& value) {\n  asm volatile(\"\" : \"+m\"(value) : : \"memory\");\n}\n\ntemplate <class Tp>\ninline BENCHMARK_ALWAYS_INLINE\n    typename std::enable_if<std::is_trivially_copyable<Tp>::value &&\n                            (sizeof(Tp) <= sizeof(Tp*))>::type\n    DoNotOptimize(Tp&& value) {\n  asm volatile(\"\" : \"+m,r\"(value) : : \"memory\");\n}\n\ntemplate <class Tp>\ninline BENCHMARK_ALWAYS_INLINE\n    typename std::enable_if<!std::is_trivially_copyable<Tp>::value ||\n                            (sizeof(Tp) > sizeof(Tp*))>::type\n    DoNotOptimize(Tp&& value) {\n  asm volatile(\"\" : \"+m\"(value) : : \"memory\");\n}\n\n#else\n// Fallback for GCC < 5. Can add some overhead because the compiler is forced\n// to use memory operations instead of operations with registers.\n// TODO: Remove if GCC < 5 will be unsupported.\ntemplate <class Tp>\nBENCHMARK_DEPRECATED_MSG(\n    \"The const-ref version of this method can permit \"\n    \"undesired compiler optimizations in benchmarks\")\ninline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) {\n  asm volatile(\"\" : : \"m\"(value) : \"memory\");\n}\n\ntemplate <class Tp>\ninline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp& value) {\n  asm volatile(\"\" : \"+m\"(value) : : \"memory\");\n}\n\n#ifdef BENCHMARK_HAS_CXX11\ntemplate <class Tp>\ninline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp&& value) {\n  asm volatile(\"\" : \"+m\"(value) : : \"memory\");\n}\n#endif\n#endif\n\n#ifndef BENCHMARK_HAS_CXX11\ninline BENCHMARK_ALWAYS_INLINE void ClobberMemory() {\n  asm volatile(\"\" : : : \"memory\");\n}\n#endif\n#elif defined(_MSC_VER)\ntemplate <class Tp>\nBENCHMARK_DEPRECATED_MSG(\n    \"The const-ref version of this method can permit \"\n    \"undesired compiler optimizations in benchmarks\")\ninline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) {\n  internal::UseCharPointer(&reinterpret_cast<char const volatile&>(value));\n  _ReadWriteBarrier();\n}\n\n#ifndef BENCHMARK_HAS_CXX11\ninline BENCHMARK_ALWAYS_INLINE void ClobberMemory() { _ReadWriteBarrier(); }\n#endif\n#else\ntemplate <class Tp>\nBENCHMARK_DEPRECATED_MSG(\n    \"The const-ref version of this method can permit \"\n    \"undesired compiler optimizations in benchmarks\")\ninline BENCHMARK_ALWAYS_INLINE void DoNotOptimize(Tp const& value) {\n  internal::UseCharPointer(&reinterpret_cast<char const volatile&>(value));\n}\n// FIXME Add ClobberMemory() for non-gnu and non-msvc compilers, before C++11.\n#endif\n\n// This class is used for user-defined counters.\nclass Counter {\n public:\n  enum Flags {\n    kDefaults = 0,\n    // Mark the counter as a rate. It will be presented divided\n    // by the duration of the benchmark.\n    kIsRate = 1 << 0,\n    // Mark the counter as a thread-average quantity. It will be\n    // presented divided by the number of threads.\n    kAvgThreads = 1 << 1,\n    // Mark the counter as a thread-average rate. See above.\n    kAvgThreadsRate = kIsRate | kAvgThreads,\n    // Mark the counter as a constant value, valid/same for *every* iteration.\n    // When reporting, it will be *multiplied* by the iteration count.\n    kIsIterationInvariant = 1 << 2,\n    // Mark the counter as a constant rate.\n    // When reporting, it will be *multiplied* by the iteration count\n    // and then divided by the duration of the benchmark.\n    kIsIterationInvariantRate = kIsRate | kIsIterationInvariant,\n    // Mark the counter as a iteration-average quantity.\n    // It will be presented divided by the number of iterations.\n    kAvgIterations = 1 << 3,\n    // Mark the counter as a iteration-average rate. See above.\n    kAvgIterationsRate = kIsRate | kAvgIterations,\n\n    // In the end, invert the result. This is always done last!\n    kInvert = 1 << 31\n  };\n\n  enum OneK {\n    // 1'000 items per 1k\n    kIs1000 = 1000,\n    // 1'024 items per 1k\n    kIs1024 = 1024\n  };\n\n  double value;\n  Flags flags;\n  OneK oneK;\n\n  BENCHMARK_ALWAYS_INLINE\n  Counter(double v = 0., Flags f = kDefaults, OneK k = kIs1000)\n      : value(v), flags(f), oneK(k) {}\n\n  BENCHMARK_ALWAYS_INLINE operator double const &() const { return value; }\n  BENCHMARK_ALWAYS_INLINE operator double&() { return value; }\n};\n\n// A helper for user code to create unforeseen combinations of Flags, without\n// having to do this cast manually each time, or providing this operator.\nCounter::Flags inline operator|(const Counter::Flags& LHS,\n                                const Counter::Flags& RHS) {\n  return static_cast<Counter::Flags>(static_cast<int>(LHS) |\n                                     static_cast<int>(RHS));\n}\n\n// This is the container for the user-defined counters.\ntypedef std::map<std::string, Counter> UserCounters;\n\n// BigO is passed to a benchmark in order to specify the asymptotic\n// computational\n// complexity for the benchmark. In case oAuto is selected, complexity will be\n// calculated automatically to the best fit.\nenum BigO { oNone, o1, oN, oNSquared, oNCubed, oLogN, oNLogN, oAuto, oLambda };\n\ntypedef int64_t IterationCount;\n\nenum StatisticUnit { kTime, kPercentage };\n\n// BigOFunc is passed to a benchmark in order to specify the asymptotic\n// computational complexity for the benchmark.\ntypedef double(BigOFunc)(IterationCount);\n\n// StatisticsFunc is passed to a benchmark in order to compute some descriptive\n// statistics over all the measurements of some type\ntypedef double(StatisticsFunc)(const std::vector<double>&);\n\nnamespace internal {\nstruct Statistics {\n  std::string name_;\n  StatisticsFunc* compute_;\n  StatisticUnit unit_;\n\n  Statistics(const std::string& name, StatisticsFunc* compute,\n             StatisticUnit unit = kTime)\n      : name_(name), compute_(compute), unit_(unit) {}\n};\n\nclass BenchmarkInstance;\nclass ThreadTimer;\nclass ThreadManager;\nclass PerfCountersMeasurement;\n\nenum AggregationReportMode\n#if defined(BENCHMARK_HAS_CXX11)\n    : unsigned\n#else\n#endif\n{\n  // The mode has not been manually specified\n  ARM_Unspecified = 0,\n  // The mode is user-specified.\n  // This may or may not be set when the following bit-flags are set.\n  ARM_Default = 1U << 0U,\n  // File reporter should only output aggregates.\n  ARM_FileReportAggregatesOnly = 1U << 1U,\n  // Display reporter should only output aggregates\n  ARM_DisplayReportAggregatesOnly = 1U << 2U,\n  // Both reporters should only display aggregates.\n  ARM_ReportAggregatesOnly =\n      ARM_FileReportAggregatesOnly | ARM_DisplayReportAggregatesOnly\n};\n\nenum Skipped\n#if defined(BENCHMARK_HAS_CXX11)\n    : unsigned\n#endif\n{\n  NotSkipped = 0,\n  SkippedWithMessage,\n  SkippedWithError\n};\n\n}  // namespace internal\n\n// State is passed to a running Benchmark and contains state for the\n// benchmark to use.\nclass BENCHMARK_EXPORT State {\n public:\n  struct StateIterator;\n  friend struct StateIterator;\n\n  // Returns iterators used to run each iteration of a benchmark using a\n  // C++11 ranged-based for loop. These functions should not be called directly.\n  //\n  // REQUIRES: The benchmark has not started running yet. Neither begin nor end\n  // have been called previously.\n  //\n  // NOTE: KeepRunning may not be used after calling either of these functions.\n  BENCHMARK_ALWAYS_INLINE StateIterator begin();\n  BENCHMARK_ALWAYS_INLINE StateIterator end();\n\n  // Returns true if the benchmark should continue through another iteration.\n  // NOTE: A benchmark may not return from the test until KeepRunning() has\n  // returned false.\n  bool KeepRunning();\n\n  // Returns true iff the benchmark should run n more iterations.\n  // REQUIRES: 'n' > 0.\n  // NOTE: A benchmark must not return from the test until KeepRunningBatch()\n  // has returned false.\n  // NOTE: KeepRunningBatch() may overshoot by up to 'n' iterations.\n  //\n  // Intended usage:\n  //   while (state.KeepRunningBatch(1000)) {\n  //     // process 1000 elements\n  //   }\n  bool KeepRunningBatch(IterationCount n);\n\n  // REQUIRES: timer is running and 'SkipWithMessage(...)' or\n  //   'SkipWithError(...)' has not been called by the current thread.\n  // Stop the benchmark timer.  If not called, the timer will be\n  // automatically stopped after the last iteration of the benchmark loop.\n  //\n  // For threaded benchmarks the PauseTiming() function only pauses the timing\n  // for the current thread.\n  //\n  // NOTE: The \"real time\" measurement is per-thread. If different threads\n  // report different measurements the largest one is reported.\n  //\n  // NOTE: PauseTiming()/ResumeTiming() are relatively\n  // heavyweight, and so their use should generally be avoided\n  // within each benchmark iteration, if possible.\n  void PauseTiming();\n\n  // REQUIRES: timer is not running and 'SkipWithMessage(...)' or\n  //   'SkipWithError(...)' has not been called by the current thread.\n  // Start the benchmark timer.  The timer is NOT running on entrance to the\n  // benchmark function. It begins running after control flow enters the\n  // benchmark loop.\n  //\n  // NOTE: PauseTiming()/ResumeTiming() are relatively\n  // heavyweight, and so their use should generally be avoided\n  // within each benchmark iteration, if possible.\n  void ResumeTiming();\n\n  // REQUIRES: 'SkipWithMessage(...)' or 'SkipWithError(...)' has not been\n  //            called previously by the current thread.\n  // Report the benchmark as resulting in being skipped with the specified\n  // 'msg'.\n  // After this call the user may explicitly 'return' from the benchmark.\n  //\n  // If the ranged-for style of benchmark loop is used, the user must explicitly\n  // break from the loop, otherwise all future iterations will be run.\n  // If the 'KeepRunning()' loop is used the current thread will automatically\n  // exit the loop at the end of the current iteration.\n  //\n  // For threaded benchmarks only the current thread stops executing and future\n  // calls to `KeepRunning()` will block until all threads have completed\n  // the `KeepRunning()` loop. If multiple threads report being skipped only the\n  // first skip message is used.\n  //\n  // NOTE: Calling 'SkipWithMessage(...)' does not cause the benchmark to exit\n  // the current scope immediately. If the function is called from within\n  // the 'KeepRunning()' loop the current iteration will finish. It is the users\n  // responsibility to exit the scope as needed.\n  void SkipWithMessage(const std::string& msg);\n\n  // REQUIRES: 'SkipWithMessage(...)' or 'SkipWithError(...)' has not been\n  //            called previously by the current thread.\n  // Report the benchmark as resulting in an error with the specified 'msg'.\n  // After this call the user may explicitly 'return' from the benchmark.\n  //\n  // If the ranged-for style of benchmark loop is used, the user must explicitly\n  // break from the loop, otherwise all future iterations will be run.\n  // If the 'KeepRunning()' loop is used the current thread will automatically\n  // exit the loop at the end of the current iteration.\n  //\n  // For threaded benchmarks only the current thread stops executing and future\n  // calls to `KeepRunning()` will block until all threads have completed\n  // the `KeepRunning()` loop. If multiple threads report an error only the\n  // first error message is used.\n  //\n  // NOTE: Calling 'SkipWithError(...)' does not cause the benchmark to exit\n  // the current scope immediately. If the function is called from within\n  // the 'KeepRunning()' loop the current iteration will finish. It is the users\n  // responsibility to exit the scope as needed.\n  void SkipWithError(const std::string& msg);\n\n  // Returns true if 'SkipWithMessage(...)' or 'SkipWithError(...)' was called.\n  bool skipped() const { return internal::NotSkipped != skipped_; }\n\n  // Returns true if an error has been reported with 'SkipWithError(...)'.\n  bool error_occurred() const { return internal::SkippedWithError == skipped_; }\n\n  // REQUIRES: called exactly once per iteration of the benchmarking loop.\n  // Set the manually measured time for this benchmark iteration, which\n  // is used instead of automatically measured time if UseManualTime() was\n  // specified.\n  //\n  // For threaded benchmarks the final value will be set to the largest\n  // reported values.\n  void SetIterationTime(double seconds);\n\n  // Set the number of bytes processed by the current benchmark\n  // execution.  This routine is typically called once at the end of a\n  // throughput oriented benchmark.\n  //\n  // REQUIRES: a benchmark has exited its benchmarking loop.\n  BENCHMARK_ALWAYS_INLINE\n  void SetBytesProcessed(int64_t bytes) {\n    counters[\"bytes_per_second\"] =\n        Counter(static_cast<double>(bytes), Counter::kIsRate, Counter::kIs1024);\n  }\n\n  BENCHMARK_ALWAYS_INLINE\n  int64_t bytes_processed() const {\n    if (counters.find(\"bytes_per_second\") != counters.end())\n      return static_cast<int64_t>(counters.at(\"bytes_per_second\"));\n    return 0;\n  }\n\n  // If this routine is called with complexity_n > 0 and complexity report is\n  // requested for the\n  // family benchmark, then current benchmark will be part of the computation\n  // and complexity_n will\n  // represent the length of N.\n  BENCHMARK_ALWAYS_INLINE\n  void SetComplexityN(int64_t complexity_n) { complexity_n_ = complexity_n; }\n\n  BENCHMARK_ALWAYS_INLINE\n  int64_t complexity_length_n() const { return complexity_n_; }\n\n  // If this routine is called with items > 0, then an items/s\n  // label is printed on the benchmark report line for the currently\n  // executing benchmark. It is typically called at the end of a processing\n  // benchmark where a processing items/second output is desired.\n  //\n  // REQUIRES: a benchmark has exited its benchmarking loop.\n  BENCHMARK_ALWAYS_INLINE\n  void SetItemsProcessed(int64_t items) {\n    counters[\"items_per_second\"] =\n        Counter(static_cast<double>(items), benchmark::Counter::kIsRate);\n  }\n\n  BENCHMARK_ALWAYS_INLINE\n  int64_t items_processed() const {\n    if (counters.find(\"items_per_second\") != counters.end())\n      return static_cast<int64_t>(counters.at(\"items_per_second\"));\n    return 0;\n  }\n\n  // If this routine is called, the specified label is printed at the\n  // end of the benchmark report line for the currently executing\n  // benchmark.  Example:\n  //  static void BM_Compress(benchmark::State& state) {\n  //    ...\n  //    double compress = input_size / output_size;\n  //    state.SetLabel(StrFormat(\"compress:%.1f%%\", 100.0*compression));\n  //  }\n  // Produces output that looks like:\n  //  BM_Compress   50         50   14115038  compress:27.3%\n  //\n  // REQUIRES: a benchmark has exited its benchmarking loop.\n  void SetLabel(const std::string& label);\n\n  // Range arguments for this run. CHECKs if the argument has been set.\n  BENCHMARK_ALWAYS_INLINE\n  int64_t range(std::size_t pos = 0) const {\n    assert(range_.size() > pos);\n    return range_[pos];\n  }\n\n  BENCHMARK_DEPRECATED_MSG(\"use 'range(0)' instead\")\n  int64_t range_x() const { return range(0); }\n\n  BENCHMARK_DEPRECATED_MSG(\"use 'range(1)' instead\")\n  int64_t range_y() const { return range(1); }\n\n  // Number of threads concurrently executing the benchmark.\n  BENCHMARK_ALWAYS_INLINE\n  int threads() const { return threads_; }\n\n  // Index of the executing thread. Values from [0, threads).\n  BENCHMARK_ALWAYS_INLINE\n  int thread_index() const { return thread_index_; }\n\n  BENCHMARK_ALWAYS_INLINE\n  IterationCount iterations() const {\n    if (BENCHMARK_BUILTIN_EXPECT(!started_, false)) {\n      return 0;\n    }\n    return max_iterations - total_iterations_ + batch_leftover_;\n  }\n\n  BENCHMARK_ALWAYS_INLINE\n  std::string name() const { return name_; }\n\n private:\n  // items we expect on the first cache line (ie 64 bytes of the struct)\n  // When total_iterations_ is 0, KeepRunning() and friends will return false.\n  // May be larger than max_iterations.\n  IterationCount total_iterations_;\n\n  // When using KeepRunningBatch(), batch_leftover_ holds the number of\n  // iterations beyond max_iters that were run. Used to track\n  // completed_iterations_ accurately.\n  IterationCount batch_leftover_;\n\n public:\n  const IterationCount max_iterations;\n\n private:\n  bool started_;\n  bool finished_;\n  internal::Skipped skipped_;\n\n  // items we don't need on the first cache line\n  std::vector<int64_t> range_;\n\n  int64_t complexity_n_;\n\n public:\n  // Container for user-defined counters.\n  UserCounters counters;\n\n private:\n  State(std::string name, IterationCount max_iters,\n        const std::vector<int64_t>& ranges, int thread_i, int n_threads,\n        internal::ThreadTimer* timer, internal::ThreadManager* manager,\n        internal::PerfCountersMeasurement* perf_counters_measurement);\n\n  void StartKeepRunning();\n  // Implementation of KeepRunning() and KeepRunningBatch().\n  // is_batch must be true unless n is 1.\n  bool KeepRunningInternal(IterationCount n, bool is_batch);\n  void FinishKeepRunning();\n\n  const std::string name_;\n  const int thread_index_;\n  const int threads_;\n\n  internal::ThreadTimer* const timer_;\n  internal::ThreadManager* const manager_;\n  internal::PerfCountersMeasurement* const perf_counters_measurement_;\n\n  friend class internal::BenchmarkInstance;\n};\n\ninline BENCHMARK_ALWAYS_INLINE bool State::KeepRunning() {\n  return KeepRunningInternal(1, /*is_batch=*/false);\n}\n\ninline BENCHMARK_ALWAYS_INLINE bool State::KeepRunningBatch(IterationCount n) {\n  return KeepRunningInternal(n, /*is_batch=*/true);\n}\n\ninline BENCHMARK_ALWAYS_INLINE bool State::KeepRunningInternal(IterationCount n,\n                                                               bool is_batch) {\n  // total_iterations_ is set to 0 by the constructor, and always set to a\n  // nonzero value by StartKepRunning().\n  assert(n > 0);\n  // n must be 1 unless is_batch is true.\n  assert(is_batch || n == 1);\n  if (BENCHMARK_BUILTIN_EXPECT(total_iterations_ >= n, true)) {\n    total_iterations_ -= n;\n    return true;\n  }\n  if (!started_) {\n    StartKeepRunning();\n    if (!skipped() && total_iterations_ >= n) {\n      total_iterations_ -= n;\n      return true;\n    }\n  }\n  // For non-batch runs, total_iterations_ must be 0 by now.\n  if (is_batch && total_iterations_ != 0) {\n    batch_leftover_ = n - total_iterations_;\n    total_iterations_ = 0;\n    return true;\n  }\n  FinishKeepRunning();\n  return false;\n}\n\nstruct State::StateIterator {\n  struct BENCHMARK_UNUSED Value {};\n  typedef std::forward_iterator_tag iterator_category;\n  typedef Value value_type;\n  typedef Value reference;\n  typedef Value pointer;\n  typedef std::ptrdiff_t difference_type;\n\n private:\n  friend class State;\n  BENCHMARK_ALWAYS_INLINE\n  StateIterator() : cached_(0), parent_() {}\n\n  BENCHMARK_ALWAYS_INLINE\n  explicit StateIterator(State* st)\n      : cached_(st->skipped() ? 0 : st->max_iterations), parent_(st) {}\n\n public:\n  BENCHMARK_ALWAYS_INLINE\n  Value operator*() const { return Value(); }\n\n  BENCHMARK_ALWAYS_INLINE\n  StateIterator& operator++() {\n    assert(cached_ > 0);\n    --cached_;\n    return *this;\n  }\n\n  BENCHMARK_ALWAYS_INLINE\n  bool operator!=(StateIterator const&) const {\n    if (BENCHMARK_BUILTIN_EXPECT(cached_ != 0, true)) return true;\n    parent_->FinishKeepRunning();\n    return false;\n  }\n\n private:\n  IterationCount cached_;\n  State* const parent_;\n};\n\ninline BENCHMARK_ALWAYS_INLINE State::StateIterator State::begin() {\n  return StateIterator(this);\n}\ninline BENCHMARK_ALWAYS_INLINE State::StateIterator State::end() {\n  StartKeepRunning();\n  return StateIterator();\n}\n\nnamespace internal {\n\ntypedef void(Function)(State&);\n\n// ------------------------------------------------------\n// Benchmark registration object.  The BENCHMARK() macro expands\n// into an internal::Benchmark* object.  Various methods can\n// be called on this object to change the properties of the benchmark.\n// Each method returns \"this\" so that multiple method calls can\n// chained into one expression.\nclass BENCHMARK_EXPORT Benchmark {\n public:\n  virtual ~Benchmark();\n\n  // Note: the following methods all return \"this\" so that multiple\n  // method calls can be chained together in one expression.\n\n  // Specify the name of the benchmark\n  Benchmark* Name(const std::string& name);\n\n  // Run this benchmark once with \"x\" as the extra argument passed\n  // to the function.\n  // REQUIRES: The function passed to the constructor must accept an arg1.\n  Benchmark* Arg(int64_t x);\n\n  // Run this benchmark with the given time unit for the generated output report\n  Benchmark* Unit(TimeUnit unit);\n\n  // Run this benchmark once for a number of values picked from the\n  // range [start..limit].  (start and limit are always picked.)\n  // REQUIRES: The function passed to the constructor must accept an arg1.\n  Benchmark* Range(int64_t start, int64_t limit);\n\n  // Run this benchmark once for all values in the range [start..limit] with\n  // specific step\n  // REQUIRES: The function passed to the constructor must accept an arg1.\n  Benchmark* DenseRange(int64_t start, int64_t limit, int step = 1);\n\n  // Run this benchmark once with \"args\" as the extra arguments passed\n  // to the function.\n  // REQUIRES: The function passed to the constructor must accept arg1, arg2 ...\n  Benchmark* Args(const std::vector<int64_t>& args);\n\n  // Equivalent to Args({x, y})\n  // NOTE: This is a legacy C++03 interface provided for compatibility only.\n  //   New code should use 'Args'.\n  Benchmark* ArgPair(int64_t x, int64_t y) {\n    std::vector<int64_t> args;\n    args.push_back(x);\n    args.push_back(y);\n    return Args(args);\n  }\n\n  // Run this benchmark once for a number of values picked from the\n  // ranges [start..limit].  (starts and limits are always picked.)\n  // REQUIRES: The function passed to the constructor must accept arg1, arg2 ...\n  Benchmark* Ranges(const std::vector<std::pair<int64_t, int64_t> >& ranges);\n\n  // Run this benchmark once for each combination of values in the (cartesian)\n  // product of the supplied argument lists.\n  // REQUIRES: The function passed to the constructor must accept arg1, arg2 ...\n  Benchmark* ArgsProduct(const std::vector<std::vector<int64_t> >& arglists);\n\n  // Equivalent to ArgNames({name})\n  Benchmark* ArgName(const std::string& name);\n\n  // Set the argument names to display in the benchmark name. If not called,\n  // only argument values will be shown.\n  Benchmark* ArgNames(const std::vector<std::string>& names);\n\n  // Equivalent to Ranges({{lo1, hi1}, {lo2, hi2}}).\n  // NOTE: This is a legacy C++03 interface provided for compatibility only.\n  //   New code should use 'Ranges'.\n  Benchmark* RangePair(int64_t lo1, int64_t hi1, int64_t lo2, int64_t hi2) {\n    std::vector<std::pair<int64_t, int64_t> > ranges;\n    ranges.push_back(std::make_pair(lo1, hi1));\n    ranges.push_back(std::make_pair(lo2, hi2));\n    return Ranges(ranges);\n  }\n\n  // Have \"setup\" and/or \"teardown\" invoked once for every benchmark run.\n  // If the benchmark is multi-threaded (will run in k threads concurrently),\n  // the setup callback will be be invoked exactly once (not k times) before\n  // each run with k threads. Time allowing (e.g. for a short benchmark), there\n  // may be multiple such runs per benchmark, each run with its own\n  // \"setup\"/\"teardown\".\n  //\n  // If the benchmark uses different size groups of threads (e.g. via\n  // ThreadRange), the above will be true for each size group.\n  //\n  // The callback will be passed a State object, which includes the number\n  // of threads, thread-index, benchmark arguments, etc.\n  //\n  // The callback must not be NULL or self-deleting.\n  Benchmark* Setup(void (*setup)(const benchmark::State&));\n  Benchmark* Teardown(void (*teardown)(const benchmark::State&));\n\n  // Pass this benchmark object to *func, which can customize\n  // the benchmark by calling various methods like Arg, Args,\n  // Threads, etc.\n  Benchmark* Apply(void (*func)(Benchmark* benchmark));\n\n  // Set the range multiplier for non-dense range. If not called, the range\n  // multiplier kRangeMultiplier will be used.\n  Benchmark* RangeMultiplier(int multiplier);\n\n  // Set the minimum amount of time to use when running this benchmark. This\n  // option overrides the `benchmark_min_time` flag.\n  // REQUIRES: `t > 0` and `Iterations` has not been called on this benchmark.\n  Benchmark* MinTime(double t);\n\n  // Set the minimum amount of time to run the benchmark before taking runtimes\n  // of this benchmark into account. This\n  // option overrides the `benchmark_min_warmup_time` flag.\n  // REQUIRES: `t >= 0` and `Iterations` has not been called on this benchmark.\n  Benchmark* MinWarmUpTime(double t);\n\n  // Specify the amount of iterations that should be run by this benchmark.\n  // This option overrides the `benchmark_min_time` flag.\n  // REQUIRES: 'n > 0' and `MinTime` has not been called on this benchmark.\n  //\n  // NOTE: This function should only be used when *exact* iteration control is\n  //   needed and never to control or limit how long a benchmark runs, where\n  // `--benchmark_min_time=<N>s` or `MinTime(...)` should be used instead.\n  Benchmark* Iterations(IterationCount n);\n\n  // Specify the amount of times to repeat this benchmark. This option overrides\n  // the `benchmark_repetitions` flag.\n  // REQUIRES: `n > 0`\n  Benchmark* Repetitions(int n);\n\n  // Specify if each repetition of the benchmark should be reported separately\n  // or if only the final statistics should be reported. If the benchmark\n  // is not repeated then the single result is always reported.\n  // Applies to *ALL* reporters (display and file).\n  Benchmark* ReportAggregatesOnly(bool value = true);\n\n  // Same as ReportAggregatesOnly(), but applies to display reporter only.\n  Benchmark* DisplayAggregatesOnly(bool value = true);\n\n  // By default, the CPU time is measured only for the main thread, which may\n  // be unrepresentative if the benchmark uses threads internally. If called,\n  // the total CPU time spent by all the threads will be measured instead.\n  // By default, only the main thread CPU time will be measured.\n  Benchmark* MeasureProcessCPUTime();\n\n  // If a particular benchmark should use the Wall clock instead of the CPU time\n  // (be it either the CPU time of the main thread only (default), or the\n  // total CPU usage of the benchmark), call this method. If called, the elapsed\n  // (wall) time will be used to control how many iterations are run, and in the\n  // printing of items/second or MB/seconds values.\n  // If not called, the CPU time used by the benchmark will be used.\n  Benchmark* UseRealTime();\n\n  // If a benchmark must measure time manually (e.g. if GPU execution time is\n  // being\n  // measured), call this method. If called, each benchmark iteration should\n  // call\n  // SetIterationTime(seconds) to report the measured time, which will be used\n  // to control how many iterations are run, and in the printing of items/second\n  // or MB/second values.\n  Benchmark* UseManualTime();\n\n  // Set the asymptotic computational complexity for the benchmark. If called\n  // the asymptotic computational complexity will be shown on the output.\n  Benchmark* Complexity(BigO complexity = benchmark::oAuto);\n\n  // Set the asymptotic computational complexity for the benchmark. If called\n  // the asymptotic computational complexity will be shown on the output.\n  Benchmark* Complexity(BigOFunc* complexity);\n\n  // Add this statistics to be computed over all the values of benchmark run\n  Benchmark* ComputeStatistics(const std::string& name,\n                               StatisticsFunc* statistics,\n                               StatisticUnit unit = kTime);\n\n  // Support for running multiple copies of the same benchmark concurrently\n  // in multiple threads.  This may be useful when measuring the scaling\n  // of some piece of code.\n\n  // Run one instance of this benchmark concurrently in t threads.\n  Benchmark* Threads(int t);\n\n  // Pick a set of values T from [min_threads,max_threads].\n  // min_threads and max_threads are always included in T.  Run this\n  // benchmark once for each value in T.  The benchmark run for a\n  // particular value t consists of t threads running the benchmark\n  // function concurrently.  For example, consider:\n  //    BENCHMARK(Foo)->ThreadRange(1,16);\n  // This will run the following benchmarks:\n  //    Foo in 1 thread\n  //    Foo in 2 threads\n  //    Foo in 4 threads\n  //    Foo in 8 threads\n  //    Foo in 16 threads\n  Benchmark* ThreadRange(int min_threads, int max_threads);\n\n  // For each value n in the range, run this benchmark once using n threads.\n  // min_threads and max_threads are always included in the range.\n  // stride specifies the increment. E.g. DenseThreadRange(1, 8, 3) starts\n  // a benchmark with 1, 4, 7 and 8 threads.\n  Benchmark* DenseThreadRange(int min_threads, int max_threads, int stride = 1);\n\n  // Equivalent to ThreadRange(NumCPUs(), NumCPUs())\n  Benchmark* ThreadPerCpu();\n\n  virtual void Run(State& state) = 0;\n\n  TimeUnit GetTimeUnit() const;\n\n protected:\n  explicit Benchmark(const std::string& name);\n  void SetName(const std::string& name);\n\n public:\n  const char* GetName() const;\n  int ArgsCnt() const;\n  const char* GetArgName(int arg) const;\n\n private:\n  friend class BenchmarkFamilies;\n  friend class BenchmarkInstance;\n\n  std::string name_;\n  AggregationReportMode aggregation_report_mode_;\n  std::vector<std::string> arg_names_;       // Args for all benchmark runs\n  std::vector<std::vector<int64_t> > args_;  // Args for all benchmark runs\n\n  TimeUnit time_unit_;\n  bool use_default_time_unit_;\n\n  int range_multiplier_;\n  double min_time_;\n  double min_warmup_time_;\n  IterationCount iterations_;\n  int repetitions_;\n  bool measure_process_cpu_time_;\n  bool use_real_time_;\n  bool use_manual_time_;\n  BigO complexity_;\n  BigOFunc* complexity_lambda_;\n  std::vector<Statistics> statistics_;\n  std::vector<int> thread_counts_;\n\n  typedef void (*callback_function)(const benchmark::State&);\n  callback_function setup_;\n  callback_function teardown_;\n\n  Benchmark(Benchmark const&)\n#if defined(BENCHMARK_HAS_CXX11)\n      = delete\n#endif\n      ;\n\n  Benchmark& operator=(Benchmark const&)\n#if defined(BENCHMARK_HAS_CXX11)\n      = delete\n#endif\n      ;\n};\n\n}  // namespace internal\n\n// Create and register a benchmark with the specified 'name' that invokes\n// the specified functor 'fn'.\n//\n// RETURNS: A pointer to the registered benchmark.\ninternal::Benchmark* RegisterBenchmark(const std::string& name,\n                                       internal::Function* fn);\n\n#if defined(BENCHMARK_HAS_CXX11)\ntemplate <class Lambda>\ninternal::Benchmark* RegisterBenchmark(const std::string& name, Lambda&& fn);\n#endif\n\n// Remove all registered benchmarks. All pointers to previously registered\n// benchmarks are invalidated.\nBENCHMARK_EXPORT void ClearRegisteredBenchmarks();\n\nnamespace internal {\n// The class used to hold all Benchmarks created from static function.\n// (ie those created using the BENCHMARK(...) macros.\nclass BENCHMARK_EXPORT FunctionBenchmark : public Benchmark {\n public:\n  FunctionBenchmark(const std::string& name, Function* func)\n      : Benchmark(name), func_(func) {}\n\n  void Run(State& st) BENCHMARK_OVERRIDE;\n\n private:\n  Function* func_;\n};\n\n#ifdef BENCHMARK_HAS_CXX11\ntemplate <class Lambda>\nclass LambdaBenchmark : public Benchmark {\n public:\n  void Run(State& st) BENCHMARK_OVERRIDE { lambda_(st); }\n\n private:\n  template <class OLambda>\n  LambdaBenchmark(const std::string& name, OLambda&& lam)\n      : Benchmark(name), lambda_(std::forward<OLambda>(lam)) {}\n\n  LambdaBenchmark(LambdaBenchmark const&) = delete;\n\n  template <class Lam>  // NOLINTNEXTLINE(readability-redundant-declaration)\n  friend Benchmark* ::benchmark::RegisterBenchmark(const std::string&, Lam&&);\n\n  Lambda lambda_;\n};\n#endif\n}  // namespace internal\n\ninline internal::Benchmark* RegisterBenchmark(const std::string& name,\n                                              internal::Function* fn) {\n  // FIXME: this should be a `std::make_unique<>()` but we don't have C++14.\n  // codechecker_intentional [cplusplus.NewDeleteLeaks]\n  return internal::RegisterBenchmarkInternal(\n      ::new internal::FunctionBenchmark(name, fn));\n}\n\n#ifdef BENCHMARK_HAS_CXX11\ntemplate <class Lambda>\ninternal::Benchmark* RegisterBenchmark(const std::string& name, Lambda&& fn) {\n  using BenchType =\n      internal::LambdaBenchmark<typename std::decay<Lambda>::type>;\n  // FIXME: this should be a `std::make_unique<>()` but we don't have C++14.\n  // codechecker_intentional [cplusplus.NewDeleteLeaks]\n  return internal::RegisterBenchmarkInternal(\n      ::new BenchType(name, std::forward<Lambda>(fn)));\n}\n#endif\n\n#if defined(BENCHMARK_HAS_CXX11) && \\\n    (!defined(BENCHMARK_GCC_VERSION) || BENCHMARK_GCC_VERSION >= 409)\ntemplate <class Lambda, class... Args>\ninternal::Benchmark* RegisterBenchmark(const std::string& name, Lambda&& fn,\n                                       Args&&... args) {\n  return benchmark::RegisterBenchmark(\n      name, [=](benchmark::State& st) { fn(st, args...); });\n}\n#else\n#define BENCHMARK_HAS_NO_VARIADIC_REGISTER_BENCHMARK\n#endif\n\n// The base class for all fixture tests.\nclass Fixture : public internal::Benchmark {\n public:\n  Fixture() : internal::Benchmark(\"\") {}\n\n  void Run(State& st) BENCHMARK_OVERRIDE {\n    this->SetUp(st);\n    this->BenchmarkCase(st);\n    this->TearDown(st);\n  }\n\n  // These will be deprecated ...\n  virtual void SetUp(const State&) {}\n  virtual void TearDown(const State&) {}\n  // ... In favor of these.\n  virtual void SetUp(State& st) { SetUp(const_cast<const State&>(st)); }\n  virtual void TearDown(State& st) { TearDown(const_cast<const State&>(st)); }\n\n protected:\n  virtual void BenchmarkCase(State&) = 0;\n};\n}  // namespace benchmark\n\n// ------------------------------------------------------\n// Macro to register benchmarks\n\n// Check that __COUNTER__ is defined and that __COUNTER__ increases by 1\n// every time it is expanded. X + 1 == X + 0 is used in case X is defined to be\n// empty. If X is empty the expression becomes (+1 == +0).\n#if defined(__COUNTER__) && (__COUNTER__ + 1 == __COUNTER__ + 0)\n#define BENCHMARK_PRIVATE_UNIQUE_ID __COUNTER__\n#else\n#define BENCHMARK_PRIVATE_UNIQUE_ID __LINE__\n#endif\n\n// Helpers for generating unique variable names\n#ifdef BENCHMARK_HAS_CXX11\n#define BENCHMARK_PRIVATE_NAME(...)                                      \\\n  BENCHMARK_PRIVATE_CONCAT(benchmark_uniq_, BENCHMARK_PRIVATE_UNIQUE_ID, \\\n                           __VA_ARGS__)\n#else\n#define BENCHMARK_PRIVATE_NAME(n) \\\n  BENCHMARK_PRIVATE_CONCAT(benchmark_uniq_, BENCHMARK_PRIVATE_UNIQUE_ID, n)\n#endif  // BENCHMARK_HAS_CXX11\n\n#define BENCHMARK_PRIVATE_CONCAT(a, b, c) BENCHMARK_PRIVATE_CONCAT2(a, b, c)\n#define BENCHMARK_PRIVATE_CONCAT2(a, b, c) a##b##c\n// Helper for concatenation with macro name expansion\n#define BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method) \\\n  BaseClass##_##Method##_Benchmark\n\n#define BENCHMARK_PRIVATE_DECLARE(n)                                 \\\n  static ::benchmark::internal::Benchmark* BENCHMARK_PRIVATE_NAME(n) \\\n      BENCHMARK_UNUSED\n\n#ifdef BENCHMARK_HAS_CXX11\n#define BENCHMARK(...)                                               \\\n  BENCHMARK_PRIVATE_DECLARE(_benchmark_) =                           \\\n      (::benchmark::internal::RegisterBenchmarkInternal(             \\\n          new ::benchmark::internal::FunctionBenchmark(#__VA_ARGS__, \\\n                                                       __VA_ARGS__)))\n#else\n#define BENCHMARK(n)                                     \\\n  BENCHMARK_PRIVATE_DECLARE(n) =                         \\\n      (::benchmark::internal::RegisterBenchmarkInternal( \\\n          new ::benchmark::internal::FunctionBenchmark(#n, n)))\n#endif  // BENCHMARK_HAS_CXX11\n\n// Old-style macros\n#define BENCHMARK_WITH_ARG(n, a) BENCHMARK(n)->Arg((a))\n#define BENCHMARK_WITH_ARG2(n, a1, a2) BENCHMARK(n)->Args({(a1), (a2)})\n#define BENCHMARK_WITH_UNIT(n, t) BENCHMARK(n)->Unit((t))\n#define BENCHMARK_RANGE(n, lo, hi) BENCHMARK(n)->Range((lo), (hi))\n#define BENCHMARK_RANGE2(n, l1, h1, l2, h2) \\\n  BENCHMARK(n)->RangePair({{(l1), (h1)}, {(l2), (h2)}})\n\n#ifdef BENCHMARK_HAS_CXX11\n\n// Register a benchmark which invokes the function specified by `func`\n// with the additional arguments specified by `...`.\n//\n// For example:\n//\n// template <class ...ExtraArgs>`\n// void BM_takes_args(benchmark::State& state, ExtraArgs&&... extra_args) {\n//  [...]\n//}\n// /* Registers a benchmark named \"BM_takes_args/int_string_test` */\n// BENCHMARK_CAPTURE(BM_takes_args, int_string_test, 42, std::string(\"abc\"));\n#define BENCHMARK_CAPTURE(func, test_case_name, ...)     \\\n  BENCHMARK_PRIVATE_DECLARE(func) =                      \\\n      (::benchmark::internal::RegisterBenchmarkInternal( \\\n          new ::benchmark::internal::FunctionBenchmark(  \\\n              #func \"/\" #test_case_name,                 \\\n              [](::benchmark::State& st) { func(st, __VA_ARGS__); })))\n\n#endif  // BENCHMARK_HAS_CXX11\n\n// This will register a benchmark for a templatized function.  For example:\n//\n// template<int arg>\n// void BM_Foo(int iters);\n//\n// BENCHMARK_TEMPLATE(BM_Foo, 1);\n//\n// will register BM_Foo<1> as a benchmark.\n#define BENCHMARK_TEMPLATE1(n, a)                        \\\n  BENCHMARK_PRIVATE_DECLARE(n) =                         \\\n      (::benchmark::internal::RegisterBenchmarkInternal( \\\n          new ::benchmark::internal::FunctionBenchmark(#n \"<\" #a \">\", n<a>)))\n\n#define BENCHMARK_TEMPLATE2(n, a, b)                                         \\\n  BENCHMARK_PRIVATE_DECLARE(n) =                                             \\\n      (::benchmark::internal::RegisterBenchmarkInternal(                     \\\n          new ::benchmark::internal::FunctionBenchmark(#n \"<\" #a \",\" #b \">\", \\\n                                                       n<a, b>)))\n\n#ifdef BENCHMARK_HAS_CXX11\n#define BENCHMARK_TEMPLATE(n, ...)                       \\\n  BENCHMARK_PRIVATE_DECLARE(n) =                         \\\n      (::benchmark::internal::RegisterBenchmarkInternal( \\\n          new ::benchmark::internal::FunctionBenchmark(  \\\n              #n \"<\" #__VA_ARGS__ \">\", n<__VA_ARGS__>)))\n#else\n#define BENCHMARK_TEMPLATE(n, a) BENCHMARK_TEMPLATE1(n, a)\n#endif\n\n#define BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method)          \\\n  class BaseClass##_##Method##_Benchmark : public BaseClass {   \\\n   public:                                                      \\\n    BaseClass##_##Method##_Benchmark() {                        \\\n      this->SetName(#BaseClass \"/\" #Method);                    \\\n    }                                                           \\\n                                                                \\\n   protected:                                                   \\\n    void BenchmarkCase(::benchmark::State&) BENCHMARK_OVERRIDE; \\\n  };\n\n#define BENCHMARK_TEMPLATE1_PRIVATE_DECLARE_F(BaseClass, Method, a) \\\n  class BaseClass##_##Method##_Benchmark : public BaseClass<a> {    \\\n   public:                                                          \\\n    BaseClass##_##Method##_Benchmark() {                            \\\n      this->SetName(#BaseClass \"<\" #a \">/\" #Method);                \\\n    }                                                               \\\n                                                                    \\\n   protected:                                                       \\\n    void BenchmarkCase(::benchmark::State&) BENCHMARK_OVERRIDE;     \\\n  };\n\n#define BENCHMARK_TEMPLATE2_PRIVATE_DECLARE_F(BaseClass, Method, a, b) \\\n  class BaseClass##_##Method##_Benchmark : public BaseClass<a, b> {    \\\n   public:                                                             \\\n    BaseClass##_##Method##_Benchmark() {                               \\\n      this->SetName(#BaseClass \"<\" #a \",\" #b \">/\" #Method);            \\\n    }                                                                  \\\n                                                                       \\\n   protected:                                                          \\\n    void BenchmarkCase(::benchmark::State&) BENCHMARK_OVERRIDE;        \\\n  };\n\n#ifdef BENCHMARK_HAS_CXX11\n#define BENCHMARK_TEMPLATE_PRIVATE_DECLARE_F(BaseClass, Method, ...)       \\\n  class BaseClass##_##Method##_Benchmark : public BaseClass<__VA_ARGS__> { \\\n   public:                                                                 \\\n    BaseClass##_##Method##_Benchmark() {                                   \\\n      this->SetName(#BaseClass \"<\" #__VA_ARGS__ \">/\" #Method);             \\\n    }                                                                      \\\n                                                                           \\\n   protected:                                                              \\\n    void BenchmarkCase(::benchmark::State&) BENCHMARK_OVERRIDE;            \\\n  };\n#else\n#define BENCHMARK_TEMPLATE_PRIVATE_DECLARE_F(n, a) \\\n  BENCHMARK_TEMPLATE1_PRIVATE_DECLARE_F(n, a)\n#endif\n\n#define BENCHMARK_DEFINE_F(BaseClass, Method)    \\\n  BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \\\n  void BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)::BenchmarkCase\n\n#define BENCHMARK_TEMPLATE1_DEFINE_F(BaseClass, Method, a)    \\\n  BENCHMARK_TEMPLATE1_PRIVATE_DECLARE_F(BaseClass, Method, a) \\\n  void BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)::BenchmarkCase\n\n#define BENCHMARK_TEMPLATE2_DEFINE_F(BaseClass, Method, a, b)    \\\n  BENCHMARK_TEMPLATE2_PRIVATE_DECLARE_F(BaseClass, Method, a, b) \\\n  void BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)::BenchmarkCase\n\n#ifdef BENCHMARK_HAS_CXX11\n#define BENCHMARK_TEMPLATE_DEFINE_F(BaseClass, Method, ...)            \\\n  BENCHMARK_TEMPLATE_PRIVATE_DECLARE_F(BaseClass, Method, __VA_ARGS__) \\\n  void BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)::BenchmarkCase\n#else\n#define BENCHMARK_TEMPLATE_DEFINE_F(BaseClass, Method, a) \\\n  BENCHMARK_TEMPLATE1_DEFINE_F(BaseClass, Method, a)\n#endif\n\n#define BENCHMARK_REGISTER_F(BaseClass, Method) \\\n  BENCHMARK_PRIVATE_REGISTER_F(BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method))\n\n#define BENCHMARK_PRIVATE_REGISTER_F(TestName) \\\n  BENCHMARK_PRIVATE_DECLARE(TestName) =        \\\n      (::benchmark::internal::RegisterBenchmarkInternal(new TestName()))\n\n// This macro will define and register a benchmark within a fixture class.\n#define BENCHMARK_F(BaseClass, Method)           \\\n  BENCHMARK_PRIVATE_DECLARE_F(BaseClass, Method) \\\n  BENCHMARK_REGISTER_F(BaseClass, Method);       \\\n  void BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)::BenchmarkCase\n\n#define BENCHMARK_TEMPLATE1_F(BaseClass, Method, a)           \\\n  BENCHMARK_TEMPLATE1_PRIVATE_DECLARE_F(BaseClass, Method, a) \\\n  BENCHMARK_REGISTER_F(BaseClass, Method);                    \\\n  void BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)::BenchmarkCase\n\n#define BENCHMARK_TEMPLATE2_F(BaseClass, Method, a, b)           \\\n  BENCHMARK_TEMPLATE2_PRIVATE_DECLARE_F(BaseClass, Method, a, b) \\\n  BENCHMARK_REGISTER_F(BaseClass, Method);                       \\\n  void BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)::BenchmarkCase\n\n#ifdef BENCHMARK_HAS_CXX11\n#define BENCHMARK_TEMPLATE_F(BaseClass, Method, ...)                   \\\n  BENCHMARK_TEMPLATE_PRIVATE_DECLARE_F(BaseClass, Method, __VA_ARGS__) \\\n  BENCHMARK_REGISTER_F(BaseClass, Method);                             \\\n  void BENCHMARK_PRIVATE_CONCAT_NAME(BaseClass, Method)::BenchmarkCase\n#else\n#define BENCHMARK_TEMPLATE_F(BaseClass, Method, a) \\\n  BENCHMARK_TEMPLATE1_F(BaseClass, Method, a)\n#endif\n\n// Helper macro to create a main routine in a test that runs the benchmarks\n// Note the workaround for Hexagon simulator passing argc != 0, argv = NULL.\n#define BENCHMARK_MAIN()                                                \\\n  int main(int argc, char** argv) {                                     \\\n    char arg0_default[] = \"benchmark\";                                  \\\n    char* args_default = arg0_default;                                  \\\n    if (!argv) {                                                        \\\n      argc = 1;                                                         \\\n      argv = &args_default;                                             \\\n    }                                                                   \\\n    ::benchmark::Initialize(&argc, argv);                               \\\n    if (::benchmark::ReportUnrecognizedArguments(argc, argv)) return 1; \\\n    ::benchmark::RunSpecifiedBenchmarks();                              \\\n    ::benchmark::Shutdown();                                            \\\n    return 0;                                                           \\\n  }                                                                     \\\n  int main(int, char**)\n\n// ------------------------------------------------------\n// Benchmark Reporters\n\nnamespace benchmark {\n\nstruct BENCHMARK_EXPORT CPUInfo {\n  struct CacheInfo {\n    std::string type;\n    int level;\n    int size;\n    int num_sharing;\n  };\n\n  enum Scaling { UNKNOWN, ENABLED, DISABLED };\n\n  int num_cpus;\n  Scaling scaling;\n  double cycles_per_second;\n  std::vector<CacheInfo> caches;\n  std::vector<double> load_avg;\n\n  static const CPUInfo& Get();\n\n private:\n  CPUInfo();\n  BENCHMARK_DISALLOW_COPY_AND_ASSIGN(CPUInfo);\n};\n\n// Adding Struct for System Information\nstruct BENCHMARK_EXPORT SystemInfo {\n  std::string name;\n  static const SystemInfo& Get();\n\n private:\n  SystemInfo();\n  BENCHMARK_DISALLOW_COPY_AND_ASSIGN(SystemInfo);\n};\n\n// BenchmarkName contains the components of the Benchmark's name\n// which allows individual fields to be modified or cleared before\n// building the final name using 'str()'.\nstruct BENCHMARK_EXPORT BenchmarkName {\n  std::string function_name;\n  std::string args;\n  std::string min_time;\n  std::string min_warmup_time;\n  std::string iterations;\n  std::string repetitions;\n  std::string time_type;\n  std::string threads;\n\n  // Return the full name of the benchmark with each non-empty\n  // field separated by a '/'\n  std::string str() const;\n};\n\n// Interface for custom benchmark result printers.\n// By default, benchmark reports are printed to stdout. However an application\n// can control the destination of the reports by calling\n// RunSpecifiedBenchmarks and passing it a custom reporter object.\n// The reporter object must implement the following interface.\nclass BENCHMARK_EXPORT BenchmarkReporter {\n public:\n  struct Context {\n    CPUInfo const& cpu_info;\n    SystemInfo const& sys_info;\n    // The number of chars in the longest benchmark name.\n    size_t name_field_width;\n    static const char* executable_name;\n    Context();\n  };\n\n  struct BENCHMARK_EXPORT Run {\n    static const int64_t no_repetition_index = -1;\n    enum RunType { RT_Iteration, RT_Aggregate };\n\n    Run()\n        : run_type(RT_Iteration),\n          aggregate_unit(kTime),\n          skipped(internal::NotSkipped),\n          iterations(1),\n          threads(1),\n          time_unit(GetDefaultTimeUnit()),\n          real_accumulated_time(0),\n          cpu_accumulated_time(0),\n          max_heapbytes_used(0),\n          complexity(oNone),\n          complexity_lambda(),\n          complexity_n(0),\n          report_big_o(false),\n          report_rms(false),\n          memory_result(NULL),\n          allocs_per_iter(0.0) {}\n\n    std::string benchmark_name() const;\n    BenchmarkName run_name;\n    int64_t family_index;\n    int64_t per_family_instance_index;\n    RunType run_type;\n    std::string aggregate_name;\n    StatisticUnit aggregate_unit;\n    std::string report_label;  // Empty if not set by benchmark.\n    internal::Skipped skipped;\n    std::string skip_message;\n\n    IterationCount iterations;\n    int64_t threads;\n    int64_t repetition_index;\n    int64_t repetitions;\n    TimeUnit time_unit;\n    double real_accumulated_time;\n    double cpu_accumulated_time;\n\n    // Return a value representing the real time per iteration in the unit\n    // specified by 'time_unit'.\n    // NOTE: If 'iterations' is zero the returned value represents the\n    // accumulated time.\n    double GetAdjustedRealTime() const;\n\n    // Return a value representing the cpu time per iteration in the unit\n    // specified by 'time_unit'.\n    // NOTE: If 'iterations' is zero the returned value represents the\n    // accumulated time.\n    double GetAdjustedCPUTime() const;\n\n    // This is set to 0.0 if memory tracing is not enabled.\n    double max_heapbytes_used;\n\n    // Keep track of arguments to compute asymptotic complexity\n    BigO complexity;\n    BigOFunc* complexity_lambda;\n    int64_t complexity_n;\n\n    // what statistics to compute from the measurements\n    const std::vector<internal::Statistics>* statistics;\n\n    // Inform print function whether the current run is a complexity report\n    bool report_big_o;\n    bool report_rms;\n\n    UserCounters counters;\n\n    // Memory metrics.\n    const MemoryManager::Result* memory_result;\n    double allocs_per_iter;\n  };\n\n  struct PerFamilyRunReports {\n    PerFamilyRunReports() : num_runs_total(0), num_runs_done(0) {}\n\n    // How many runs will all instances of this benchmark perform?\n    int num_runs_total;\n\n    // How many runs have happened already?\n    int num_runs_done;\n\n    // The reports about (non-errneous!) runs of this family.\n    std::vector<BenchmarkReporter::Run> Runs;\n  };\n\n  // Construct a BenchmarkReporter with the output stream set to 'std::cout'\n  // and the error stream set to 'std::cerr'\n  BenchmarkReporter();\n\n  // Called once for every suite of benchmarks run.\n  // The parameter \"context\" contains information that the\n  // reporter may wish to use when generating its report, for example the\n  // platform under which the benchmarks are running. The benchmark run is\n  // never started if this function returns false, allowing the reporter\n  // to skip runs based on the context information.\n  virtual bool ReportContext(const Context& context) = 0;\n\n  // Called once for each group of benchmark runs, gives information about\n  // the configurations of the runs.\n  virtual void ReportRunsConfig(double /*min_time*/,\n                                bool /*has_explicit_iters*/,\n                                IterationCount /*iters*/) {}\n\n  // Called once for each group of benchmark runs, gives information about\n  // cpu-time and heap memory usage during the benchmark run. If the group\n  // of runs contained more than two entries then 'report' contains additional\n  // elements representing the mean and standard deviation of those runs.\n  // Additionally if this group of runs was the last in a family of benchmarks\n  // 'reports' contains additional entries representing the asymptotic\n  // complexity and RMS of that benchmark family.\n  virtual void ReportRuns(const std::vector<Run>& report) = 0;\n\n  // Called once and only once after ever group of benchmarks is run and\n  // reported.\n  virtual void Finalize() {}\n\n  // REQUIRES: The object referenced by 'out' is valid for the lifetime\n  // of the reporter.\n  void SetOutputStream(std::ostream* out) {\n    assert(out);\n    output_stream_ = out;\n  }\n\n  // REQUIRES: The object referenced by 'err' is valid for the lifetime\n  // of the reporter.\n  void SetErrorStream(std::ostream* err) {\n    assert(err);\n    error_stream_ = err;\n  }\n\n  std::ostream& GetOutputStream() const { return *output_stream_; }\n\n  std::ostream& GetErrorStream() const { return *error_stream_; }\n\n  virtual ~BenchmarkReporter();\n\n  // Write a human readable string to 'out' representing the specified\n  // 'context'.\n  // REQUIRES: 'out' is non-null.\n  static void PrintBasicContext(std::ostream* out, Context const& context);\n\n private:\n  std::ostream* output_stream_;\n  std::ostream* error_stream_;\n};\n\n// Simple reporter that outputs benchmark data to the console. This is the\n// default reporter used by RunSpecifiedBenchmarks().\nclass BENCHMARK_EXPORT ConsoleReporter : public BenchmarkReporter {\n public:\n  enum OutputOptions {\n    OO_None = 0,\n    OO_Color = 1,\n    OO_Tabular = 2,\n    OO_ColorTabular = OO_Color | OO_Tabular,\n    OO_Defaults = OO_ColorTabular\n  };\n  explicit ConsoleReporter(OutputOptions opts_ = OO_Defaults)\n      : output_options_(opts_), name_field_width_(0), printed_header_(false) {}\n\n  bool ReportContext(const Context& context) BENCHMARK_OVERRIDE;\n  void ReportRuns(const std::vector<Run>& reports) BENCHMARK_OVERRIDE;\n\n protected:\n  virtual void PrintRunData(const Run& report);\n  virtual void PrintHeader(const Run& report);\n\n  OutputOptions output_options_;\n  size_t name_field_width_;\n  UserCounters prev_counters_;\n  bool printed_header_;\n};\n\nclass BENCHMARK_EXPORT JSONReporter : public BenchmarkReporter {\n public:\n  JSONReporter() : first_report_(true) {}\n  bool ReportContext(const Context& context) BENCHMARK_OVERRIDE;\n  void ReportRuns(const std::vector<Run>& reports) BENCHMARK_OVERRIDE;\n  void Finalize() BENCHMARK_OVERRIDE;\n\n private:\n  void PrintRunData(const Run& report);\n\n  bool first_report_;\n};\n\nclass BENCHMARK_EXPORT BENCHMARK_DEPRECATED_MSG(\n    \"The CSV Reporter will be removed in a future release\") CSVReporter\n    : public BenchmarkReporter {\n public:\n  CSVReporter() : printed_header_(false) {}\n  bool ReportContext(const Context& context) BENCHMARK_OVERRIDE;\n  void ReportRuns(const std::vector<Run>& reports) BENCHMARK_OVERRIDE;\n\n private:\n  void PrintRunData(const Run& report);\n\n  bool printed_header_;\n  std::set<std::string> user_counter_names_;\n};\n\ninline const char* GetTimeUnitString(TimeUnit unit) {\n  switch (unit) {\n    case kSecond:\n      return \"s\";\n    case kMillisecond:\n      return \"ms\";\n    case kMicrosecond:\n      return \"us\";\n    case kNanosecond:\n      return \"ns\";\n  }\n  BENCHMARK_UNREACHABLE();\n}\n\ninline double GetTimeUnitMultiplier(TimeUnit unit) {\n  switch (unit) {\n    case kSecond:\n      return 1;\n    case kMillisecond:\n      return 1e3;\n    case kMicrosecond:\n      return 1e6;\n    case kNanosecond:\n      return 1e9;\n  }\n  BENCHMARK_UNREACHABLE();\n}\n\n// Creates a list of integer values for the given range and multiplier.\n// This can be used together with ArgsProduct() to allow multiple ranges\n// with different multipliers.\n// Example:\n// ArgsProduct({\n//   CreateRange(0, 1024, /*multi=*/32),\n//   CreateRange(0, 100, /*multi=*/4),\n//   CreateDenseRange(0, 4, /*step=*/1),\n// });\nBENCHMARK_EXPORT\nstd::vector<int64_t> CreateRange(int64_t lo, int64_t hi, int multi);\n\n// Creates a list of integer values for the given range and step.\nBENCHMARK_EXPORT\nstd::vector<int64_t> CreateDenseRange(int64_t start, int64_t limit, int step);\n\n}  // namespace benchmark\n\n#if defined(_MSC_VER)\n#pragma warning(pop)\n#endif\n\n#endif  // BENCHMARK_BENCHMARK_H_\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/include/benchmark/export.h",
    "content": "#ifndef BENCHMARK_EXPORT_H\n#define BENCHMARK_EXPORT_H\n\n#if defined(_WIN32)\n#define EXPORT_ATTR __declspec(dllexport)\n#define IMPORT_ATTR __declspec(dllimport)\n#define NO_EXPORT_ATTR\n#define DEPRECATED_ATTR __declspec(deprecated)\n#else  // _WIN32\n#define EXPORT_ATTR __attribute__((visibility(\"default\")))\n#define IMPORT_ATTR __attribute__((visibility(\"default\")))\n#define NO_EXPORT_ATTR __attribute__((visibility(\"hidden\")))\n#define DEPRECATE_ATTR __attribute__((__deprecated__))\n#endif  // _WIN32\n\n#ifdef BENCHMARK_STATIC_DEFINE\n#define BENCHMARK_EXPORT\n#define BENCHMARK_NO_EXPORT\n#else  // BENCHMARK_STATIC_DEFINE\n#ifndef BENCHMARK_EXPORT\n#ifdef benchmark_EXPORTS\n/* We are building this library */\n#define BENCHMARK_EXPORT EXPORT_ATTR\n#else  // benchmark_EXPORTS\n/* We are using this library */\n#define BENCHMARK_EXPORT IMPORT_ATTR\n#endif  // benchmark_EXPORTS\n#endif  // !BENCHMARK_EXPORT\n\n#ifndef BENCHMARK_NO_EXPORT\n#define BENCHMARK_NO_EXPORT NO_EXPORT_ATTR\n#endif  // !BENCHMARK_NO_EXPORT\n#endif  // BENCHMARK_STATIC_DEFINE\n\n#ifndef BENCHMARK_DEPRECATED\n#define BENCHMARK_DEPRECATED DEPRECATE_ATTR\n#endif  // BENCHMARK_DEPRECATED\n\n#ifndef BENCHMARK_DEPRECATED_EXPORT\n#define BENCHMARK_DEPRECATED_EXPORT BENCHMARK_EXPORT BENCHMARK_DEPRECATED\n#endif  // BENCHMARK_DEPRECATED_EXPORT\n\n#ifndef BENCHMARK_DEPRECATED_NO_EXPORT\n#define BENCHMARK_DEPRECATED_NO_EXPORT BENCHMARK_NO_EXPORT BENCHMARK_DEPRECATED\n#endif  // BENCHMARK_DEPRECATED_EXPORT\n\n#endif /* BENCHMARK_EXPORT_H */\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/setup.py",
    "content": "import contextlib\nimport os\nimport platform\nimport shutil\nimport sysconfig\nfrom pathlib import Path\nfrom typing import List\n\nimport setuptools\nfrom setuptools.command import build_ext\n\n\nPYTHON_INCLUDE_PATH_PLACEHOLDER = \"<PYTHON_INCLUDE_PATH>\"\n\nIS_WINDOWS = platform.system() == \"Windows\"\nIS_MAC = platform.system() == \"Darwin\"\n\n\ndef _get_long_description(fp: str) -> str:\n    with open(fp, \"r\", encoding=\"utf-8\") as f:\n        return f.read()\n\n\ndef _get_version(fp: str) -> str:\n    \"\"\"Parse a version string from a file.\"\"\"\n    with open(fp, \"r\") as f:\n        for line in f:\n            if \"__version__\" in line:\n                delim = '\"'\n                return line.split(delim)[1]\n    raise RuntimeError(f\"could not find a version string in file {fp!r}.\")\n\n\ndef _parse_requirements(fp: str) -> List[str]:\n    with open(fp) as requirements:\n        return [\n            line.rstrip()\n            for line in requirements\n            if not (line.isspace() or line.startswith(\"#\"))\n        ]\n\n\n@contextlib.contextmanager\ndef temp_fill_include_path(fp: str):\n    \"\"\"Temporarily set the Python include path in a file.\"\"\"\n    with open(fp, \"r+\") as f:\n        try:\n            content = f.read()\n            replaced = content.replace(\n                PYTHON_INCLUDE_PATH_PLACEHOLDER,\n                Path(sysconfig.get_paths()['include']).as_posix(),\n            )\n            f.seek(0)\n            f.write(replaced)\n            f.truncate()\n            yield\n        finally:\n            # revert to the original content after exit\n            f.seek(0)\n            f.write(content)\n            f.truncate()\n\n\nclass BazelExtension(setuptools.Extension):\n    \"\"\"A C/C++ extension that is defined as a Bazel BUILD target.\"\"\"\n\n    def __init__(self, name: str, bazel_target: str):\n        super().__init__(name=name, sources=[])\n\n        self.bazel_target = bazel_target\n        stripped_target = bazel_target.split(\"//\")[-1]\n        self.relpath, self.target_name = stripped_target.split(\":\")\n\n\nclass BuildBazelExtension(build_ext.build_ext):\n    \"\"\"A command that runs Bazel to build a C/C++ extension.\"\"\"\n\n    def run(self):\n        for ext in self.extensions:\n            self.bazel_build(ext)\n        build_ext.build_ext.run(self)\n\n    def bazel_build(self, ext: BazelExtension):\n        \"\"\"Runs the bazel build to create the package.\"\"\"\n        with temp_fill_include_path(\"WORKSPACE\"):\n            temp_path = Path(self.build_temp)\n\n            bazel_argv = [\n                \"bazel\",\n                \"build\",\n                ext.bazel_target,\n                f\"--symlink_prefix={temp_path / 'bazel-'}\",\n                f\"--compilation_mode={'dbg' if self.debug else 'opt'}\",\n                # C++17 is required by nanobind\n                f\"--cxxopt={'/std:c++17' if IS_WINDOWS else '-std=c++17'}\",\n            ]\n\n            if IS_WINDOWS:\n                # Link with python*.lib.\n                for library_dir in self.library_dirs:\n                    bazel_argv.append(\"--linkopt=/LIBPATH:\" + library_dir)\n            elif IS_MAC:\n                if platform.machine() == \"x86_64\":\n                    # C++17 needs macOS 10.14 at minimum\n                    bazel_argv.append(\"--macos_minimum_os=10.14\")\n\n                    # cross-compilation for Mac ARM64 on GitHub Mac x86 runners.\n                    # ARCHFLAGS is set by cibuildwheel before macOS wheel builds.\n                    archflags = os.getenv(\"ARCHFLAGS\", \"\")\n                    if \"arm64\" in archflags:\n                        bazel_argv.append(\"--cpu=darwin_arm64\")\n                        bazel_argv.append(\"--macos_cpus=arm64\")\n\n                elif platform.machine() == \"arm64\":\n                    bazel_argv.append(\"--macos_minimum_os=11.0\")\n\n            self.spawn(bazel_argv)\n\n            shared_lib_suffix = '.dll' if IS_WINDOWS else '.so'\n            ext_name = ext.target_name + shared_lib_suffix\n            ext_bazel_bin_path = temp_path / 'bazel-bin' / ext.relpath / ext_name\n\n            ext_dest_path = Path(self.get_ext_fullpath(ext.name))\n            shutil.copyfile(ext_bazel_bin_path, ext_dest_path)\n\n            # explicitly call `bazel shutdown` for graceful exit\n            self.spawn([\"bazel\", \"shutdown\"])\n\n\nsetuptools.setup(\n    name=\"google_benchmark\",\n    version=_get_version(\"bindings/python/google_benchmark/__init__.py\"),\n    url=\"https://github.com/google/benchmark\",\n    description=\"A library to benchmark code snippets.\",\n    long_description=_get_long_description(\"README.md\"),\n    long_description_content_type=\"text/markdown\",\n    author=\"Google\",\n    author_email=\"benchmark-py@google.com\",\n    # Contained modules and scripts.\n    package_dir={\"\": \"bindings/python\"},\n    packages=setuptools.find_packages(\"bindings/python\"),\n    install_requires=_parse_requirements(\"bindings/python/requirements.txt\"),\n    cmdclass=dict(build_ext=BuildBazelExtension),\n    ext_modules=[\n        BazelExtension(\n            \"google_benchmark._benchmark\",\n            \"//bindings/python/google_benchmark:_benchmark\",\n        )\n    ],\n    zip_safe=False,\n    # PyPI package information.\n    classifiers=[\n        \"Development Status :: 4 - Beta\",\n        \"Intended Audience :: Developers\",\n        \"Intended Audience :: Science/Research\",\n        \"License :: OSI Approved :: Apache Software License\",\n        \"Programming Language :: Python :: 3.8\",\n        \"Programming Language :: Python :: 3.9\",\n        \"Programming Language :: Python :: 3.10\",\n        \"Programming Language :: Python :: 3.11\",\n        \"Topic :: Software Development :: Testing\",\n        \"Topic :: System :: Benchmark\",\n    ],\n    license=\"Apache 2.0\",\n    keywords=\"benchmark\",\n)\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/CMakeLists.txt",
    "content": "# Allow the source files to find headers in src/\ninclude(GNUInstallDirs)\ninclude_directories(${PROJECT_SOURCE_DIR}/src)\n\nif (DEFINED BENCHMARK_CXX_LINKER_FLAGS)\n  list(APPEND CMAKE_SHARED_LINKER_FLAGS ${BENCHMARK_CXX_LINKER_FLAGS})\n  list(APPEND CMAKE_MODULE_LINKER_FLAGS ${BENCHMARK_CXX_LINKER_FLAGS})\nendif()\n\nfile(GLOB\n  SOURCE_FILES\n    *.cc\n    ${PROJECT_SOURCE_DIR}/include/benchmark/*.h\n    ${CMAKE_CURRENT_SOURCE_DIR}/*.h)\nfile(GLOB BENCHMARK_MAIN \"benchmark_main.cc\")\nforeach(item ${BENCHMARK_MAIN})\n  list(REMOVE_ITEM SOURCE_FILES \"${item}\")\nendforeach()\n\nadd_library(benchmark ${SOURCE_FILES})\nadd_library(benchmark::benchmark ALIAS benchmark)\nset_target_properties(benchmark PROPERTIES\n  OUTPUT_NAME \"benchmark\"\n  VERSION ${GENERIC_LIB_VERSION}\n  SOVERSION ${GENERIC_LIB_SOVERSION}\n)\ntarget_include_directories(benchmark PUBLIC\n  $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>\n)\n\n# libpfm, if available\nif (HAVE_LIBPFM)\n  target_link_libraries(benchmark PRIVATE pfm)\n  target_compile_definitions(benchmark PRIVATE -DHAVE_LIBPFM)\nendif()\n\n# pthread affinity, if available\nif(HAVE_PTHREAD_AFFINITY)\n  target_compile_definitions(benchmark PRIVATE -DBENCHMARK_HAS_PTHREAD_AFFINITY)\nendif()\n\n# Link threads.\ntarget_link_libraries(benchmark PRIVATE Threads::Threads)\n\ntarget_link_libraries(benchmark PRIVATE ${BENCHMARK_CXX_LIBRARIES})\n\nif(HAVE_LIB_RT)\n  target_link_libraries(benchmark PRIVATE rt)\nendif(HAVE_LIB_RT)\n\n\n# We need extra libraries on Windows\nif(${CMAKE_SYSTEM_NAME} MATCHES \"Windows\")\n  target_link_libraries(benchmark PRIVATE shlwapi)\nendif()\n\n# We need extra libraries on Solaris\nif(${CMAKE_SYSTEM_NAME} MATCHES \"SunOS\")\n  target_link_libraries(benchmark PRIVATE kstat)\nendif()\n\nif (NOT BUILD_SHARED_LIBS)\n  target_compile_definitions(benchmark PUBLIC -DBENCHMARK_STATIC_DEFINE)\nendif()\n\n# Benchmark main library\nadd_library(benchmark_main \"benchmark_main.cc\")\nadd_library(benchmark::benchmark_main ALIAS benchmark_main)\nset_target_properties(benchmark_main PROPERTIES\n  OUTPUT_NAME \"benchmark_main\"\n  VERSION ${GENERIC_LIB_VERSION}\n  SOVERSION ${GENERIC_LIB_SOVERSION}\n  DEFINE_SYMBOL benchmark_EXPORTS\n)\ntarget_link_libraries(benchmark_main PUBLIC benchmark::benchmark)\n\nset(generated_dir \"${PROJECT_BINARY_DIR}\")\n\nset(version_config \"${generated_dir}/${PROJECT_NAME}ConfigVersion.cmake\")\nset(project_config \"${generated_dir}/${PROJECT_NAME}Config.cmake\")\nset(pkg_config \"${generated_dir}/${PROJECT_NAME}.pc\")\nset(targets_to_export benchmark benchmark_main)\nset(targets_export_name \"${PROJECT_NAME}Targets\")\n\nset(namespace \"${PROJECT_NAME}::\")\n\ninclude(CMakePackageConfigHelpers)\n\nconfigure_package_config_file (\n  ${PROJECT_SOURCE_DIR}/cmake/Config.cmake.in\n  ${project_config}\n  INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}\n  NO_SET_AND_CHECK_MACRO\n  NO_CHECK_REQUIRED_COMPONENTS_MACRO\n)\nwrite_basic_package_version_file(\n  \"${version_config}\" VERSION ${GENERIC_LIB_VERSION} COMPATIBILITY SameMajorVersion\n)\n\nconfigure_file(\"${PROJECT_SOURCE_DIR}/cmake/benchmark.pc.in\" \"${pkg_config}\" @ONLY)\n\nexport (\n  TARGETS ${targets_to_export}\n  NAMESPACE \"${namespace}\"\n  FILE ${generated_dir}/${targets_export_name}.cmake\n)\n\nif (BENCHMARK_ENABLE_INSTALL)\n  # Install target (will install the library to specified CMAKE_INSTALL_PREFIX variable)\n  install(\n    TARGETS ${targets_to_export}\n    EXPORT ${targets_export_name}\n    ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}\n    LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}\n    RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}\n    INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})\n\n  install(\n    DIRECTORY \"${PROJECT_SOURCE_DIR}/include/benchmark\"\n              \"${PROJECT_BINARY_DIR}/include/benchmark\"\n    DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}\n    FILES_MATCHING PATTERN \"*.*h\")\n\n  install(\n      FILES \"${project_config}\" \"${version_config}\"\n      DESTINATION \"${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}\")\n\n  install(\n      FILES \"${pkg_config}\"\n      DESTINATION \"${CMAKE_INSTALL_LIBDIR}/pkgconfig\")\n\n  install(\n      EXPORT \"${targets_export_name}\"\n      NAMESPACE \"${namespace}\"\n      DESTINATION \"${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}\")\nendif()\n\nif (BENCHMARK_ENABLE_DOXYGEN)\n  find_package(Doxygen REQUIRED)\n  set(DOXYGEN_QUIET YES)\n  set(DOXYGEN_RECURSIVE YES)\n  set(DOXYGEN_GENERATE_HTML YES)\n  set(DOXYGEN_GENERATE_MAN NO)\n  set(DOXYGEN_MARKDOWN_SUPPORT YES)\n  set(DOXYGEN_BUILTIN_STL_SUPPORT YES)\n  set(DOXYGEN_EXTRACT_PACKAGE YES)\n  set(DOXYGEN_EXTRACT_STATIC YES)\n  set(DOXYGEN_SHOW_INCLUDE_FILES YES)\n  set(DOXYGEN_BINARY_TOC YES)\n  set(DOXYGEN_TOC_EXPAND YES)\n  set(DOXYGEN_USE_MDFILE_AS_MAINPAGE \"index.md\")\n  doxygen_add_docs(benchmark_doxygen\n    docs\n    include\n    src\n    ALL\n    WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}\n    COMMENT \"Building documentation with Doxygen.\")\n  if (BENCHMARK_ENABLE_INSTALL AND BENCHMARK_INSTALL_DOCS)\n    install(\n      DIRECTORY \"${CMAKE_CURRENT_BINARY_DIR}/html/\"\n      DESTINATION ${CMAKE_INSTALL_DOCDIR})\n  endif()\nelse()\n  if (BENCHMARK_ENABLE_INSTALL AND BENCHMARK_INSTALL_DOCS)\n    install(\n      DIRECTORY \"${PROJECT_SOURCE_DIR}/docs/\"\n      DESTINATION ${CMAKE_INSTALL_DOCDIR})\n  endif()\nendif()\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/arraysize.h",
    "content": "#ifndef BENCHMARK_ARRAYSIZE_H_\n#define BENCHMARK_ARRAYSIZE_H_\n\n#include \"internal_macros.h\"\n\nnamespace benchmark {\nnamespace internal {\n// The arraysize(arr) macro returns the # of elements in an array arr.\n// The expression is a compile-time constant, and therefore can be\n// used in defining new arrays, for example.  If you use arraysize on\n// a pointer by mistake, you will get a compile-time error.\n//\n\n// This template function declaration is used in defining arraysize.\n// Note that the function doesn't need an implementation, as we only\n// use its type.\ntemplate <typename T, size_t N>\nchar (&ArraySizeHelper(T (&array)[N]))[N];\n\n// That gcc wants both of these prototypes seems mysterious. VC, for\n// its part, can't decide which to use (another mystery). Matching of\n// template overloads: the final frontier.\n#ifndef COMPILER_MSVC\ntemplate <typename T, size_t N>\nchar (&ArraySizeHelper(const T (&array)[N]))[N];\n#endif\n\n#define arraysize(array) (sizeof(::benchmark::internal::ArraySizeHelper(array)))\n\n}  // end namespace internal\n}  // end namespace benchmark\n\n#endif  // BENCHMARK_ARRAYSIZE_H_\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/benchmark.cc",
    "content": "// Copyright 2015 Google Inc. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"benchmark/benchmark.h\"\n\n#include \"benchmark_api_internal.h\"\n#include \"benchmark_runner.h\"\n#include \"internal_macros.h\"\n\n#ifndef BENCHMARK_OS_WINDOWS\n#if !defined(BENCHMARK_OS_FUCHSIA) && !defined(BENCHMARK_OS_QURT)\n#include <sys/resource.h>\n#endif\n#include <sys/time.h>\n#include <unistd.h>\n#endif\n\n#include <algorithm>\n#include <atomic>\n#include <condition_variable>\n#include <cstdio>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <limits>\n#include <map>\n#include <memory>\n#include <random>\n#include <string>\n#include <thread>\n#include <utility>\n\n#include \"check.h\"\n#include \"colorprint.h\"\n#include \"commandlineflags.h\"\n#include \"complexity.h\"\n#include \"counter.h\"\n#include \"internal_macros.h\"\n#include \"log.h\"\n#include \"mutex.h\"\n#include \"perf_counters.h\"\n#include \"re.h\"\n#include \"statistics.h\"\n#include \"string_util.h\"\n#include \"thread_manager.h\"\n#include \"thread_timer.h\"\n\nnamespace benchmark {\n// Print a list of benchmarks. This option overrides all other options.\nBM_DEFINE_bool(benchmark_list_tests, false);\n\n// A regular expression that specifies the set of benchmarks to execute.  If\n// this flag is empty, or if this flag is the string \\\"all\\\", all benchmarks\n// linked into the binary are run.\nBM_DEFINE_string(benchmark_filter, \"\");\n\n// Specification of how long to run the benchmark.\n//\n// It can be either an exact number of iterations (specified as `<integer>x`),\n// or a minimum number of seconds (specified as `<float>s`). If the latter\n// format (ie., min seconds) is used, the system may run the benchmark longer\n// until the results are considered significant.\n//\n// For backward compatibility, the `s` suffix may be omitted, in which case,\n// the specified number is interpreted as the number of seconds.\n//\n// For cpu-time based tests, this is the lower bound\n// on the total cpu time used by all threads that make up the test.  For\n// real-time based tests, this is the lower bound on the elapsed time of the\n// benchmark execution, regardless of number of threads.\nBM_DEFINE_string(benchmark_min_time, kDefaultMinTimeStr);\n\n// Minimum number of seconds a benchmark should be run before results should be\n// taken into account. This e.g can be necessary for benchmarks of code which\n// needs to fill some form of cache before performance is of interest.\n// Note: results gathered within this period are discarded and not used for\n// reported result.\nBM_DEFINE_double(benchmark_min_warmup_time, 0.0);\n\n// The number of runs of each benchmark. If greater than 1, the mean and\n// standard deviation of the runs will be reported.\nBM_DEFINE_int32(benchmark_repetitions, 1);\n\n// If set, enable random interleaving of repetitions of all benchmarks.\n// See http://github.com/google/benchmark/issues/1051 for details.\nBM_DEFINE_bool(benchmark_enable_random_interleaving, false);\n\n// Report the result of each benchmark repetitions. When 'true' is specified\n// only the mean, standard deviation, and other statistics are reported for\n// repeated benchmarks. Affects all reporters.\nBM_DEFINE_bool(benchmark_report_aggregates_only, false);\n\n// Display the result of each benchmark repetitions. When 'true' is specified\n// only the mean, standard deviation, and other statistics are displayed for\n// repeated benchmarks. Unlike benchmark_report_aggregates_only, only affects\n// the display reporter, but  *NOT* file reporter, which will still contain\n// all the output.\nBM_DEFINE_bool(benchmark_display_aggregates_only, false);\n\n// The format to use for console output.\n// Valid values are 'console', 'json', or 'csv'.\nBM_DEFINE_string(benchmark_format, \"console\");\n\n// The format to use for file output.\n// Valid values are 'console', 'json', or 'csv'.\nBM_DEFINE_string(benchmark_out_format, \"json\");\n\n// The file to write additional output to.\nBM_DEFINE_string(benchmark_out, \"\");\n\n// Whether to use colors in the output.  Valid values:\n// 'true'/'yes'/1, 'false'/'no'/0, and 'auto'. 'auto' means to use colors if\n// the output is being sent to a terminal and the TERM environment variable is\n// set to a terminal type that supports colors.\nBM_DEFINE_string(benchmark_color, \"auto\");\n\n// Whether to use tabular format when printing user counters to the console.\n// Valid values: 'true'/'yes'/1, 'false'/'no'/0.  Defaults to false.\nBM_DEFINE_bool(benchmark_counters_tabular, false);\n\n// List of additional perf counters to collect, in libpfm format. For more\n// information about libpfm: https://man7.org/linux/man-pages/man3/libpfm.3.html\nBM_DEFINE_string(benchmark_perf_counters, \"\");\n\n// Extra context to include in the output formatted as comma-separated key-value\n// pairs. Kept internal as it's only used for parsing from env/command line.\nBM_DEFINE_kvpairs(benchmark_context, {});\n\n// Set the default time unit to use for reports\n// Valid values are 'ns', 'us', 'ms' or 's'\nBM_DEFINE_string(benchmark_time_unit, \"\");\n\n// The level of verbose logging to output\nBM_DEFINE_int32(v, 0);\n\nnamespace internal {\n\nstd::map<std::string, std::string>* global_context = nullptr;\n\nBENCHMARK_EXPORT std::map<std::string, std::string>*& GetGlobalContext() {\n  return global_context;\n}\n\n// FIXME: wouldn't LTO mess this up?\nvoid UseCharPointer(char const volatile*) {}\n\n}  // namespace internal\n\nState::State(std::string name, IterationCount max_iters,\n             const std::vector<int64_t>& ranges, int thread_i, int n_threads,\n             internal::ThreadTimer* timer, internal::ThreadManager* manager,\n             internal::PerfCountersMeasurement* perf_counters_measurement)\n    : total_iterations_(0),\n      batch_leftover_(0),\n      max_iterations(max_iters),\n      started_(false),\n      finished_(false),\n      skipped_(internal::NotSkipped),\n      range_(ranges),\n      complexity_n_(0),\n      name_(std::move(name)),\n      thread_index_(thread_i),\n      threads_(n_threads),\n      timer_(timer),\n      manager_(manager),\n      perf_counters_measurement_(perf_counters_measurement) {\n  BM_CHECK(max_iterations != 0) << \"At least one iteration must be run\";\n  BM_CHECK_LT(thread_index_, threads_)\n      << \"thread_index must be less than threads\";\n\n  // Note: The use of offsetof below is technically undefined until C++17\n  // because State is not a standard layout type. However, all compilers\n  // currently provide well-defined behavior as an extension (which is\n  // demonstrated since constexpr evaluation must diagnose all undefined\n  // behavior). However, GCC and Clang also warn about this use of offsetof,\n  // which must be suppressed.\n#if defined(__INTEL_COMPILER)\n#pragma warning push\n#pragma warning(disable : 1875)\n#elif defined(__GNUC__)\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Winvalid-offsetof\"\n#endif\n#if defined(__NVCC__)\n#pragma nv_diagnostic push\n#pragma nv_diag_suppress 1427\n#endif\n#if defined(__NVCOMPILER)\n#pragma diagnostic push\n#pragma diag_suppress offset_in_non_POD_nonstandard\n#endif\n  // Offset tests to ensure commonly accessed data is on the first cache line.\n  const int cache_line_size = 64;\n  static_assert(\n      offsetof(State, skipped_) <= (cache_line_size - sizeof(skipped_)), \"\");\n#if defined(__INTEL_COMPILER)\n#pragma warning pop\n#elif defined(__GNUC__)\n#pragma GCC diagnostic pop\n#endif\n#if defined(__NVCC__)\n#pragma nv_diagnostic pop\n#endif\n#if defined(__NVCOMPILER)\n#pragma diagnostic pop\n#endif\n}\n\nvoid State::PauseTiming() {\n  // Add in time accumulated so far\n  BM_CHECK(started_ && !finished_ && !skipped());\n  timer_->StopTimer();\n  if (perf_counters_measurement_) {\n    std::vector<std::pair<std::string, double>> measurements;\n    if (!perf_counters_measurement_->Stop(measurements)) {\n      BM_CHECK(false) << \"Perf counters read the value failed.\";\n    }\n    for (const auto& name_and_measurement : measurements) {\n      auto name = name_and_measurement.first;\n      auto measurement = name_and_measurement.second;\n      BM_CHECK_EQ(std::fpclassify(double{counters[name]}), FP_ZERO);\n      counters[name] = Counter(measurement, Counter::kAvgIterations);\n    }\n  }\n}\n\nvoid State::ResumeTiming() {\n  BM_CHECK(started_ && !finished_ && !skipped());\n  timer_->StartTimer();\n  if (perf_counters_measurement_) {\n    perf_counters_measurement_->Start();\n  }\n}\n\nvoid State::SkipWithMessage(const std::string& msg) {\n  skipped_ = internal::SkippedWithMessage;\n  {\n    MutexLock l(manager_->GetBenchmarkMutex());\n    if (internal::NotSkipped == manager_->results.skipped_) {\n      manager_->results.skip_message_ = msg;\n      manager_->results.skipped_ = skipped_;\n    }\n  }\n  total_iterations_ = 0;\n  if (timer_->running()) timer_->StopTimer();\n}\n\nvoid State::SkipWithError(const std::string& msg) {\n  skipped_ = internal::SkippedWithError;\n  {\n    MutexLock l(manager_->GetBenchmarkMutex());\n    if (internal::NotSkipped == manager_->results.skipped_) {\n      manager_->results.skip_message_ = msg;\n      manager_->results.skipped_ = skipped_;\n    }\n  }\n  total_iterations_ = 0;\n  if (timer_->running()) timer_->StopTimer();\n}\n\nvoid State::SetIterationTime(double seconds) {\n  timer_->SetIterationTime(seconds);\n}\n\nvoid State::SetLabel(const std::string& label) {\n  MutexLock l(manager_->GetBenchmarkMutex());\n  manager_->results.report_label_ = label;\n}\n\nvoid State::StartKeepRunning() {\n  BM_CHECK(!started_ && !finished_);\n  started_ = true;\n  total_iterations_ = skipped() ? 0 : max_iterations;\n  manager_->StartStopBarrier();\n  if (!skipped()) ResumeTiming();\n}\n\nvoid State::FinishKeepRunning() {\n  BM_CHECK(started_ && (!finished_ || skipped()));\n  if (!skipped()) {\n    PauseTiming();\n  }\n  // Total iterations has now wrapped around past 0. Fix this.\n  total_iterations_ = 0;\n  finished_ = true;\n  manager_->StartStopBarrier();\n}\n\nnamespace internal {\nnamespace {\n\n// Flushes streams after invoking reporter methods that write to them. This\n// ensures users get timely updates even when streams are not line-buffered.\nvoid FlushStreams(BenchmarkReporter* reporter) {\n  if (!reporter) return;\n  std::flush(reporter->GetOutputStream());\n  std::flush(reporter->GetErrorStream());\n}\n\n// Reports in both display and file reporters.\nvoid Report(BenchmarkReporter* display_reporter,\n            BenchmarkReporter* file_reporter, const RunResults& run_results) {\n  auto report_one = [](BenchmarkReporter* reporter, bool aggregates_only,\n                       const RunResults& results) {\n    assert(reporter);\n    // If there are no aggregates, do output non-aggregates.\n    aggregates_only &= !results.aggregates_only.empty();\n    if (!aggregates_only) reporter->ReportRuns(results.non_aggregates);\n    if (!results.aggregates_only.empty())\n      reporter->ReportRuns(results.aggregates_only);\n  };\n\n  report_one(display_reporter, run_results.display_report_aggregates_only,\n             run_results);\n  if (file_reporter)\n    report_one(file_reporter, run_results.file_report_aggregates_only,\n               run_results);\n\n  FlushStreams(display_reporter);\n  FlushStreams(file_reporter);\n}\n\nvoid RunBenchmarks(const std::vector<BenchmarkInstance>& benchmarks,\n                   BenchmarkReporter* display_reporter,\n                   BenchmarkReporter* file_reporter) {\n  // Note the file_reporter can be null.\n  BM_CHECK(display_reporter != nullptr);\n\n  // Determine the width of the name field using a minimum width of 10.\n  bool might_have_aggregates = FLAGS_benchmark_repetitions > 1;\n  size_t name_field_width = 10;\n  size_t stat_field_width = 0;\n  for (const BenchmarkInstance& benchmark : benchmarks) {\n    name_field_width =\n        std::max<size_t>(name_field_width, benchmark.name().str().size());\n    might_have_aggregates |= benchmark.repetitions() > 1;\n\n    for (const auto& Stat : benchmark.statistics())\n      stat_field_width = std::max<size_t>(stat_field_width, Stat.name_.size());\n  }\n  if (might_have_aggregates) name_field_width += 1 + stat_field_width;\n\n  // Print header here\n  BenchmarkReporter::Context context;\n  context.name_field_width = name_field_width;\n\n  // Keep track of running times of all instances of each benchmark family.\n  std::map<int /*family_index*/, BenchmarkReporter::PerFamilyRunReports>\n      per_family_reports;\n\n  if (display_reporter->ReportContext(context) &&\n      (!file_reporter || file_reporter->ReportContext(context))) {\n    FlushStreams(display_reporter);\n    FlushStreams(file_reporter);\n\n    size_t num_repetitions_total = 0;\n\n    // This perfcounters object needs to be created before the runners vector\n    // below so it outlasts their lifetime.\n    PerfCountersMeasurement perfcounters(\n        StrSplit(FLAGS_benchmark_perf_counters, ','));\n\n    // Vector of benchmarks to run\n    std::vector<internal::BenchmarkRunner> runners;\n    runners.reserve(benchmarks.size());\n\n    // Count the number of benchmarks with threads to warn the user in case\n    // performance counters are used.\n    int benchmarks_with_threads = 0;\n\n    // Loop through all benchmarks\n    for (const BenchmarkInstance& benchmark : benchmarks) {\n      BenchmarkReporter::PerFamilyRunReports* reports_for_family = nullptr;\n      if (benchmark.complexity() != oNone)\n        reports_for_family = &per_family_reports[benchmark.family_index()];\n      benchmarks_with_threads += (benchmark.threads() > 0);\n      runners.emplace_back(benchmark, &perfcounters, reports_for_family);\n      int num_repeats_of_this_instance = runners.back().GetNumRepeats();\n      num_repetitions_total += num_repeats_of_this_instance;\n      if (reports_for_family)\n        reports_for_family->num_runs_total += num_repeats_of_this_instance;\n    }\n    assert(runners.size() == benchmarks.size() && \"Unexpected runner count.\");\n\n    // The use of performance counters with threads would be unintuitive for\n    // the average user so we need to warn them about this case\n    if ((benchmarks_with_threads > 0) && (perfcounters.num_counters() > 0)) {\n      GetErrorLogInstance()\n          << \"***WARNING*** There are \" << benchmarks_with_threads\n          << \" benchmarks with threads and \" << perfcounters.num_counters()\n          << \" performance counters were requested. Beware counters will \"\n             \"reflect the combined usage across all \"\n             \"threads.\\n\";\n    }\n\n    std::vector<size_t> repetition_indices;\n    repetition_indices.reserve(num_repetitions_total);\n    for (size_t runner_index = 0, num_runners = runners.size();\n         runner_index != num_runners; ++runner_index) {\n      const internal::BenchmarkRunner& runner = runners[runner_index];\n      std::fill_n(std::back_inserter(repetition_indices),\n                  runner.GetNumRepeats(), runner_index);\n    }\n    assert(repetition_indices.size() == num_repetitions_total &&\n           \"Unexpected number of repetition indexes.\");\n\n    if (FLAGS_benchmark_enable_random_interleaving) {\n      std::random_device rd;\n      std::mt19937 g(rd());\n      std::shuffle(repetition_indices.begin(), repetition_indices.end(), g);\n    }\n\n    for (size_t repetition_index : repetition_indices) {\n      internal::BenchmarkRunner& runner = runners[repetition_index];\n      runner.DoOneRepetition();\n      if (runner.HasRepeatsRemaining()) continue;\n      // FIXME: report each repetition separately, not all of them in bulk.\n\n      display_reporter->ReportRunsConfig(\n          runner.GetMinTime(), runner.HasExplicitIters(), runner.GetIters());\n      if (file_reporter)\n        file_reporter->ReportRunsConfig(\n            runner.GetMinTime(), runner.HasExplicitIters(), runner.GetIters());\n\n      RunResults run_results = runner.GetResults();\n\n      // Maybe calculate complexity report\n      if (const auto* reports_for_family = runner.GetReportsForFamily()) {\n        if (reports_for_family->num_runs_done ==\n            reports_for_family->num_runs_total) {\n          auto additional_run_stats = ComputeBigO(reports_for_family->Runs);\n          run_results.aggregates_only.insert(run_results.aggregates_only.end(),\n                                             additional_run_stats.begin(),\n                                             additional_run_stats.end());\n          per_family_reports.erase(\n              static_cast<int>(reports_for_family->Runs.front().family_index));\n        }\n      }\n\n      Report(display_reporter, file_reporter, run_results);\n    }\n  }\n  display_reporter->Finalize();\n  if (file_reporter) file_reporter->Finalize();\n  FlushStreams(display_reporter);\n  FlushStreams(file_reporter);\n}\n\n// Disable deprecated warnings temporarily because we need to reference\n// CSVReporter but don't want to trigger -Werror=-Wdeprecated-declarations\nBENCHMARK_DISABLE_DEPRECATED_WARNING\n\nstd::unique_ptr<BenchmarkReporter> CreateReporter(\n    std::string const& name, ConsoleReporter::OutputOptions output_opts) {\n  typedef std::unique_ptr<BenchmarkReporter> PtrType;\n  if (name == \"console\") {\n    return PtrType(new ConsoleReporter(output_opts));\n  }\n  if (name == \"json\") {\n    return PtrType(new JSONReporter());\n  }\n  if (name == \"csv\") {\n    return PtrType(new CSVReporter());\n  }\n  std::cerr << \"Unexpected format: '\" << name << \"'\\n\";\n  std::exit(1);\n}\n\nBENCHMARK_RESTORE_DEPRECATED_WARNING\n\n}  // end namespace\n\nbool IsZero(double n) {\n  return std::abs(n) < std::numeric_limits<double>::epsilon();\n}\n\nConsoleReporter::OutputOptions GetOutputOptions(bool force_no_color) {\n  int output_opts = ConsoleReporter::OO_Defaults;\n  auto is_benchmark_color = [force_no_color]() -> bool {\n    if (force_no_color) {\n      return false;\n    }\n    if (FLAGS_benchmark_color == \"auto\") {\n      return IsColorTerminal();\n    }\n    return IsTruthyFlagValue(FLAGS_benchmark_color);\n  };\n  if (is_benchmark_color()) {\n    output_opts |= ConsoleReporter::OO_Color;\n  } else {\n    output_opts &= ~ConsoleReporter::OO_Color;\n  }\n  if (FLAGS_benchmark_counters_tabular) {\n    output_opts |= ConsoleReporter::OO_Tabular;\n  } else {\n    output_opts &= ~ConsoleReporter::OO_Tabular;\n  }\n  return static_cast<ConsoleReporter::OutputOptions>(output_opts);\n}\n\n}  // end namespace internal\n\nBenchmarkReporter* CreateDefaultDisplayReporter() {\n  static auto default_display_reporter =\n      internal::CreateReporter(FLAGS_benchmark_format,\n                               internal::GetOutputOptions())\n          .release();\n  return default_display_reporter;\n}\n\nsize_t RunSpecifiedBenchmarks() {\n  return RunSpecifiedBenchmarks(nullptr, nullptr, FLAGS_benchmark_filter);\n}\n\nsize_t RunSpecifiedBenchmarks(std::string spec) {\n  return RunSpecifiedBenchmarks(nullptr, nullptr, std::move(spec));\n}\n\nsize_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter) {\n  return RunSpecifiedBenchmarks(display_reporter, nullptr,\n                                FLAGS_benchmark_filter);\n}\n\nsize_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter,\n                              std::string spec) {\n  return RunSpecifiedBenchmarks(display_reporter, nullptr, std::move(spec));\n}\n\nsize_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter,\n                              BenchmarkReporter* file_reporter) {\n  return RunSpecifiedBenchmarks(display_reporter, file_reporter,\n                                FLAGS_benchmark_filter);\n}\n\nsize_t RunSpecifiedBenchmarks(BenchmarkReporter* display_reporter,\n                              BenchmarkReporter* file_reporter,\n                              std::string spec) {\n  if (spec.empty() || spec == \"all\")\n    spec = \".\";  // Regexp that matches all benchmarks\n\n  // Setup the reporters\n  std::ofstream output_file;\n  std::unique_ptr<BenchmarkReporter> default_display_reporter;\n  std::unique_ptr<BenchmarkReporter> default_file_reporter;\n  if (!display_reporter) {\n    default_display_reporter.reset(CreateDefaultDisplayReporter());\n    display_reporter = default_display_reporter.get();\n  }\n  auto& Out = display_reporter->GetOutputStream();\n  auto& Err = display_reporter->GetErrorStream();\n\n  std::string const& fname = FLAGS_benchmark_out;\n  if (fname.empty() && file_reporter) {\n    Err << \"A custom file reporter was provided but \"\n           \"--benchmark_out=<file> was not specified.\"\n        << std::endl;\n    std::exit(1);\n  }\n  if (!fname.empty()) {\n    output_file.open(fname);\n    if (!output_file.is_open()) {\n      Err << \"invalid file name: '\" << fname << \"'\" << std::endl;\n      std::exit(1);\n    }\n    if (!file_reporter) {\n      default_file_reporter = internal::CreateReporter(\n          FLAGS_benchmark_out_format, ConsoleReporter::OO_None);\n      file_reporter = default_file_reporter.get();\n    }\n    file_reporter->SetOutputStream(&output_file);\n    file_reporter->SetErrorStream(&output_file);\n  }\n\n  std::vector<internal::BenchmarkInstance> benchmarks;\n  if (!FindBenchmarksInternal(spec, &benchmarks, &Err)) return 0;\n\n  if (benchmarks.empty()) {\n    Err << \"Failed to match any benchmarks against regex: \" << spec << \"\\n\";\n    return 0;\n  }\n\n  if (FLAGS_benchmark_list_tests) {\n    for (auto const& benchmark : benchmarks)\n      Out << benchmark.name().str() << \"\\n\";\n  } else {\n    internal::RunBenchmarks(benchmarks, display_reporter, file_reporter);\n  }\n\n  return benchmarks.size();\n}\n\nnamespace {\n// stores the time unit benchmarks use by default\nTimeUnit default_time_unit = kNanosecond;\n}  // namespace\n\nTimeUnit GetDefaultTimeUnit() { return default_time_unit; }\n\nvoid SetDefaultTimeUnit(TimeUnit unit) { default_time_unit = unit; }\n\nstd::string GetBenchmarkFilter() { return FLAGS_benchmark_filter; }\n\nvoid SetBenchmarkFilter(std::string value) {\n  FLAGS_benchmark_filter = std::move(value);\n}\n\nint32_t GetBenchmarkVerbosity() { return FLAGS_v; }\n\nvoid RegisterMemoryManager(MemoryManager* manager) {\n  internal::memory_manager = manager;\n}\n\nvoid AddCustomContext(const std::string& key, const std::string& value) {\n  if (internal::global_context == nullptr) {\n    internal::global_context = new std::map<std::string, std::string>();\n  }\n  if (!internal::global_context->emplace(key, value).second) {\n    std::cerr << \"Failed to add custom context \\\"\" << key << \"\\\" as it already \"\n              << \"exists with value \\\"\" << value << \"\\\"\\n\";\n  }\n}\n\nnamespace internal {\n\nvoid (*HelperPrintf)();\n\nvoid PrintUsageAndExit() {\n  HelperPrintf();\n  exit(0);\n}\n\nvoid SetDefaultTimeUnitFromFlag(const std::string& time_unit_flag) {\n  if (time_unit_flag == \"s\") {\n    return SetDefaultTimeUnit(kSecond);\n  }\n  if (time_unit_flag == \"ms\") {\n    return SetDefaultTimeUnit(kMillisecond);\n  }\n  if (time_unit_flag == \"us\") {\n    return SetDefaultTimeUnit(kMicrosecond);\n  }\n  if (time_unit_flag == \"ns\") {\n    return SetDefaultTimeUnit(kNanosecond);\n  }\n  if (!time_unit_flag.empty()) {\n    PrintUsageAndExit();\n  }\n}\n\nvoid ParseCommandLineFlags(int* argc, char** argv) {\n  using namespace benchmark;\n  BenchmarkReporter::Context::executable_name =\n      (argc && *argc > 0) ? argv[0] : \"unknown\";\n  for (int i = 1; argc && i < *argc; ++i) {\n    if (ParseBoolFlag(argv[i], \"benchmark_list_tests\",\n                      &FLAGS_benchmark_list_tests) ||\n        ParseStringFlag(argv[i], \"benchmark_filter\", &FLAGS_benchmark_filter) ||\n        ParseStringFlag(argv[i], \"benchmark_min_time\",\n                        &FLAGS_benchmark_min_time) ||\n        ParseDoubleFlag(argv[i], \"benchmark_min_warmup_time\",\n                        &FLAGS_benchmark_min_warmup_time) ||\n        ParseInt32Flag(argv[i], \"benchmark_repetitions\",\n                       &FLAGS_benchmark_repetitions) ||\n        ParseBoolFlag(argv[i], \"benchmark_enable_random_interleaving\",\n                      &FLAGS_benchmark_enable_random_interleaving) ||\n        ParseBoolFlag(argv[i], \"benchmark_report_aggregates_only\",\n                      &FLAGS_benchmark_report_aggregates_only) ||\n        ParseBoolFlag(argv[i], \"benchmark_display_aggregates_only\",\n                      &FLAGS_benchmark_display_aggregates_only) ||\n        ParseStringFlag(argv[i], \"benchmark_format\", &FLAGS_benchmark_format) ||\n        ParseStringFlag(argv[i], \"benchmark_out\", &FLAGS_benchmark_out) ||\n        ParseStringFlag(argv[i], \"benchmark_out_format\",\n                        &FLAGS_benchmark_out_format) ||\n        ParseStringFlag(argv[i], \"benchmark_color\", &FLAGS_benchmark_color) ||\n        ParseBoolFlag(argv[i], \"benchmark_counters_tabular\",\n                      &FLAGS_benchmark_counters_tabular) ||\n        ParseStringFlag(argv[i], \"benchmark_perf_counters\",\n                        &FLAGS_benchmark_perf_counters) ||\n        ParseKeyValueFlag(argv[i], \"benchmark_context\",\n                          &FLAGS_benchmark_context) ||\n        ParseStringFlag(argv[i], \"benchmark_time_unit\",\n                        &FLAGS_benchmark_time_unit) ||\n        ParseInt32Flag(argv[i], \"v\", &FLAGS_v)) {\n      for (int j = i; j != *argc - 1; ++j) argv[j] = argv[j + 1];\n\n      --(*argc);\n      --i;\n    } else if (IsFlag(argv[i], \"help\")) {\n      PrintUsageAndExit();\n    }\n  }\n  for (auto const* flag :\n       {&FLAGS_benchmark_format, &FLAGS_benchmark_out_format}) {\n    if (*flag != \"console\" && *flag != \"json\" && *flag != \"csv\") {\n      PrintUsageAndExit();\n    }\n  }\n  SetDefaultTimeUnitFromFlag(FLAGS_benchmark_time_unit);\n  if (FLAGS_benchmark_color.empty()) {\n    PrintUsageAndExit();\n  }\n  for (const auto& kv : FLAGS_benchmark_context) {\n    AddCustomContext(kv.first, kv.second);\n  }\n}\n\nint InitializeStreams() {\n  static std::ios_base::Init init;\n  return 0;\n}\n\n}  // end namespace internal\n\nvoid PrintDefaultHelp() {\n  fprintf(stdout,\n          \"benchmark\"\n          \" [--benchmark_list_tests={true|false}]\\n\"\n          \"          [--benchmark_filter=<regex>]\\n\"\n          \"          [--benchmark_min_time=`<integer>x` OR `<float>s` ]\\n\"\n          \"          [--benchmark_min_warmup_time=<min_warmup_time>]\\n\"\n          \"          [--benchmark_repetitions=<num_repetitions>]\\n\"\n          \"          [--benchmark_enable_random_interleaving={true|false}]\\n\"\n          \"          [--benchmark_report_aggregates_only={true|false}]\\n\"\n          \"          [--benchmark_display_aggregates_only={true|false}]\\n\"\n          \"          [--benchmark_format=<console|json|csv>]\\n\"\n          \"          [--benchmark_out=<filename>]\\n\"\n          \"          [--benchmark_out_format=<json|console|csv>]\\n\"\n          \"          [--benchmark_color={auto|true|false}]\\n\"\n          \"          [--benchmark_counters_tabular={true|false}]\\n\"\n#if defined HAVE_LIBPFM\n          \"          [--benchmark_perf_counters=<counter>,...]\\n\"\n#endif\n          \"          [--benchmark_context=<key>=<value>,...]\\n\"\n          \"          [--benchmark_time_unit={ns|us|ms|s}]\\n\"\n          \"          [--v=<verbosity>]\\n\");\n}\n\nvoid Initialize(int* argc, char** argv, void (*HelperPrintf)()) {\n  internal::HelperPrintf = HelperPrintf;\n  internal::ParseCommandLineFlags(argc, argv);\n  internal::LogLevel() = FLAGS_v;\n}\n\nvoid Shutdown() { delete internal::global_context; }\n\nbool ReportUnrecognizedArguments(int argc, char** argv) {\n  for (int i = 1; i < argc; ++i) {\n    fprintf(stderr, \"%s: error: unrecognized command-line flag: %s\\n\", argv[0],\n            argv[i]);\n  }\n  return argc > 1;\n}\n\n}  // end namespace benchmark\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/benchmark_api_internal.cc",
    "content": "#include \"benchmark_api_internal.h\"\n\n#include <cinttypes>\n\n#include \"string_util.h\"\n\nnamespace benchmark {\nnamespace internal {\n\nBenchmarkInstance::BenchmarkInstance(Benchmark* benchmark, int family_idx,\n                                     int per_family_instance_idx,\n                                     const std::vector<int64_t>& args,\n                                     int thread_count)\n    : benchmark_(*benchmark),\n      family_index_(family_idx),\n      per_family_instance_index_(per_family_instance_idx),\n      aggregation_report_mode_(benchmark_.aggregation_report_mode_),\n      args_(args),\n      time_unit_(benchmark_.GetTimeUnit()),\n      measure_process_cpu_time_(benchmark_.measure_process_cpu_time_),\n      use_real_time_(benchmark_.use_real_time_),\n      use_manual_time_(benchmark_.use_manual_time_),\n      complexity_(benchmark_.complexity_),\n      complexity_lambda_(benchmark_.complexity_lambda_),\n      statistics_(benchmark_.statistics_),\n      repetitions_(benchmark_.repetitions_),\n      min_time_(benchmark_.min_time_),\n      min_warmup_time_(benchmark_.min_warmup_time_),\n      iterations_(benchmark_.iterations_),\n      threads_(thread_count) {\n  name_.function_name = benchmark_.name_;\n\n  size_t arg_i = 0;\n  for (const auto& arg : args) {\n    if (!name_.args.empty()) {\n      name_.args += '/';\n    }\n\n    if (arg_i < benchmark->arg_names_.size()) {\n      const auto& arg_name = benchmark_.arg_names_[arg_i];\n      if (!arg_name.empty()) {\n        name_.args += StrFormat(\"%s:\", arg_name.c_str());\n      }\n    }\n\n    name_.args += StrFormat(\"%\" PRId64, arg);\n    ++arg_i;\n  }\n\n  if (!IsZero(benchmark->min_time_)) {\n    name_.min_time = StrFormat(\"min_time:%0.3f\", benchmark_.min_time_);\n  }\n\n  if (!IsZero(benchmark->min_warmup_time_)) {\n    name_.min_warmup_time =\n        StrFormat(\"min_warmup_time:%0.3f\", benchmark_.min_warmup_time_);\n  }\n\n  if (benchmark_.iterations_ != 0) {\n    name_.iterations = StrFormat(\n        \"iterations:%lu\", static_cast<unsigned long>(benchmark_.iterations_));\n  }\n\n  if (benchmark_.repetitions_ != 0) {\n    name_.repetitions = StrFormat(\"repeats:%d\", benchmark_.repetitions_);\n  }\n\n  if (benchmark_.measure_process_cpu_time_) {\n    name_.time_type = \"process_time\";\n  }\n\n  if (benchmark_.use_manual_time_) {\n    if (!name_.time_type.empty()) {\n      name_.time_type += '/';\n    }\n    name_.time_type += \"manual_time\";\n  } else if (benchmark_.use_real_time_) {\n    if (!name_.time_type.empty()) {\n      name_.time_type += '/';\n    }\n    name_.time_type += \"real_time\";\n  }\n\n  if (!benchmark_.thread_counts_.empty()) {\n    name_.threads = StrFormat(\"threads:%d\", threads_);\n  }\n\n  setup_ = benchmark_.setup_;\n  teardown_ = benchmark_.teardown_;\n}\n\nState BenchmarkInstance::Run(\n    IterationCount iters, int thread_id, internal::ThreadTimer* timer,\n    internal::ThreadManager* manager,\n    internal::PerfCountersMeasurement* perf_counters_measurement) const {\n  State st(name_.function_name, iters, args_, thread_id, threads_, timer,\n           manager, perf_counters_measurement);\n  benchmark_.Run(st);\n  return st;\n}\n\nvoid BenchmarkInstance::Setup() const {\n  if (setup_) {\n    State st(name_.function_name, /*iters*/ 1, args_, /*thread_id*/ 0, threads_,\n             nullptr, nullptr, nullptr);\n    setup_(st);\n  }\n}\n\nvoid BenchmarkInstance::Teardown() const {\n  if (teardown_) {\n    State st(name_.function_name, /*iters*/ 1, args_, /*thread_id*/ 0, threads_,\n             nullptr, nullptr, nullptr);\n    teardown_(st);\n  }\n}\n}  // namespace internal\n}  // namespace benchmark\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/benchmark_api_internal.h",
    "content": "#ifndef BENCHMARK_API_INTERNAL_H\n#define BENCHMARK_API_INTERNAL_H\n\n#include <cmath>\n#include <iosfwd>\n#include <limits>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include \"benchmark/benchmark.h\"\n#include \"commandlineflags.h\"\n\nnamespace benchmark {\nnamespace internal {\n\n// Information kept per benchmark we may want to run\nclass BenchmarkInstance {\n public:\n  BenchmarkInstance(Benchmark* benchmark, int family_index,\n                    int per_family_instance_index,\n                    const std::vector<int64_t>& args, int threads);\n\n  const BenchmarkName& name() const { return name_; }\n  int family_index() const { return family_index_; }\n  int per_family_instance_index() const { return per_family_instance_index_; }\n  AggregationReportMode aggregation_report_mode() const {\n    return aggregation_report_mode_;\n  }\n  TimeUnit time_unit() const { return time_unit_; }\n  bool measure_process_cpu_time() const { return measure_process_cpu_time_; }\n  bool use_real_time() const { return use_real_time_; }\n  bool use_manual_time() const { return use_manual_time_; }\n  BigO complexity() const { return complexity_; }\n  BigOFunc* complexity_lambda() const { return complexity_lambda_; }\n  const std::vector<Statistics>& statistics() const { return statistics_; }\n  int repetitions() const { return repetitions_; }\n  double min_time() const { return min_time_; }\n  double min_warmup_time() const { return min_warmup_time_; }\n  IterationCount iterations() const { return iterations_; }\n  int threads() const { return threads_; }\n  void Setup() const;\n  void Teardown() const;\n\n  State Run(IterationCount iters, int thread_id, internal::ThreadTimer* timer,\n            internal::ThreadManager* manager,\n            internal::PerfCountersMeasurement* perf_counters_measurement) const;\n\n private:\n  BenchmarkName name_;\n  Benchmark& benchmark_;\n  const int family_index_;\n  const int per_family_instance_index_;\n  AggregationReportMode aggregation_report_mode_;\n  const std::vector<int64_t>& args_;\n  TimeUnit time_unit_;\n  bool measure_process_cpu_time_;\n  bool use_real_time_;\n  bool use_manual_time_;\n  BigO complexity_;\n  BigOFunc* complexity_lambda_;\n  UserCounters counters_;\n  const std::vector<Statistics>& statistics_;\n  int repetitions_;\n  double min_time_;\n  double min_warmup_time_;\n  IterationCount iterations_;\n  int threads_;  // Number of concurrent threads to us\n\n  typedef void (*callback_function)(const benchmark::State&);\n  callback_function setup_ = nullptr;\n  callback_function teardown_ = nullptr;\n};\n\nbool FindBenchmarksInternal(const std::string& re,\n                            std::vector<BenchmarkInstance>* benchmarks,\n                            std::ostream* Err);\n\nbool IsZero(double n);\n\nBENCHMARK_EXPORT\nConsoleReporter::OutputOptions GetOutputOptions(bool force_no_color = false);\n\n}  // end namespace internal\n}  // end namespace benchmark\n\n#endif  // BENCHMARK_API_INTERNAL_H\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/benchmark_main.cc",
    "content": "// Copyright 2018 Google Inc. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"benchmark/benchmark.h\"\n\nBENCHMARK_EXPORT int main(int, char**);\nBENCHMARK_MAIN();\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/benchmark_name.cc",
    "content": "// Copyright 2015 Google Inc. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include <benchmark/benchmark.h>\n\nnamespace benchmark {\n\nnamespace {\n\n// Compute the total size of a pack of std::strings\nsize_t size_impl() { return 0; }\n\ntemplate <typename Head, typename... Tail>\nsize_t size_impl(const Head& head, const Tail&... tail) {\n  return head.size() + size_impl(tail...);\n}\n\n// Join a pack of std::strings using a delimiter\n// TODO: use absl::StrJoin\nvoid join_impl(std::string&, char) {}\n\ntemplate <typename Head, typename... Tail>\nvoid join_impl(std::string& s, const char delimiter, const Head& head,\n               const Tail&... tail) {\n  if (!s.empty() && !head.empty()) {\n    s += delimiter;\n  }\n\n  s += head;\n\n  join_impl(s, delimiter, tail...);\n}\n\ntemplate <typename... Ts>\nstd::string join(char delimiter, const Ts&... ts) {\n  std::string s;\n  s.reserve(sizeof...(Ts) + size_impl(ts...));\n  join_impl(s, delimiter, ts...);\n  return s;\n}\n}  // namespace\n\nBENCHMARK_EXPORT\nstd::string BenchmarkName::str() const {\n  return join('/', function_name, args, min_time, min_warmup_time, iterations,\n              repetitions, time_type, threads);\n}\n}  // namespace benchmark\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/benchmark_register.cc",
    "content": "// Copyright 2015 Google Inc. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"benchmark_register.h\"\n\n#ifndef BENCHMARK_OS_WINDOWS\n#if !defined(BENCHMARK_OS_FUCHSIA) && !defined(BENCHMARK_OS_QURT)\n#include <sys/resource.h>\n#endif\n#include <sys/time.h>\n#include <unistd.h>\n#endif\n\n#include <algorithm>\n#include <atomic>\n#include <cinttypes>\n#include <condition_variable>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <fstream>\n#include <iostream>\n#include <memory>\n#include <numeric>\n#include <sstream>\n#include <thread>\n\n#include \"benchmark/benchmark.h\"\n#include \"benchmark_api_internal.h\"\n#include \"check.h\"\n#include \"commandlineflags.h\"\n#include \"complexity.h\"\n#include \"internal_macros.h\"\n#include \"log.h\"\n#include \"mutex.h\"\n#include \"re.h\"\n#include \"statistics.h\"\n#include \"string_util.h\"\n#include \"timers.h\"\n\nnamespace benchmark {\n\nnamespace {\n// For non-dense Range, intermediate values are powers of kRangeMultiplier.\nstatic constexpr int kRangeMultiplier = 8;\n\n// The size of a benchmark family determines is the number of inputs to repeat\n// the benchmark on. If this is \"large\" then warn the user during configuration.\nstatic constexpr size_t kMaxFamilySize = 100;\n\nstatic constexpr char kDisabledPrefix[] = \"DISABLED_\";\n}  // end namespace\n\nnamespace internal {\n\n//=============================================================================//\n//                         BenchmarkFamilies\n//=============================================================================//\n\n// Class for managing registered benchmarks.  Note that each registered\n// benchmark identifies a family of related benchmarks to run.\nclass BenchmarkFamilies {\n public:\n  static BenchmarkFamilies* GetInstance();\n\n  // Registers a benchmark family and returns the index assigned to it.\n  size_t AddBenchmark(std::unique_ptr<Benchmark> family);\n\n  // Clear all registered benchmark families.\n  void ClearBenchmarks();\n\n  // Extract the list of benchmark instances that match the specified\n  // regular expression.\n  bool FindBenchmarks(std::string re,\n                      std::vector<BenchmarkInstance>* benchmarks,\n                      std::ostream* Err);\n\n private:\n  BenchmarkFamilies() {}\n\n  std::vector<std::unique_ptr<Benchmark>> families_;\n  Mutex mutex_;\n};\n\nBenchmarkFamilies* BenchmarkFamilies::GetInstance() {\n  static BenchmarkFamilies instance;\n  return &instance;\n}\n\nsize_t BenchmarkFamilies::AddBenchmark(std::unique_ptr<Benchmark> family) {\n  MutexLock l(mutex_);\n  size_t index = families_.size();\n  families_.push_back(std::move(family));\n  return index;\n}\n\nvoid BenchmarkFamilies::ClearBenchmarks() {\n  MutexLock l(mutex_);\n  families_.clear();\n  families_.shrink_to_fit();\n}\n\nbool BenchmarkFamilies::FindBenchmarks(\n    std::string spec, std::vector<BenchmarkInstance>* benchmarks,\n    std::ostream* ErrStream) {\n  BM_CHECK(ErrStream);\n  auto& Err = *ErrStream;\n  // Make regular expression out of command-line flag\n  std::string error_msg;\n  Regex re;\n  bool is_negative_filter = false;\n  if (spec[0] == '-') {\n    spec.replace(0, 1, \"\");\n    is_negative_filter = true;\n  }\n  if (!re.Init(spec, &error_msg)) {\n    Err << \"Could not compile benchmark re: \" << error_msg << std::endl;\n    return false;\n  }\n\n  // Special list of thread counts to use when none are specified\n  const std::vector<int> one_thread = {1};\n\n  int next_family_index = 0;\n\n  MutexLock l(mutex_);\n  for (std::unique_ptr<Benchmark>& family : families_) {\n    int family_index = next_family_index;\n    int per_family_instance_index = 0;\n\n    // Family was deleted or benchmark doesn't match\n    if (!family) continue;\n\n    if (family->ArgsCnt() == -1) {\n      family->Args({});\n    }\n    const std::vector<int>* thread_counts =\n        (family->thread_counts_.empty()\n             ? &one_thread\n             : &static_cast<const std::vector<int>&>(family->thread_counts_));\n    const size_t family_size = family->args_.size() * thread_counts->size();\n    // The benchmark will be run at least 'family_size' different inputs.\n    // If 'family_size' is very large warn the user.\n    if (family_size > kMaxFamilySize) {\n      Err << \"The number of inputs is very large. \" << family->name_\n          << \" will be repeated at least \" << family_size << \" times.\\n\";\n    }\n    // reserve in the special case the regex \".\", since we know the final\n    // family size.  this doesn't take into account any disabled benchmarks\n    // so worst case we reserve more than we need.\n    if (spec == \".\") benchmarks->reserve(benchmarks->size() + family_size);\n\n    for (auto const& args : family->args_) {\n      for (int num_threads : *thread_counts) {\n        BenchmarkInstance instance(family.get(), family_index,\n                                   per_family_instance_index, args,\n                                   num_threads);\n\n        const auto full_name = instance.name().str();\n        if (full_name.rfind(kDisabledPrefix, 0) != 0 &&\n            ((re.Match(full_name) && !is_negative_filter) ||\n             (!re.Match(full_name) && is_negative_filter))) {\n          benchmarks->push_back(std::move(instance));\n\n          ++per_family_instance_index;\n\n          // Only bump the next family index once we've estabilished that\n          // at least one instance of this family will be run.\n          if (next_family_index == family_index) ++next_family_index;\n        }\n      }\n    }\n  }\n  return true;\n}\n\nBenchmark* RegisterBenchmarkInternal(Benchmark* bench) {\n  std::unique_ptr<Benchmark> bench_ptr(bench);\n  BenchmarkFamilies* families = BenchmarkFamilies::GetInstance();\n  families->AddBenchmark(std::move(bench_ptr));\n  return bench;\n}\n\n// FIXME: This function is a hack so that benchmark.cc can access\n// `BenchmarkFamilies`\nbool FindBenchmarksInternal(const std::string& re,\n                            std::vector<BenchmarkInstance>* benchmarks,\n                            std::ostream* Err) {\n  return BenchmarkFamilies::GetInstance()->FindBenchmarks(re, benchmarks, Err);\n}\n\n//=============================================================================//\n//                               Benchmark\n//=============================================================================//\n\nBenchmark::Benchmark(const std::string& name)\n    : name_(name),\n      aggregation_report_mode_(ARM_Unspecified),\n      time_unit_(GetDefaultTimeUnit()),\n      use_default_time_unit_(true),\n      range_multiplier_(kRangeMultiplier),\n      min_time_(0),\n      min_warmup_time_(0),\n      iterations_(0),\n      repetitions_(0),\n      measure_process_cpu_time_(false),\n      use_real_time_(false),\n      use_manual_time_(false),\n      complexity_(oNone),\n      complexity_lambda_(nullptr),\n      setup_(nullptr),\n      teardown_(nullptr) {\n  ComputeStatistics(\"mean\", StatisticsMean);\n  ComputeStatistics(\"median\", StatisticsMedian);\n  ComputeStatistics(\"stddev\", StatisticsStdDev);\n  ComputeStatistics(\"cv\", StatisticsCV, kPercentage);\n}\n\nBenchmark::~Benchmark() {}\n\nBenchmark* Benchmark::Name(const std::string& name) {\n  SetName(name);\n  return this;\n}\n\nBenchmark* Benchmark::Arg(int64_t x) {\n  BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == 1);\n  args_.push_back({x});\n  return this;\n}\n\nBenchmark* Benchmark::Unit(TimeUnit unit) {\n  time_unit_ = unit;\n  use_default_time_unit_ = false;\n  return this;\n}\n\nBenchmark* Benchmark::Range(int64_t start, int64_t limit) {\n  BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == 1);\n  std::vector<int64_t> arglist;\n  AddRange(&arglist, start, limit, range_multiplier_);\n\n  for (int64_t i : arglist) {\n    args_.push_back({i});\n  }\n  return this;\n}\n\nBenchmark* Benchmark::Ranges(\n    const std::vector<std::pair<int64_t, int64_t>>& ranges) {\n  BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast<int>(ranges.size()));\n  std::vector<std::vector<int64_t>> arglists(ranges.size());\n  for (std::size_t i = 0; i < ranges.size(); i++) {\n    AddRange(&arglists[i], ranges[i].first, ranges[i].second,\n             range_multiplier_);\n  }\n\n  ArgsProduct(arglists);\n\n  return this;\n}\n\nBenchmark* Benchmark::ArgsProduct(\n    const std::vector<std::vector<int64_t>>& arglists) {\n  BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast<int>(arglists.size()));\n\n  std::vector<std::size_t> indices(arglists.size());\n  const std::size_t total = std::accumulate(\n      std::begin(arglists), std::end(arglists), std::size_t{1},\n      [](const std::size_t res, const std::vector<int64_t>& arglist) {\n        return res * arglist.size();\n      });\n  std::vector<int64_t> args;\n  args.reserve(arglists.size());\n  for (std::size_t i = 0; i < total; i++) {\n    for (std::size_t arg = 0; arg < arglists.size(); arg++) {\n      args.push_back(arglists[arg][indices[arg]]);\n    }\n    args_.push_back(args);\n    args.clear();\n\n    std::size_t arg = 0;\n    do {\n      indices[arg] = (indices[arg] + 1) % arglists[arg].size();\n    } while (indices[arg++] == 0 && arg < arglists.size());\n  }\n\n  return this;\n}\n\nBenchmark* Benchmark::ArgName(const std::string& name) {\n  BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == 1);\n  arg_names_ = {name};\n  return this;\n}\n\nBenchmark* Benchmark::ArgNames(const std::vector<std::string>& names) {\n  BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast<int>(names.size()));\n  arg_names_ = names;\n  return this;\n}\n\nBenchmark* Benchmark::DenseRange(int64_t start, int64_t limit, int step) {\n  BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == 1);\n  BM_CHECK_LE(start, limit);\n  for (int64_t arg = start; arg <= limit; arg += step) {\n    args_.push_back({arg});\n  }\n  return this;\n}\n\nBenchmark* Benchmark::Args(const std::vector<int64_t>& args) {\n  BM_CHECK(ArgsCnt() == -1 || ArgsCnt() == static_cast<int>(args.size()));\n  args_.push_back(args);\n  return this;\n}\n\nBenchmark* Benchmark::Apply(void (*custom_arguments)(Benchmark* benchmark)) {\n  custom_arguments(this);\n  return this;\n}\n\nBenchmark* Benchmark::Setup(void (*setup)(const benchmark::State&)) {\n  BM_CHECK(setup != nullptr);\n  setup_ = setup;\n  return this;\n}\n\nBenchmark* Benchmark::Teardown(void (*teardown)(const benchmark::State&)) {\n  BM_CHECK(teardown != nullptr);\n  teardown_ = teardown;\n  return this;\n}\n\nBenchmark* Benchmark::RangeMultiplier(int multiplier) {\n  BM_CHECK(multiplier > 1);\n  range_multiplier_ = multiplier;\n  return this;\n}\n\nBenchmark* Benchmark::MinTime(double t) {\n  BM_CHECK(t > 0.0);\n  BM_CHECK(iterations_ == 0);\n  min_time_ = t;\n  return this;\n}\n\nBenchmark* Benchmark::MinWarmUpTime(double t) {\n  BM_CHECK(t >= 0.0);\n  BM_CHECK(iterations_ == 0);\n  min_warmup_time_ = t;\n  return this;\n}\n\nBenchmark* Benchmark::Iterations(IterationCount n) {\n  BM_CHECK(n > 0);\n  BM_CHECK(IsZero(min_time_));\n  BM_CHECK(IsZero(min_warmup_time_));\n  iterations_ = n;\n  return this;\n}\n\nBenchmark* Benchmark::Repetitions(int n) {\n  BM_CHECK(n > 0);\n  repetitions_ = n;\n  return this;\n}\n\nBenchmark* Benchmark::ReportAggregatesOnly(bool value) {\n  aggregation_report_mode_ = value ? ARM_ReportAggregatesOnly : ARM_Default;\n  return this;\n}\n\nBenchmark* Benchmark::DisplayAggregatesOnly(bool value) {\n  // If we were called, the report mode is no longer 'unspecified', in any case.\n  aggregation_report_mode_ = static_cast<AggregationReportMode>(\n      aggregation_report_mode_ | ARM_Default);\n\n  if (value) {\n    aggregation_report_mode_ = static_cast<AggregationReportMode>(\n        aggregation_report_mode_ | ARM_DisplayReportAggregatesOnly);\n  } else {\n    aggregation_report_mode_ = static_cast<AggregationReportMode>(\n        aggregation_report_mode_ & ~ARM_DisplayReportAggregatesOnly);\n  }\n\n  return this;\n}\n\nBenchmark* Benchmark::MeasureProcessCPUTime() {\n  // Can be used together with UseRealTime() / UseManualTime().\n  measure_process_cpu_time_ = true;\n  return this;\n}\n\nBenchmark* Benchmark::UseRealTime() {\n  BM_CHECK(!use_manual_time_)\n      << \"Cannot set UseRealTime and UseManualTime simultaneously.\";\n  use_real_time_ = true;\n  return this;\n}\n\nBenchmark* Benchmark::UseManualTime() {\n  BM_CHECK(!use_real_time_)\n      << \"Cannot set UseRealTime and UseManualTime simultaneously.\";\n  use_manual_time_ = true;\n  return this;\n}\n\nBenchmark* Benchmark::Complexity(BigO complexity) {\n  complexity_ = complexity;\n  return this;\n}\n\nBenchmark* Benchmark::Complexity(BigOFunc* complexity) {\n  complexity_lambda_ = complexity;\n  complexity_ = oLambda;\n  return this;\n}\n\nBenchmark* Benchmark::ComputeStatistics(const std::string& name,\n                                        StatisticsFunc* statistics,\n                                        StatisticUnit unit) {\n  statistics_.emplace_back(name, statistics, unit);\n  return this;\n}\n\nBenchmark* Benchmark::Threads(int t) {\n  BM_CHECK_GT(t, 0);\n  thread_counts_.push_back(t);\n  return this;\n}\n\nBenchmark* Benchmark::ThreadRange(int min_threads, int max_threads) {\n  BM_CHECK_GT(min_threads, 0);\n  BM_CHECK_GE(max_threads, min_threads);\n\n  AddRange(&thread_counts_, min_threads, max_threads, 2);\n  return this;\n}\n\nBenchmark* Benchmark::DenseThreadRange(int min_threads, int max_threads,\n                                       int stride) {\n  BM_CHECK_GT(min_threads, 0);\n  BM_CHECK_GE(max_threads, min_threads);\n  BM_CHECK_GE(stride, 1);\n\n  for (auto i = min_threads; i < max_threads; i += stride) {\n    thread_counts_.push_back(i);\n  }\n  thread_counts_.push_back(max_threads);\n  return this;\n}\n\nBenchmark* Benchmark::ThreadPerCpu() {\n  thread_counts_.push_back(CPUInfo::Get().num_cpus);\n  return this;\n}\n\nvoid Benchmark::SetName(const std::string& name) { name_ = name; }\n\nconst char* Benchmark::GetName() const { return name_.c_str(); }\n\nint Benchmark::ArgsCnt() const {\n  if (args_.empty()) {\n    if (arg_names_.empty()) return -1;\n    return static_cast<int>(arg_names_.size());\n  }\n  return static_cast<int>(args_.front().size());\n}\n\nconst char* Benchmark::GetArgName(int arg) const {\n  BM_CHECK_GE(arg, 0);\n  BM_CHECK_LT(arg, static_cast<int>(arg_names_.size()));\n  return arg_names_[arg].c_str();\n}\n\nTimeUnit Benchmark::GetTimeUnit() const {\n  return use_default_time_unit_ ? GetDefaultTimeUnit() : time_unit_;\n}\n\n//=============================================================================//\n//                            FunctionBenchmark\n//=============================================================================//\n\nvoid FunctionBenchmark::Run(State& st) { func_(st); }\n\n}  // end namespace internal\n\nvoid ClearRegisteredBenchmarks() {\n  internal::BenchmarkFamilies::GetInstance()->ClearBenchmarks();\n}\n\nstd::vector<int64_t> CreateRange(int64_t lo, int64_t hi, int multi) {\n  std::vector<int64_t> args;\n  internal::AddRange(&args, lo, hi, multi);\n  return args;\n}\n\nstd::vector<int64_t> CreateDenseRange(int64_t start, int64_t limit, int step) {\n  BM_CHECK_LE(start, limit);\n  std::vector<int64_t> args;\n  for (int64_t arg = start; arg <= limit; arg += step) {\n    args.push_back(arg);\n  }\n  return args;\n}\n\n}  // end namespace benchmark\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/benchmark_register.h",
    "content": "#ifndef BENCHMARK_REGISTER_H\n#define BENCHMARK_REGISTER_H\n\n#include <algorithm>\n#include <limits>\n#include <vector>\n\n#include \"check.h\"\n\nnamespace benchmark {\nnamespace internal {\n\n// Append the powers of 'mult' in the closed interval [lo, hi].\n// Returns iterator to the start of the inserted range.\ntemplate <typename T>\ntypename std::vector<T>::iterator AddPowers(std::vector<T>* dst, T lo, T hi,\n                                            int mult) {\n  BM_CHECK_GE(lo, 0);\n  BM_CHECK_GE(hi, lo);\n  BM_CHECK_GE(mult, 2);\n\n  const size_t start_offset = dst->size();\n\n  static const T kmax = std::numeric_limits<T>::max();\n\n  // Space out the values in multiples of \"mult\"\n  for (T i = static_cast<T>(1); i <= hi; i *= static_cast<T>(mult)) {\n    if (i >= lo) {\n      dst->push_back(i);\n    }\n    // Break the loop here since multiplying by\n    // 'mult' would move outside of the range of T\n    if (i > kmax / mult) break;\n  }\n\n  return dst->begin() + static_cast<int>(start_offset);\n}\n\ntemplate <typename T>\nvoid AddNegatedPowers(std::vector<T>* dst, T lo, T hi, int mult) {\n  // We negate lo and hi so we require that they cannot be equal to 'min'.\n  BM_CHECK_GT(lo, std::numeric_limits<T>::min());\n  BM_CHECK_GT(hi, std::numeric_limits<T>::min());\n  BM_CHECK_GE(hi, lo);\n  BM_CHECK_LE(hi, 0);\n\n  // Add positive powers, then negate and reverse.\n  // Casts necessary since small integers get promoted\n  // to 'int' when negating.\n  const auto lo_complement = static_cast<T>(-lo);\n  const auto hi_complement = static_cast<T>(-hi);\n\n  const auto it = AddPowers(dst, hi_complement, lo_complement, mult);\n\n  std::for_each(it, dst->end(), [](T& t) { t *= -1; });\n  std::reverse(it, dst->end());\n}\n\ntemplate <typename T>\nvoid AddRange(std::vector<T>* dst, T lo, T hi, int mult) {\n  static_assert(std::is_integral<T>::value && std::is_signed<T>::value,\n                \"Args type must be a signed integer\");\n\n  BM_CHECK_GE(hi, lo);\n  BM_CHECK_GE(mult, 2);\n\n  // Add \"lo\"\n  dst->push_back(lo);\n\n  // Handle lo == hi as a special case, so we then know\n  // lo < hi and so it is safe to add 1 to lo and subtract 1\n  // from hi without falling outside of the range of T.\n  if (lo == hi) return;\n\n  // Ensure that lo_inner <= hi_inner below.\n  if (lo + 1 == hi) {\n    dst->push_back(hi);\n    return;\n  }\n\n  // Add all powers of 'mult' in the range [lo+1, hi-1] (inclusive).\n  const auto lo_inner = static_cast<T>(lo + 1);\n  const auto hi_inner = static_cast<T>(hi - 1);\n\n  // Insert negative values\n  if (lo_inner < 0) {\n    AddNegatedPowers(dst, lo_inner, std::min(hi_inner, T{-1}), mult);\n  }\n\n  // Treat 0 as a special case (see discussion on #762).\n  if (lo < 0 && hi >= 0) {\n    dst->push_back(0);\n  }\n\n  // Insert positive values\n  if (hi_inner > 0) {\n    AddPowers(dst, std::max(lo_inner, T{1}), hi_inner, mult);\n  }\n\n  // Add \"hi\" (if different from last value).\n  if (hi != dst->back()) {\n    dst->push_back(hi);\n  }\n}\n\n}  // namespace internal\n}  // namespace benchmark\n\n#endif  // BENCHMARK_REGISTER_H\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/benchmark_runner.cc",
    "content": "// Copyright 2015 Google Inc. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"benchmark_runner.h\"\n\n#include \"benchmark/benchmark.h\"\n#include \"benchmark_api_internal.h\"\n#include \"internal_macros.h\"\n\n#ifndef BENCHMARK_OS_WINDOWS\n#if !defined(BENCHMARK_OS_FUCHSIA) && !defined(BENCHMARK_OS_QURT)\n#include <sys/resource.h>\n#endif\n#include <sys/time.h>\n#include <unistd.h>\n#endif\n\n#include <algorithm>\n#include <atomic>\n#include <climits>\n#include <cmath>\n#include <condition_variable>\n#include <cstdio>\n#include <cstdlib>\n#include <fstream>\n#include <iostream>\n#include <limits>\n#include <memory>\n#include <string>\n#include <thread>\n#include <utility>\n\n#include \"check.h\"\n#include \"colorprint.h\"\n#include \"commandlineflags.h\"\n#include \"complexity.h\"\n#include \"counter.h\"\n#include \"internal_macros.h\"\n#include \"log.h\"\n#include \"mutex.h\"\n#include \"perf_counters.h\"\n#include \"re.h\"\n#include \"statistics.h\"\n#include \"string_util.h\"\n#include \"thread_manager.h\"\n#include \"thread_timer.h\"\n\nnamespace benchmark {\n\nnamespace internal {\n\nMemoryManager* memory_manager = nullptr;\n\nnamespace {\n\nstatic constexpr IterationCount kMaxIterations = 1000000000;\nconst double kDefaultMinTime =\n    std::strtod(::benchmark::kDefaultMinTimeStr, /*p_end*/ nullptr);\n\nBenchmarkReporter::Run CreateRunReport(\n    const benchmark::internal::BenchmarkInstance& b,\n    const internal::ThreadManager::Result& results,\n    IterationCount memory_iterations,\n    const MemoryManager::Result* memory_result, double seconds,\n    int64_t repetition_index, int64_t repeats) {\n  // Create report about this benchmark run.\n  BenchmarkReporter::Run report;\n\n  report.run_name = b.name();\n  report.family_index = b.family_index();\n  report.per_family_instance_index = b.per_family_instance_index();\n  report.skipped = results.skipped_;\n  report.skip_message = results.skip_message_;\n  report.report_label = results.report_label_;\n  // This is the total iterations across all threads.\n  report.iterations = results.iterations;\n  report.time_unit = b.time_unit();\n  report.threads = b.threads();\n  report.repetition_index = repetition_index;\n  report.repetitions = repeats;\n\n  if (!report.skipped) {\n    if (b.use_manual_time()) {\n      report.real_accumulated_time = results.manual_time_used;\n    } else {\n      report.real_accumulated_time = results.real_time_used;\n    }\n    report.cpu_accumulated_time = results.cpu_time_used;\n    report.complexity_n = results.complexity_n;\n    report.complexity = b.complexity();\n    report.complexity_lambda = b.complexity_lambda();\n    report.statistics = &b.statistics();\n    report.counters = results.counters;\n\n    if (memory_iterations > 0) {\n      assert(memory_result != nullptr);\n      report.memory_result = memory_result;\n      report.allocs_per_iter =\n          memory_iterations ? static_cast<double>(memory_result->num_allocs) /\n                                  memory_iterations\n                            : 0;\n    }\n\n    internal::Finish(&report.counters, results.iterations, seconds,\n                     b.threads());\n  }\n  return report;\n}\n\n// Execute one thread of benchmark b for the specified number of iterations.\n// Adds the stats collected for the thread into manager->results.\nvoid RunInThread(const BenchmarkInstance* b, IterationCount iters,\n                 int thread_id, ThreadManager* manager,\n                 PerfCountersMeasurement* perf_counters_measurement) {\n  internal::ThreadTimer timer(\n      b->measure_process_cpu_time()\n          ? internal::ThreadTimer::CreateProcessCpuTime()\n          : internal::ThreadTimer::Create());\n\n  State st =\n      b->Run(iters, thread_id, &timer, manager, perf_counters_measurement);\n  BM_CHECK(st.skipped() || st.iterations() >= st.max_iterations)\n      << \"Benchmark returned before State::KeepRunning() returned false!\";\n  {\n    MutexLock l(manager->GetBenchmarkMutex());\n    internal::ThreadManager::Result& results = manager->results;\n    results.iterations += st.iterations();\n    results.cpu_time_used += timer.cpu_time_used();\n    results.real_time_used += timer.real_time_used();\n    results.manual_time_used += timer.manual_time_used();\n    results.complexity_n += st.complexity_length_n();\n    internal::Increment(&results.counters, st.counters);\n  }\n  manager->NotifyThreadComplete();\n}\n\ndouble ComputeMinTime(const benchmark::internal::BenchmarkInstance& b,\n                      const BenchTimeType& iters_or_time) {\n  if (!IsZero(b.min_time())) return b.min_time();\n  // If the flag was used to specify number of iters, then return the default\n  // min_time.\n  if (iters_or_time.tag == BenchTimeType::ITERS) return kDefaultMinTime;\n\n  return iters_or_time.time;\n}\n\nIterationCount ComputeIters(const benchmark::internal::BenchmarkInstance& b,\n                            const BenchTimeType& iters_or_time) {\n  if (b.iterations() != 0) return b.iterations();\n\n  // We've already concluded that this flag is currently used to pass\n  // iters but do a check here again anyway.\n  BM_CHECK(iters_or_time.tag == BenchTimeType::ITERS);\n  return iters_or_time.iters;\n}\n\n}  // end namespace\n\nBenchTimeType ParseBenchMinTime(const std::string& value) {\n  BenchTimeType ret;\n\n  if (value.empty()) {\n    ret.tag = BenchTimeType::TIME;\n    ret.time = 0.0;\n    return ret;\n  }\n\n  if (value.back() == 'x') {\n    char* p_end;\n    // Reset errno before it's changed by strtol.\n    errno = 0;\n    IterationCount num_iters = std::strtol(value.c_str(), &p_end, 10);\n\n    // After a valid parse, p_end should have been set to\n    // point to the 'x' suffix.\n    BM_CHECK(errno == 0 && p_end != nullptr && *p_end == 'x')\n        << \"Malformed iters value passed to --benchmark_min_time: `\" << value\n        << \"`. Expected --benchmark_min_time=<integer>x.\";\n\n    ret.tag = BenchTimeType::ITERS;\n    ret.iters = num_iters;\n    return ret;\n  }\n\n  bool has_suffix = value.back() == 's';\n  if (!has_suffix) {\n    BM_VLOG(0) << \"Value passed to --benchmark_min_time should have a suffix. \"\n                  \"Eg., `30s` for 30-seconds.\";\n  }\n\n  char* p_end;\n  // Reset errno before it's changed by strtod.\n  errno = 0;\n  double min_time = std::strtod(value.c_str(), &p_end);\n\n  // After a successful parse, p_end should point to the suffix 's',\n  // or the end of the string if the suffix was omitted.\n  BM_CHECK(errno == 0 && p_end != nullptr &&\n           ((has_suffix && *p_end == 's') || *p_end == '\\0'))\n      << \"Malformed seconds value passed to --benchmark_min_time: `\" << value\n      << \"`. Expected --benchmark_min_time=<float>x.\";\n\n  ret.tag = BenchTimeType::TIME;\n  ret.time = min_time;\n\n  return ret;\n}\n\nBenchmarkRunner::BenchmarkRunner(\n    const benchmark::internal::BenchmarkInstance& b_,\n    PerfCountersMeasurement* pcm_,\n    BenchmarkReporter::PerFamilyRunReports* reports_for_family_)\n    : b(b_),\n      reports_for_family(reports_for_family_),\n      parsed_benchtime_flag(ParseBenchMinTime(FLAGS_benchmark_min_time)),\n      min_time(ComputeMinTime(b_, parsed_benchtime_flag)),\n      min_warmup_time((!IsZero(b.min_time()) && b.min_warmup_time() > 0.0)\n                          ? b.min_warmup_time()\n                          : FLAGS_benchmark_min_warmup_time),\n      warmup_done(!(min_warmup_time > 0.0)),\n      repeats(b.repetitions() != 0 ? b.repetitions()\n                                   : FLAGS_benchmark_repetitions),\n      has_explicit_iteration_count(b.iterations() != 0 ||\n                                   parsed_benchtime_flag.tag ==\n                                       BenchTimeType::ITERS),\n      pool(b.threads() - 1),\n      iters(has_explicit_iteration_count\n                ? ComputeIters(b_, parsed_benchtime_flag)\n                : 1),\n      perf_counters_measurement_ptr(pcm_) {\n  run_results.display_report_aggregates_only =\n      (FLAGS_benchmark_report_aggregates_only ||\n       FLAGS_benchmark_display_aggregates_only);\n  run_results.file_report_aggregates_only =\n      FLAGS_benchmark_report_aggregates_only;\n  if (b.aggregation_report_mode() != internal::ARM_Unspecified) {\n    run_results.display_report_aggregates_only =\n        (b.aggregation_report_mode() &\n         internal::ARM_DisplayReportAggregatesOnly);\n    run_results.file_report_aggregates_only =\n        (b.aggregation_report_mode() & internal::ARM_FileReportAggregatesOnly);\n    BM_CHECK(FLAGS_benchmark_perf_counters.empty() ||\n             (perf_counters_measurement_ptr->num_counters() == 0))\n        << \"Perf counters were requested but could not be set up.\";\n  }\n}\n\nBenchmarkRunner::IterationResults BenchmarkRunner::DoNIterations() {\n  BM_VLOG(2) << \"Running \" << b.name().str() << \" for \" << iters << \"\\n\";\n\n  std::unique_ptr<internal::ThreadManager> manager;\n  manager.reset(new internal::ThreadManager(b.threads()));\n\n  // Run all but one thread in separate threads\n  for (std::size_t ti = 0; ti < pool.size(); ++ti) {\n    pool[ti] = std::thread(&RunInThread, &b, iters, static_cast<int>(ti + 1),\n                           manager.get(), perf_counters_measurement_ptr);\n  }\n  // And run one thread here directly.\n  // (If we were asked to run just one thread, we don't create new threads.)\n  // Yes, we need to do this here *after* we start the separate threads.\n  RunInThread(&b, iters, 0, manager.get(), perf_counters_measurement_ptr);\n\n  // The main thread has finished. Now let's wait for the other threads.\n  manager->WaitForAllThreads();\n  for (std::thread& thread : pool) thread.join();\n\n  IterationResults i;\n  // Acquire the measurements/counters from the manager, UNDER THE LOCK!\n  {\n    MutexLock l(manager->GetBenchmarkMutex());\n    i.results = manager->results;\n  }\n\n  // And get rid of the manager.\n  manager.reset();\n\n  // Adjust real/manual time stats since they were reported per thread.\n  i.results.real_time_used /= b.threads();\n  i.results.manual_time_used /= b.threads();\n  // If we were measuring whole-process CPU usage, adjust the CPU time too.\n  if (b.measure_process_cpu_time()) i.results.cpu_time_used /= b.threads();\n\n  BM_VLOG(2) << \"Ran in \" << i.results.cpu_time_used << \"/\"\n             << i.results.real_time_used << \"\\n\";\n\n  // By using KeepRunningBatch a benchmark can iterate more times than\n  // requested, so take the iteration count from i.results.\n  i.iters = i.results.iterations / b.threads();\n\n  // Base decisions off of real time if requested by this benchmark.\n  i.seconds = i.results.cpu_time_used;\n  if (b.use_manual_time()) {\n    i.seconds = i.results.manual_time_used;\n  } else if (b.use_real_time()) {\n    i.seconds = i.results.real_time_used;\n  }\n\n  return i;\n}\n\nIterationCount BenchmarkRunner::PredictNumItersNeeded(\n    const IterationResults& i) const {\n  // See how much iterations should be increased by.\n  // Note: Avoid division by zero with max(seconds, 1ns).\n  double multiplier = GetMinTimeToApply() * 1.4 / std::max(i.seconds, 1e-9);\n  // If our last run was at least 10% of FLAGS_benchmark_min_time then we\n  // use the multiplier directly.\n  // Otherwise we use at most 10 times expansion.\n  // NOTE: When the last run was at least 10% of the min time the max\n  // expansion should be 14x.\n  const bool is_significant = (i.seconds / GetMinTimeToApply()) > 0.1;\n  multiplier = is_significant ? multiplier : 10.0;\n\n  // So what seems to be the sufficiently-large iteration count? Round up.\n  const IterationCount max_next_iters = static_cast<IterationCount>(\n      std::lround(std::max(multiplier * static_cast<double>(i.iters),\n                           static_cast<double>(i.iters) + 1.0)));\n  // But we do have *some* limits though..\n  const IterationCount next_iters = std::min(max_next_iters, kMaxIterations);\n\n  BM_VLOG(3) << \"Next iters: \" << next_iters << \", \" << multiplier << \"\\n\";\n  return next_iters;  // round up before conversion to integer.\n}\n\nbool BenchmarkRunner::ShouldReportIterationResults(\n    const IterationResults& i) const {\n  // Determine if this run should be reported;\n  // Either it has run for a sufficient amount of time\n  // or because an error was reported.\n  return i.results.skipped_ ||\n         i.iters >= kMaxIterations ||  // Too many iterations already.\n         i.seconds >=\n             GetMinTimeToApply() ||  // The elapsed time is large enough.\n         // CPU time is specified but the elapsed real time greatly exceeds\n         // the minimum time.\n         // Note that user provided timers are except from this test.\n         ((i.results.real_time_used >= 5 * GetMinTimeToApply()) &&\n          !b.use_manual_time());\n}\n\ndouble BenchmarkRunner::GetMinTimeToApply() const {\n  // In order to re-use functionality to run and measure benchmarks for running\n  // a warmup phase of the benchmark, we need a way of telling whether to apply\n  // min_time or min_warmup_time. This function will figure out if we are in the\n  // warmup phase and therefore need to apply min_warmup_time or if we already\n  // in the benchmarking phase and min_time needs to be applied.\n  return warmup_done ? min_time : min_warmup_time;\n}\n\nvoid BenchmarkRunner::FinishWarmUp(const IterationCount& i) {\n  warmup_done = true;\n  iters = i;\n}\n\nvoid BenchmarkRunner::RunWarmUp() {\n  // Use the same mechanisms for warming up the benchmark as used for actually\n  // running and measuring the benchmark.\n  IterationResults i_warmup;\n  // Dont use the iterations determined in the warmup phase for the actual\n  // measured benchmark phase. While this may be a good starting point for the\n  // benchmark and it would therefore get rid of the need to figure out how many\n  // iterations are needed if min_time is set again, this may also be a complete\n  // wrong guess since the warmup loops might be considerably slower (e.g\n  // because of caching effects).\n  const IterationCount i_backup = iters;\n\n  for (;;) {\n    b.Setup();\n    i_warmup = DoNIterations();\n    b.Teardown();\n\n    const bool finish = ShouldReportIterationResults(i_warmup);\n\n    if (finish) {\n      FinishWarmUp(i_backup);\n      break;\n    }\n\n    // Although we are running \"only\" a warmup phase where running enough\n    // iterations at once without measuring time isn't as important as it is for\n    // the benchmarking phase, we still do it the same way as otherwise it is\n    // very confusing for the user to know how to choose a proper value for\n    // min_warmup_time if a different approach on running it is used.\n    iters = PredictNumItersNeeded(i_warmup);\n    assert(iters > i_warmup.iters &&\n           \"if we did more iterations than we want to do the next time, \"\n           \"then we should have accepted the current iteration run.\");\n  }\n}\n\nvoid BenchmarkRunner::DoOneRepetition() {\n  assert(HasRepeatsRemaining() && \"Already done all repetitions?\");\n\n  const bool is_the_first_repetition = num_repetitions_done == 0;\n\n  // In case a warmup phase is requested by the benchmark, run it now.\n  // After running the warmup phase the BenchmarkRunner should be in a state as\n  // this warmup never happened except the fact that warmup_done is set. Every\n  // other manipulation of the BenchmarkRunner instance would be a bug! Please\n  // fix it.\n  if (!warmup_done) RunWarmUp();\n\n  IterationResults i;\n  // We *may* be gradually increasing the length (iteration count)\n  // of the benchmark until we decide the results are significant.\n  // And once we do, we report those last results and exit.\n  // Please do note that the if there are repetitions, the iteration count\n  // is *only* calculated for the *first* repetition, and other repetitions\n  // simply use that precomputed iteration count.\n  for (;;) {\n    b.Setup();\n    i = DoNIterations();\n    b.Teardown();\n\n    // Do we consider the results to be significant?\n    // If we are doing repetitions, and the first repetition was already done,\n    // it has calculated the correct iteration time, so we have run that very\n    // iteration count just now. No need to calculate anything. Just report.\n    // Else, the normal rules apply.\n    const bool results_are_significant = !is_the_first_repetition ||\n                                         has_explicit_iteration_count ||\n                                         ShouldReportIterationResults(i);\n\n    if (results_are_significant) break;  // Good, let's report them!\n\n    // Nope, bad iteration. Let's re-estimate the hopefully-sufficient\n    // iteration count, and run the benchmark again...\n\n    iters = PredictNumItersNeeded(i);\n    assert(iters > i.iters &&\n           \"if we did more iterations than we want to do the next time, \"\n           \"then we should have accepted the current iteration run.\");\n  }\n\n  // Oh, one last thing, we need to also produce the 'memory measurements'..\n  MemoryManager::Result* memory_result = nullptr;\n  IterationCount memory_iterations = 0;\n  if (memory_manager != nullptr) {\n    // TODO(vyng): Consider making BenchmarkReporter::Run::memory_result an\n    // optional so we don't have to own the Result here.\n    // Can't do it now due to cxx03.\n    memory_results.push_back(MemoryManager::Result());\n    memory_result = &memory_results.back();\n    // Only run a few iterations to reduce the impact of one-time\n    // allocations in benchmarks that are not properly managed.\n    memory_iterations = std::min<IterationCount>(16, iters);\n    memory_manager->Start();\n    std::unique_ptr<internal::ThreadManager> manager;\n    manager.reset(new internal::ThreadManager(1));\n    b.Setup();\n    RunInThread(&b, memory_iterations, 0, manager.get(),\n                perf_counters_measurement_ptr);\n    manager->WaitForAllThreads();\n    manager.reset();\n    b.Teardown();\n    memory_manager->Stop(*memory_result);\n  }\n\n  // Ok, now actually report.\n  BenchmarkReporter::Run report =\n      CreateRunReport(b, i.results, memory_iterations, memory_result, i.seconds,\n                      num_repetitions_done, repeats);\n\n  if (reports_for_family) {\n    ++reports_for_family->num_runs_done;\n    if (!report.skipped) reports_for_family->Runs.push_back(report);\n  }\n\n  run_results.non_aggregates.push_back(report);\n\n  ++num_repetitions_done;\n}\n\nRunResults&& BenchmarkRunner::GetResults() {\n  assert(!HasRepeatsRemaining() && \"Did not run all repetitions yet?\");\n\n  // Calculate additional statistics over the repetitions of this instance.\n  run_results.aggregates_only = ComputeStats(run_results.non_aggregates);\n\n  return std::move(run_results);\n}\n\n}  // end namespace internal\n\n}  // end namespace benchmark\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/benchmark_runner.h",
    "content": "// Copyright 2015 Google Inc. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef BENCHMARK_RUNNER_H_\n#define BENCHMARK_RUNNER_H_\n\n#include <thread>\n#include <vector>\n\n#include \"benchmark_api_internal.h\"\n#include \"internal_macros.h\"\n#include \"perf_counters.h\"\n#include \"thread_manager.h\"\n\nnamespace benchmark {\n\nBM_DECLARE_string(benchmark_min_time);\nBM_DECLARE_double(benchmark_min_warmup_time);\nBM_DECLARE_int32(benchmark_repetitions);\nBM_DECLARE_bool(benchmark_report_aggregates_only);\nBM_DECLARE_bool(benchmark_display_aggregates_only);\nBM_DECLARE_string(benchmark_perf_counters);\n\nnamespace internal {\n\nextern MemoryManager* memory_manager;\n\nstruct RunResults {\n  std::vector<BenchmarkReporter::Run> non_aggregates;\n  std::vector<BenchmarkReporter::Run> aggregates_only;\n\n  bool display_report_aggregates_only = false;\n  bool file_report_aggregates_only = false;\n};\n\nstruct BENCHMARK_EXPORT BenchTimeType {\n  enum { ITERS, TIME } tag;\n  union {\n    IterationCount iters;\n    double time;\n  };\n};\n\nBENCHMARK_EXPORT\nBenchTimeType ParseBenchMinTime(const std::string& value);\n\nclass BenchmarkRunner {\n public:\n  BenchmarkRunner(const benchmark::internal::BenchmarkInstance& b_,\n                  benchmark::internal::PerfCountersMeasurement* pmc_,\n                  BenchmarkReporter::PerFamilyRunReports* reports_for_family);\n\n  int GetNumRepeats() const { return repeats; }\n\n  bool HasRepeatsRemaining() const {\n    return GetNumRepeats() != num_repetitions_done;\n  }\n\n  void DoOneRepetition();\n\n  RunResults&& GetResults();\n\n  BenchmarkReporter::PerFamilyRunReports* GetReportsForFamily() const {\n    return reports_for_family;\n  }\n\n  double GetMinTime() const { return min_time; }\n\n  bool HasExplicitIters() const { return has_explicit_iteration_count; }\n\n  IterationCount GetIters() const { return iters; }\n\n private:\n  RunResults run_results;\n\n  const benchmark::internal::BenchmarkInstance& b;\n  BenchmarkReporter::PerFamilyRunReports* reports_for_family;\n\n  BenchTimeType parsed_benchtime_flag;\n  const double min_time;\n  const double min_warmup_time;\n  bool warmup_done;\n  const int repeats;\n  const bool has_explicit_iteration_count;\n\n  int num_repetitions_done = 0;\n\n  std::vector<std::thread> pool;\n\n  std::vector<MemoryManager::Result> memory_results;\n\n  IterationCount iters;  // preserved between repetitions!\n  // So only the first repetition has to find/calculate it,\n  // the other repetitions will just use that precomputed iteration count.\n\n  PerfCountersMeasurement* const perf_counters_measurement_ptr = nullptr;\n\n  struct IterationResults {\n    internal::ThreadManager::Result results;\n    IterationCount iters;\n    double seconds;\n  };\n  IterationResults DoNIterations();\n\n  IterationCount PredictNumItersNeeded(const IterationResults& i) const;\n\n  bool ShouldReportIterationResults(const IterationResults& i) const;\n\n  double GetMinTimeToApply() const;\n\n  void FinishWarmUp(const IterationCount& i);\n\n  void RunWarmUp();\n};\n\n}  // namespace internal\n\n}  // end namespace benchmark\n\n#endif  // BENCHMARK_RUNNER_H_\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/check.cc",
    "content": "#include \"check.h\"\n\nnamespace benchmark {\nnamespace internal {\n\nstatic AbortHandlerT* handler = &std::abort;\n\nBENCHMARK_EXPORT AbortHandlerT*& GetAbortHandler() { return handler; }\n\n}  // namespace internal\n}  // namespace benchmark\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/check.h",
    "content": "#ifndef CHECK_H_\n#define CHECK_H_\n\n#include <cmath>\n#include <cstdlib>\n#include <ostream>\n\n#include \"benchmark/export.h\"\n#include \"internal_macros.h\"\n#include \"log.h\"\n\n#if defined(__GNUC__) || defined(__clang__)\n#define BENCHMARK_NOEXCEPT noexcept\n#define BENCHMARK_NOEXCEPT_OP(x) noexcept(x)\n#elif defined(_MSC_VER) && !defined(__clang__)\n#if _MSC_VER >= 1900\n#define BENCHMARK_NOEXCEPT noexcept\n#define BENCHMARK_NOEXCEPT_OP(x) noexcept(x)\n#else\n#define BENCHMARK_NOEXCEPT\n#define BENCHMARK_NOEXCEPT_OP(x)\n#endif\n#define __func__ __FUNCTION__\n#else\n#define BENCHMARK_NOEXCEPT\n#define BENCHMARK_NOEXCEPT_OP(x)\n#endif\n\nnamespace benchmark {\nnamespace internal {\n\ntypedef void(AbortHandlerT)();\n\nBENCHMARK_EXPORT\nAbortHandlerT*& GetAbortHandler();\n\nBENCHMARK_NORETURN inline void CallAbortHandler() {\n  GetAbortHandler()();\n  std::abort();  // fallback to enforce noreturn\n}\n\n// CheckHandler is the class constructed by failing BM_CHECK macros.\n// CheckHandler will log information about the failures and abort when it is\n// destructed.\nclass CheckHandler {\n public:\n  CheckHandler(const char* check, const char* file, const char* func, int line)\n      : log_(GetErrorLogInstance()) {\n    log_ << file << \":\" << line << \": \" << func << \": Check `\" << check\n         << \"' failed. \";\n  }\n\n  LogType& GetLog() { return log_; }\n\n#if defined(COMPILER_MSVC)\n#pragma warning(push)\n#pragma warning(disable : 4722)\n#endif\n  BENCHMARK_NORETURN ~CheckHandler() BENCHMARK_NOEXCEPT_OP(false) {\n    log_ << std::endl;\n    CallAbortHandler();\n  }\n#if defined(COMPILER_MSVC)\n#pragma warning(pop)\n#endif\n\n  CheckHandler& operator=(const CheckHandler&) = delete;\n  CheckHandler(const CheckHandler&) = delete;\n  CheckHandler() = delete;\n\n private:\n  LogType& log_;\n};\n\n}  // end namespace internal\n}  // end namespace benchmark\n\n// The BM_CHECK macro returns a std::ostream object that can have extra\n// information written to it.\n#ifndef NDEBUG\n#define BM_CHECK(b)                                                          \\\n  (b ? ::benchmark::internal::GetNullLogInstance()                           \\\n     : ::benchmark::internal::CheckHandler(#b, __FILE__, __func__, __LINE__) \\\n           .GetLog())\n#else\n#define BM_CHECK(b) ::benchmark::internal::GetNullLogInstance()\n#endif\n\n// clang-format off\n// preserve whitespacing between operators for alignment\n#define BM_CHECK_EQ(a, b) BM_CHECK((a) == (b))\n#define BM_CHECK_NE(a, b) BM_CHECK((a) != (b))\n#define BM_CHECK_GE(a, b) BM_CHECK((a) >= (b))\n#define BM_CHECK_LE(a, b) BM_CHECK((a) <= (b))\n#define BM_CHECK_GT(a, b) BM_CHECK((a) > (b))\n#define BM_CHECK_LT(a, b) BM_CHECK((a) < (b))\n\n#define BM_CHECK_FLOAT_EQ(a, b, eps) BM_CHECK(std::fabs((a) - (b)) <  (eps))\n#define BM_CHECK_FLOAT_NE(a, b, eps) BM_CHECK(std::fabs((a) - (b)) >= (eps))\n#define BM_CHECK_FLOAT_GE(a, b, eps) BM_CHECK((a) - (b) > -(eps))\n#define BM_CHECK_FLOAT_LE(a, b, eps) BM_CHECK((b) - (a) > -(eps))\n#define BM_CHECK_FLOAT_GT(a, b, eps) BM_CHECK((a) - (b) >  (eps))\n#define BM_CHECK_FLOAT_LT(a, b, eps) BM_CHECK((b) - (a) >  (eps))\n//clang-format on\n\n#endif  // CHECK_H_\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/colorprint.cc",
    "content": "// Copyright 2015 Google Inc. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"colorprint.h\"\n\n#include <cstdarg>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <memory>\n#include <string>\n\n#include \"check.h\"\n#include \"internal_macros.h\"\n\n#ifdef BENCHMARK_OS_WINDOWS\n#include <io.h>\n#include <windows.h>\n#else\n#include <unistd.h>\n#endif  // BENCHMARK_OS_WINDOWS\n\nnamespace benchmark {\nnamespace {\n#ifdef BENCHMARK_OS_WINDOWS\ntypedef WORD PlatformColorCode;\n#else\ntypedef const char* PlatformColorCode;\n#endif\n\nPlatformColorCode GetPlatformColorCode(LogColor color) {\n#ifdef BENCHMARK_OS_WINDOWS\n  switch (color) {\n    case COLOR_RED:\n      return FOREGROUND_RED;\n    case COLOR_GREEN:\n      return FOREGROUND_GREEN;\n    case COLOR_YELLOW:\n      return FOREGROUND_RED | FOREGROUND_GREEN;\n    case COLOR_BLUE:\n      return FOREGROUND_BLUE;\n    case COLOR_MAGENTA:\n      return FOREGROUND_BLUE | FOREGROUND_RED;\n    case COLOR_CYAN:\n      return FOREGROUND_BLUE | FOREGROUND_GREEN;\n    case COLOR_WHITE:  // fall through to default\n    default:\n      return 0;\n  }\n#else\n  switch (color) {\n    case COLOR_RED:\n      return \"1\";\n    case COLOR_GREEN:\n      return \"2\";\n    case COLOR_YELLOW:\n      return \"3\";\n    case COLOR_BLUE:\n      return \"4\";\n    case COLOR_MAGENTA:\n      return \"5\";\n    case COLOR_CYAN:\n      return \"6\";\n    case COLOR_WHITE:\n      return \"7\";\n    default:\n      return nullptr;\n  };\n#endif\n}\n\n}  // end namespace\n\nstd::string FormatString(const char* msg, va_list args) {\n  // we might need a second shot at this, so pre-emptivly make a copy\n  va_list args_cp;\n  va_copy(args_cp, args);\n\n  std::size_t size = 256;\n  char local_buff[256];\n  auto ret = vsnprintf(local_buff, size, msg, args_cp);\n\n  va_end(args_cp);\n\n  // currently there is no error handling for failure, so this is hack.\n  BM_CHECK(ret >= 0);\n\n  if (ret == 0) {  // handle empty expansion\n    return {};\n  }\n  if (static_cast<size_t>(ret) < size) {\n    return local_buff;\n  }\n  // we did not provide a long enough buffer on our first attempt.\n  size = static_cast<size_t>(ret) + 1;  // + 1 for the null byte\n  std::unique_ptr<char[]> buff(new char[size]);\n  ret = vsnprintf(buff.get(), size, msg, args);\n  BM_CHECK(ret > 0 && (static_cast<size_t>(ret)) < size);\n  return buff.get();\n}\n\nstd::string FormatString(const char* msg, ...) {\n  va_list args;\n  va_start(args, msg);\n  auto tmp = FormatString(msg, args);\n  va_end(args);\n  return tmp;\n}\n\nvoid ColorPrintf(std::ostream& out, LogColor color, const char* fmt, ...) {\n  va_list args;\n  va_start(args, fmt);\n  ColorPrintf(out, color, fmt, args);\n  va_end(args);\n}\n\nvoid ColorPrintf(std::ostream& out, LogColor color, const char* fmt,\n                 va_list args) {\n#ifdef BENCHMARK_OS_WINDOWS\n  ((void)out);  // suppress unused warning\n\n  const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);\n\n  // Gets the current text color.\n  CONSOLE_SCREEN_BUFFER_INFO buffer_info;\n  GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);\n  const WORD old_color_attrs = buffer_info.wAttributes;\n\n  // We need to flush the stream buffers into the console before each\n  // SetConsoleTextAttribute call lest it affect the text that is already\n  // printed but has not yet reached the console.\n  fflush(stdout);\n  SetConsoleTextAttribute(stdout_handle,\n                          GetPlatformColorCode(color) | FOREGROUND_INTENSITY);\n  vprintf(fmt, args);\n\n  fflush(stdout);\n  // Restores the text color.\n  SetConsoleTextAttribute(stdout_handle, old_color_attrs);\n#else\n  const char* color_code = GetPlatformColorCode(color);\n  if (color_code) out << FormatString(\"\\033[0;3%sm\", color_code);\n  out << FormatString(fmt, args) << \"\\033[m\";\n#endif\n}\n\nbool IsColorTerminal() {\n#if BENCHMARK_OS_WINDOWS\n  // On Windows the TERM variable is usually not set, but the\n  // console there does support colors.\n  return 0 != _isatty(_fileno(stdout));\n#else\n  // On non-Windows platforms, we rely on the TERM variable. This list of\n  // supported TERM values is copied from Google Test:\n  // <https://github.com/google/googletest/blob/v1.13.0/googletest/src/gtest.cc#L3225-L3259>.\n  const char* const SUPPORTED_TERM_VALUES[] = {\n      \"xterm\",\n      \"xterm-color\",\n      \"xterm-256color\",\n      \"screen\",\n      \"screen-256color\",\n      \"tmux\",\n      \"tmux-256color\",\n      \"rxvt-unicode\",\n      \"rxvt-unicode-256color\",\n      \"linux\",\n      \"cygwin\",\n      \"xterm-kitty\",\n      \"alacritty\",\n      \"foot\",\n      \"foot-extra\",\n      \"wezterm\",\n  };\n\n  const char* const term = getenv(\"TERM\");\n\n  bool term_supports_color = false;\n  for (const char* candidate : SUPPORTED_TERM_VALUES) {\n    if (term && 0 == strcmp(term, candidate)) {\n      term_supports_color = true;\n      break;\n    }\n  }\n\n  return 0 != isatty(fileno(stdout)) && term_supports_color;\n#endif  // BENCHMARK_OS_WINDOWS\n}\n\n}  // end namespace benchmark\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/colorprint.h",
    "content": "#ifndef BENCHMARK_COLORPRINT_H_\n#define BENCHMARK_COLORPRINT_H_\n\n#include <cstdarg>\n#include <iostream>\n#include <string>\n\nnamespace benchmark {\nenum LogColor {\n  COLOR_DEFAULT,\n  COLOR_RED,\n  COLOR_GREEN,\n  COLOR_YELLOW,\n  COLOR_BLUE,\n  COLOR_MAGENTA,\n  COLOR_CYAN,\n  COLOR_WHITE\n};\n\nstd::string FormatString(const char* msg, va_list args);\nstd::string FormatString(const char* msg, ...);\n\nvoid ColorPrintf(std::ostream& out, LogColor color, const char* fmt,\n                 va_list args);\nvoid ColorPrintf(std::ostream& out, LogColor color, const char* fmt, ...);\n\n// Returns true if stdout appears to be a terminal that supports colored\n// output, false otherwise.\nbool IsColorTerminal();\n\n}  // end namespace benchmark\n\n#endif  // BENCHMARK_COLORPRINT_H_\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/commandlineflags.cc",
    "content": "// Copyright 2015 Google Inc. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"commandlineflags.h\"\n\n#include <algorithm>\n#include <cctype>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <limits>\n#include <map>\n#include <utility>\n\n#include \"../src/string_util.h\"\n\nnamespace benchmark {\nnamespace {\n\n// Parses 'str' for a 32-bit signed integer.  If successful, writes\n// the result to *value and returns true; otherwise leaves *value\n// unchanged and returns false.\nbool ParseInt32(const std::string& src_text, const char* str, int32_t* value) {\n  // Parses the environment variable as a decimal integer.\n  char* end = nullptr;\n  const long long_value = strtol(str, &end, 10);  // NOLINT\n\n  // Has strtol() consumed all characters in the string?\n  if (*end != '\\0') {\n    // No - an invalid character was encountered.\n    std::cerr << src_text << \" is expected to be a 32-bit integer, \"\n              << \"but actually has value \\\"\" << str << \"\\\".\\n\";\n    return false;\n  }\n\n  // Is the parsed value in the range of an Int32?\n  const int32_t result = static_cast<int32_t>(long_value);\n  if (long_value == std::numeric_limits<long>::max() ||\n      long_value == std::numeric_limits<long>::min() ||\n      // The parsed value overflows as a long.  (strtol() returns\n      // LONG_MAX or LONG_MIN when the input overflows.)\n      result != long_value\n      // The parsed value overflows as an Int32.\n  ) {\n    std::cerr << src_text << \" is expected to be a 32-bit integer, \"\n              << \"but actually has value \\\"\" << str << \"\\\", \"\n              << \"which overflows.\\n\";\n    return false;\n  }\n\n  *value = result;\n  return true;\n}\n\n// Parses 'str' for a double.  If successful, writes the result to *value and\n// returns true; otherwise leaves *value unchanged and returns false.\nbool ParseDouble(const std::string& src_text, const char* str, double* value) {\n  // Parses the environment variable as a decimal integer.\n  char* end = nullptr;\n  const double double_value = strtod(str, &end);  // NOLINT\n\n  // Has strtol() consumed all characters in the string?\n  if (*end != '\\0') {\n    // No - an invalid character was encountered.\n    std::cerr << src_text << \" is expected to be a double, \"\n              << \"but actually has value \\\"\" << str << \"\\\".\\n\";\n    return false;\n  }\n\n  *value = double_value;\n  return true;\n}\n\n// Parses 'str' into KV pairs. If successful, writes the result to *value and\n// returns true; otherwise leaves *value unchanged and returns false.\nbool ParseKvPairs(const std::string& src_text, const char* str,\n                  std::map<std::string, std::string>* value) {\n  std::map<std::string, std::string> kvs;\n  for (const auto& kvpair : StrSplit(str, ',')) {\n    const auto kv = StrSplit(kvpair, '=');\n    if (kv.size() != 2) {\n      std::cerr << src_text << \" is expected to be a comma-separated list of \"\n                << \"<key>=<value> strings, but actually has value \\\"\" << str\n                << \"\\\".\\n\";\n      return false;\n    }\n    if (!kvs.emplace(kv[0], kv[1]).second) {\n      std::cerr << src_text << \" is expected to contain unique keys but key \\\"\"\n                << kv[0] << \"\\\" was repeated.\\n\";\n      return false;\n    }\n  }\n\n  *value = kvs;\n  return true;\n}\n\n// Returns the name of the environment variable corresponding to the\n// given flag.  For example, FlagToEnvVar(\"foo\") will return\n// \"BENCHMARK_FOO\" in the open-source version.\nstatic std::string FlagToEnvVar(const char* flag) {\n  const std::string flag_str(flag);\n\n  std::string env_var;\n  for (size_t i = 0; i != flag_str.length(); ++i)\n    env_var += static_cast<char>(::toupper(flag_str.c_str()[i]));\n\n  return env_var;\n}\n\n}  // namespace\n\nBENCHMARK_EXPORT\nbool BoolFromEnv(const char* flag, bool default_val) {\n  const std::string env_var = FlagToEnvVar(flag);\n  const char* const value_str = getenv(env_var.c_str());\n  return value_str == nullptr ? default_val : IsTruthyFlagValue(value_str);\n}\n\nBENCHMARK_EXPORT\nint32_t Int32FromEnv(const char* flag, int32_t default_val) {\n  const std::string env_var = FlagToEnvVar(flag);\n  const char* const value_str = getenv(env_var.c_str());\n  int32_t value = default_val;\n  if (value_str == nullptr ||\n      !ParseInt32(std::string(\"Environment variable \") + env_var, value_str,\n                  &value)) {\n    return default_val;\n  }\n  return value;\n}\n\nBENCHMARK_EXPORT\ndouble DoubleFromEnv(const char* flag, double default_val) {\n  const std::string env_var = FlagToEnvVar(flag);\n  const char* const value_str = getenv(env_var.c_str());\n  double value = default_val;\n  if (value_str == nullptr ||\n      !ParseDouble(std::string(\"Environment variable \") + env_var, value_str,\n                   &value)) {\n    return default_val;\n  }\n  return value;\n}\n\nBENCHMARK_EXPORT\nconst char* StringFromEnv(const char* flag, const char* default_val) {\n  const std::string env_var = FlagToEnvVar(flag);\n  const char* const value = getenv(env_var.c_str());\n  return value == nullptr ? default_val : value;\n}\n\nBENCHMARK_EXPORT\nstd::map<std::string, std::string> KvPairsFromEnv(\n    const char* flag, std::map<std::string, std::string> default_val) {\n  const std::string env_var = FlagToEnvVar(flag);\n  const char* const value_str = getenv(env_var.c_str());\n\n  if (value_str == nullptr) return default_val;\n\n  std::map<std::string, std::string> value;\n  if (!ParseKvPairs(\"Environment variable \" + env_var, value_str, &value)) {\n    return default_val;\n  }\n  return value;\n}\n\n// Parses a string as a command line flag.  The string should have\n// the format \"--flag=value\".  When def_optional is true, the \"=value\"\n// part can be omitted.\n//\n// Returns the value of the flag, or nullptr if the parsing failed.\nconst char* ParseFlagValue(const char* str, const char* flag,\n                           bool def_optional) {\n  // str and flag must not be nullptr.\n  if (str == nullptr || flag == nullptr) return nullptr;\n\n  // The flag must start with \"--\".\n  const std::string flag_str = std::string(\"--\") + std::string(flag);\n  const size_t flag_len = flag_str.length();\n  if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr;\n\n  // Skips the flag name.\n  const char* flag_end = str + flag_len;\n\n  // When def_optional is true, it's OK to not have a \"=value\" part.\n  if (def_optional && (flag_end[0] == '\\0')) return flag_end;\n\n  // If def_optional is true and there are more characters after the\n  // flag name, or if def_optional is false, there must be a '=' after\n  // the flag name.\n  if (flag_end[0] != '=') return nullptr;\n\n  // Returns the string after \"=\".\n  return flag_end + 1;\n}\n\nBENCHMARK_EXPORT\nbool ParseBoolFlag(const char* str, const char* flag, bool* value) {\n  // Gets the value of the flag as a string.\n  const char* const value_str = ParseFlagValue(str, flag, true);\n\n  // Aborts if the parsing failed.\n  if (value_str == nullptr) return false;\n\n  // Converts the string value to a bool.\n  *value = IsTruthyFlagValue(value_str);\n  return true;\n}\n\nBENCHMARK_EXPORT\nbool ParseInt32Flag(const char* str, const char* flag, int32_t* value) {\n  // Gets the value of the flag as a string.\n  const char* const value_str = ParseFlagValue(str, flag, false);\n\n  // Aborts if the parsing failed.\n  if (value_str == nullptr) return false;\n\n  // Sets *value to the value of the flag.\n  return ParseInt32(std::string(\"The value of flag --\") + flag, value_str,\n                    value);\n}\n\nBENCHMARK_EXPORT\nbool ParseDoubleFlag(const char* str, const char* flag, double* value) {\n  // Gets the value of the flag as a string.\n  const char* const value_str = ParseFlagValue(str, flag, false);\n\n  // Aborts if the parsing failed.\n  if (value_str == nullptr) return false;\n\n  // Sets *value to the value of the flag.\n  return ParseDouble(std::string(\"The value of flag --\") + flag, value_str,\n                     value);\n}\n\nBENCHMARK_EXPORT\nbool ParseStringFlag(const char* str, const char* flag, std::string* value) {\n  // Gets the value of the flag as a string.\n  const char* const value_str = ParseFlagValue(str, flag, false);\n\n  // Aborts if the parsing failed.\n  if (value_str == nullptr) return false;\n\n  *value = value_str;\n  return true;\n}\n\nBENCHMARK_EXPORT\nbool ParseKeyValueFlag(const char* str, const char* flag,\n                       std::map<std::string, std::string>* value) {\n  const char* const value_str = ParseFlagValue(str, flag, false);\n\n  if (value_str == nullptr) return false;\n\n  for (const auto& kvpair : StrSplit(value_str, ',')) {\n    const auto kv = StrSplit(kvpair, '=');\n    if (kv.size() != 2) return false;\n    value->emplace(kv[0], kv[1]);\n  }\n\n  return true;\n}\n\nBENCHMARK_EXPORT\nbool IsFlag(const char* str, const char* flag) {\n  return (ParseFlagValue(str, flag, true) != nullptr);\n}\n\nBENCHMARK_EXPORT\nbool IsTruthyFlagValue(const std::string& value) {\n  if (value.size() == 1) {\n    char v = value[0];\n    return isalnum(v) &&\n           !(v == '0' || v == 'f' || v == 'F' || v == 'n' || v == 'N');\n  }\n  if (!value.empty()) {\n    std::string value_lower(value);\n    std::transform(value_lower.begin(), value_lower.end(), value_lower.begin(),\n                   [](char c) { return static_cast<char>(::tolower(c)); });\n    return !(value_lower == \"false\" || value_lower == \"no\" ||\n             value_lower == \"off\");\n  }\n  return true;\n}\n\n}  // end namespace benchmark\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/commandlineflags.h",
    "content": "#ifndef BENCHMARK_COMMANDLINEFLAGS_H_\n#define BENCHMARK_COMMANDLINEFLAGS_H_\n\n#include <cstdint>\n#include <map>\n#include <string>\n\n#include \"benchmark/export.h\"\n\n// Macro for referencing flags.\n#define FLAG(name) FLAGS_##name\n\n// Macros for declaring flags.\n#define BM_DECLARE_bool(name) BENCHMARK_EXPORT extern bool FLAG(name)\n#define BM_DECLARE_int32(name) BENCHMARK_EXPORT extern int32_t FLAG(name)\n#define BM_DECLARE_double(name) BENCHMARK_EXPORT extern double FLAG(name)\n#define BM_DECLARE_string(name) BENCHMARK_EXPORT extern std::string FLAG(name)\n#define BM_DECLARE_kvpairs(name) \\\n  BENCHMARK_EXPORT extern std::map<std::string, std::string> FLAG(name)\n\n// Macros for defining flags.\n#define BM_DEFINE_bool(name, default_val) \\\n  BENCHMARK_EXPORT bool FLAG(name) = benchmark::BoolFromEnv(#name, default_val)\n#define BM_DEFINE_int32(name, default_val) \\\n  BENCHMARK_EXPORT int32_t FLAG(name) =    \\\n      benchmark::Int32FromEnv(#name, default_val)\n#define BM_DEFINE_double(name, default_val) \\\n  BENCHMARK_EXPORT double FLAG(name) =      \\\n      benchmark::DoubleFromEnv(#name, default_val)\n#define BM_DEFINE_string(name, default_val) \\\n  BENCHMARK_EXPORT std::string FLAG(name) = \\\n      benchmark::StringFromEnv(#name, default_val)\n#define BM_DEFINE_kvpairs(name, default_val)                       \\\n  BENCHMARK_EXPORT std::map<std::string, std::string> FLAG(name) = \\\n      benchmark::KvPairsFromEnv(#name, default_val)\n\nnamespace benchmark {\n\n// Parses a bool from the environment variable corresponding to the given flag.\n//\n// If the variable exists, returns IsTruthyFlagValue() value;  if not,\n// returns the given default value.\nBENCHMARK_EXPORT\nbool BoolFromEnv(const char* flag, bool default_val);\n\n// Parses an Int32 from the environment variable corresponding to the given\n// flag.\n//\n// If the variable exists, returns ParseInt32() value;  if not, returns\n// the given default value.\nBENCHMARK_EXPORT\nint32_t Int32FromEnv(const char* flag, int32_t default_val);\n\n// Parses an Double from the environment variable corresponding to the given\n// flag.\n//\n// If the variable exists, returns ParseDouble();  if not, returns\n// the given default value.\nBENCHMARK_EXPORT\ndouble DoubleFromEnv(const char* flag, double default_val);\n\n// Parses a string from the environment variable corresponding to the given\n// flag.\n//\n// If variable exists, returns its value;  if not, returns\n// the given default value.\nBENCHMARK_EXPORT\nconst char* StringFromEnv(const char* flag, const char* default_val);\n\n// Parses a set of kvpairs from the environment variable corresponding to the\n// given flag.\n//\n// If variable exists, returns its value;  if not, returns\n// the given default value.\nBENCHMARK_EXPORT\nstd::map<std::string, std::string> KvPairsFromEnv(\n    const char* flag, std::map<std::string, std::string> default_val);\n\n// Parses a string for a bool flag, in the form of either\n// \"--flag=value\" or \"--flag\".\n//\n// In the former case, the value is taken as true if it passes IsTruthyValue().\n//\n// In the latter case, the value is taken as true.\n//\n// On success, stores the value of the flag in *value, and returns\n// true.  On failure, returns false without changing *value.\nBENCHMARK_EXPORT\nbool ParseBoolFlag(const char* str, const char* flag, bool* value);\n\n// Parses a string for an Int32 flag, in the form of \"--flag=value\".\n//\n// On success, stores the value of the flag in *value, and returns\n// true.  On failure, returns false without changing *value.\nBENCHMARK_EXPORT\nbool ParseInt32Flag(const char* str, const char* flag, int32_t* value);\n\n// Parses a string for a Double flag, in the form of \"--flag=value\".\n//\n// On success, stores the value of the flag in *value, and returns\n// true.  On failure, returns false without changing *value.\nBENCHMARK_EXPORT\nbool ParseDoubleFlag(const char* str, const char* flag, double* value);\n\n// Parses a string for a string flag, in the form of \"--flag=value\".\n//\n// On success, stores the value of the flag in *value, and returns\n// true.  On failure, returns false without changing *value.\nBENCHMARK_EXPORT\nbool ParseStringFlag(const char* str, const char* flag, std::string* value);\n\n// Parses a string for a kvpairs flag in the form \"--flag=key=value,key=value\"\n//\n// On success, stores the value of the flag in *value and returns true. On\n// failure returns false, though *value may have been mutated.\nBENCHMARK_EXPORT\nbool ParseKeyValueFlag(const char* str, const char* flag,\n                       std::map<std::string, std::string>* value);\n\n// Returns true if the string matches the flag.\nBENCHMARK_EXPORT\nbool IsFlag(const char* str, const char* flag);\n\n// Returns true unless value starts with one of: '0', 'f', 'F', 'n' or 'N', or\n// some non-alphanumeric character. Also returns false if the value matches\n// one of 'no', 'false', 'off' (case-insensitive). As a special case, also\n// returns true if value is the empty string.\nBENCHMARK_EXPORT\nbool IsTruthyFlagValue(const std::string& value);\n\n}  // end namespace benchmark\n\n#endif  // BENCHMARK_COMMANDLINEFLAGS_H_\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/complexity.cc",
    "content": "// Copyright 2016 Ismael Jimenez Martinez. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// Source project : https://github.com/ismaelJimenez/cpp.leastsq\n// Adapted to be used with google benchmark\n\n#include \"complexity.h\"\n\n#include <algorithm>\n#include <cmath>\n\n#include \"benchmark/benchmark.h\"\n#include \"check.h\"\n\nnamespace benchmark {\n\n// Internal function to calculate the different scalability forms\nBigOFunc* FittingCurve(BigO complexity) {\n  static const double kLog2E = 1.44269504088896340736;\n  switch (complexity) {\n    case oN:\n      return [](IterationCount n) -> double { return static_cast<double>(n); };\n    case oNSquared:\n      return [](IterationCount n) -> double { return std::pow(n, 2); };\n    case oNCubed:\n      return [](IterationCount n) -> double { return std::pow(n, 3); };\n    case oLogN:\n      /* Note: can't use log2 because Android's GNU STL lacks it */\n      return\n          [](IterationCount n) { return kLog2E * log(static_cast<double>(n)); };\n    case oNLogN:\n      /* Note: can't use log2 because Android's GNU STL lacks it */\n      return [](IterationCount n) {\n        return kLog2E * n * log(static_cast<double>(n));\n      };\n    case o1:\n    default:\n      return [](IterationCount) { return 1.0; };\n  }\n}\n\n// Function to return an string for the calculated complexity\nstd::string GetBigOString(BigO complexity) {\n  switch (complexity) {\n    case oN:\n      return \"N\";\n    case oNSquared:\n      return \"N^2\";\n    case oNCubed:\n      return \"N^3\";\n    case oLogN:\n      return \"lgN\";\n    case oNLogN:\n      return \"NlgN\";\n    case o1:\n      return \"(1)\";\n    default:\n      return \"f(N)\";\n  }\n}\n\n// Find the coefficient for the high-order term in the running time, by\n// minimizing the sum of squares of relative error, for the fitting curve\n// given by the lambda expression.\n//   - n             : Vector containing the size of the benchmark tests.\n//   - time          : Vector containing the times for the benchmark tests.\n//   - fitting_curve : lambda expression (e.g. [](int64_t n) {return n; };).\n\n// For a deeper explanation on the algorithm logic, please refer to\n// https://en.wikipedia.org/wiki/Least_squares#Least_squares,_regression_analysis_and_statistics\n\nLeastSq MinimalLeastSq(const std::vector<int64_t>& n,\n                       const std::vector<double>& time,\n                       BigOFunc* fitting_curve) {\n  double sigma_gn_squared = 0.0;\n  double sigma_time = 0.0;\n  double sigma_time_gn = 0.0;\n\n  // Calculate least square fitting parameter\n  for (size_t i = 0; i < n.size(); ++i) {\n    double gn_i = fitting_curve(n[i]);\n    sigma_gn_squared += gn_i * gn_i;\n    sigma_time += time[i];\n    sigma_time_gn += time[i] * gn_i;\n  }\n\n  LeastSq result;\n  result.complexity = oLambda;\n\n  // Calculate complexity.\n  result.coef = sigma_time_gn / sigma_gn_squared;\n\n  // Calculate RMS\n  double rms = 0.0;\n  for (size_t i = 0; i < n.size(); ++i) {\n    double fit = result.coef * fitting_curve(n[i]);\n    rms += pow((time[i] - fit), 2);\n  }\n\n  // Normalized RMS by the mean of the observed values\n  double mean = sigma_time / n.size();\n  result.rms = sqrt(rms / n.size()) / mean;\n\n  return result;\n}\n\n// Find the coefficient for the high-order term in the running time, by\n// minimizing the sum of squares of relative error.\n//   - n          : Vector containing the size of the benchmark tests.\n//   - time       : Vector containing the times for the benchmark tests.\n//   - complexity : If different than oAuto, the fitting curve will stick to\n//                  this one. If it is oAuto, it will be calculated the best\n//                  fitting curve.\nLeastSq MinimalLeastSq(const std::vector<int64_t>& n,\n                       const std::vector<double>& time, const BigO complexity) {\n  BM_CHECK_EQ(n.size(), time.size());\n  BM_CHECK_GE(n.size(), 2);  // Do not compute fitting curve is less than two\n                             // benchmark runs are given\n  BM_CHECK_NE(complexity, oNone);\n\n  LeastSq best_fit;\n\n  if (complexity == oAuto) {\n    std::vector<BigO> fit_curves = {oLogN, oN, oNLogN, oNSquared, oNCubed};\n\n    // Take o1 as default best fitting curve\n    best_fit = MinimalLeastSq(n, time, FittingCurve(o1));\n    best_fit.complexity = o1;\n\n    // Compute all possible fitting curves and stick to the best one\n    for (const auto& fit : fit_curves) {\n      LeastSq current_fit = MinimalLeastSq(n, time, FittingCurve(fit));\n      if (current_fit.rms < best_fit.rms) {\n        best_fit = current_fit;\n        best_fit.complexity = fit;\n      }\n    }\n  } else {\n    best_fit = MinimalLeastSq(n, time, FittingCurve(complexity));\n    best_fit.complexity = complexity;\n  }\n\n  return best_fit;\n}\n\nstd::vector<BenchmarkReporter::Run> ComputeBigO(\n    const std::vector<BenchmarkReporter::Run>& reports) {\n  typedef BenchmarkReporter::Run Run;\n  std::vector<Run> results;\n\n  if (reports.size() < 2) return results;\n\n  // Accumulators.\n  std::vector<int64_t> n;\n  std::vector<double> real_time;\n  std::vector<double> cpu_time;\n\n  // Populate the accumulators.\n  for (const Run& run : reports) {\n    BM_CHECK_GT(run.complexity_n, 0)\n        << \"Did you forget to call SetComplexityN?\";\n    n.push_back(run.complexity_n);\n    real_time.push_back(run.real_accumulated_time / run.iterations);\n    cpu_time.push_back(run.cpu_accumulated_time / run.iterations);\n  }\n\n  LeastSq result_cpu;\n  LeastSq result_real;\n\n  if (reports[0].complexity == oLambda) {\n    result_cpu = MinimalLeastSq(n, cpu_time, reports[0].complexity_lambda);\n    result_real = MinimalLeastSq(n, real_time, reports[0].complexity_lambda);\n  } else {\n    result_cpu = MinimalLeastSq(n, cpu_time, reports[0].complexity);\n    result_real = MinimalLeastSq(n, real_time, result_cpu.complexity);\n  }\n\n  // Drop the 'args' when reporting complexity.\n  auto run_name = reports[0].run_name;\n  run_name.args.clear();\n\n  // Get the data from the accumulator to BenchmarkReporter::Run's.\n  Run big_o;\n  big_o.run_name = run_name;\n  big_o.family_index = reports[0].family_index;\n  big_o.per_family_instance_index = reports[0].per_family_instance_index;\n  big_o.run_type = BenchmarkReporter::Run::RT_Aggregate;\n  big_o.repetitions = reports[0].repetitions;\n  big_o.repetition_index = Run::no_repetition_index;\n  big_o.threads = reports[0].threads;\n  big_o.aggregate_name = \"BigO\";\n  big_o.aggregate_unit = StatisticUnit::kTime;\n  big_o.report_label = reports[0].report_label;\n  big_o.iterations = 0;\n  big_o.real_accumulated_time = result_real.coef;\n  big_o.cpu_accumulated_time = result_cpu.coef;\n  big_o.report_big_o = true;\n  big_o.complexity = result_cpu.complexity;\n\n  // All the time results are reported after being multiplied by the\n  // time unit multiplier. But since RMS is a relative quantity it\n  // should not be multiplied at all. So, here, we _divide_ it by the\n  // multiplier so that when it is multiplied later the result is the\n  // correct one.\n  double multiplier = GetTimeUnitMultiplier(reports[0].time_unit);\n\n  // Only add label to mean/stddev if it is same for all runs\n  Run rms;\n  rms.run_name = run_name;\n  rms.family_index = reports[0].family_index;\n  rms.per_family_instance_index = reports[0].per_family_instance_index;\n  rms.run_type = BenchmarkReporter::Run::RT_Aggregate;\n  rms.aggregate_name = \"RMS\";\n  rms.aggregate_unit = StatisticUnit::kPercentage;\n  rms.report_label = big_o.report_label;\n  rms.iterations = 0;\n  rms.repetition_index = Run::no_repetition_index;\n  rms.repetitions = reports[0].repetitions;\n  rms.threads = reports[0].threads;\n  rms.real_accumulated_time = result_real.rms / multiplier;\n  rms.cpu_accumulated_time = result_cpu.rms / multiplier;\n  rms.report_rms = true;\n  rms.complexity = result_cpu.complexity;\n  // don't forget to keep the time unit, or we won't be able to\n  // recover the correct value.\n  rms.time_unit = reports[0].time_unit;\n\n  results.push_back(big_o);\n  results.push_back(rms);\n  return results;\n}\n\n}  // end namespace benchmark\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/complexity.h",
    "content": "// Copyright 2016 Ismael Jimenez Martinez. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// Source project : https://github.com/ismaelJimenez/cpp.leastsq\n// Adapted to be used with google benchmark\n\n#ifndef COMPLEXITY_H_\n#define COMPLEXITY_H_\n\n#include <string>\n#include <vector>\n\n#include \"benchmark/benchmark.h\"\n\nnamespace benchmark {\n\n// Return a vector containing the bigO and RMS information for the specified\n// list of reports. If 'reports.size() < 2' an empty vector is returned.\nstd::vector<BenchmarkReporter::Run> ComputeBigO(\n    const std::vector<BenchmarkReporter::Run>& reports);\n\n// This data structure will contain the result returned by MinimalLeastSq\n//   - coef        : Estimated coefficient for the high-order term as\n//                   interpolated from data.\n//   - rms         : Normalized Root Mean Squared Error.\n//   - complexity  : Scalability form (e.g. oN, oNLogN). In case a scalability\n//                   form has been provided to MinimalLeastSq this will return\n//                   the same value. In case BigO::oAuto has been selected, this\n//                   parameter will return the best fitting curve detected.\n\nstruct LeastSq {\n  LeastSq() : coef(0.0), rms(0.0), complexity(oNone) {}\n\n  double coef;\n  double rms;\n  BigO complexity;\n};\n\n// Function to return an string for the calculated complexity\nstd::string GetBigOString(BigO complexity);\n\n}  // end namespace benchmark\n\n#endif  // COMPLEXITY_H_\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/console_reporter.cc",
    "content": "// Copyright 2015 Google Inc. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include <algorithm>\n#include <cstdint>\n#include <cstdio>\n#include <cstring>\n#include <iostream>\n#include <string>\n#include <tuple>\n#include <vector>\n\n#include \"benchmark/benchmark.h\"\n#include \"check.h\"\n#include \"colorprint.h\"\n#include \"commandlineflags.h\"\n#include \"complexity.h\"\n#include \"counter.h\"\n#include \"internal_macros.h\"\n#include \"string_util.h\"\n#include \"timers.h\"\n\nnamespace benchmark {\n\nBENCHMARK_EXPORT\nbool ConsoleReporter::ReportContext(const Context& context) {\n  name_field_width_ = context.name_field_width;\n  printed_header_ = false;\n  prev_counters_.clear();\n\n  PrintBasicContext(&GetErrorStream(), context);\n\n#ifdef BENCHMARK_OS_WINDOWS\n  if ((output_options_ & OO_Color) && &std::cout != &GetOutputStream()) {\n    GetErrorStream()\n        << \"Color printing is only supported for stdout on windows.\"\n           \" Disabling color printing\\n\";\n    output_options_ = static_cast<OutputOptions>(output_options_ & ~OO_Color);\n  }\n#endif\n\n  return true;\n}\n\nBENCHMARK_EXPORT\nvoid ConsoleReporter::PrintHeader(const Run& run) {\n  std::string str =\n      FormatString(\"%-*s %13s %15s %12s\", static_cast<int>(name_field_width_),\n                   \"Benchmark\", \"Time\", \"CPU\", \"Iterations\");\n  if (!run.counters.empty()) {\n    if (output_options_ & OO_Tabular) {\n      for (auto const& c : run.counters) {\n        str += FormatString(\" %10s\", c.first.c_str());\n      }\n    } else {\n      str += \" UserCounters...\";\n    }\n  }\n  std::string line = std::string(str.length(), '-');\n  GetOutputStream() << line << \"\\n\" << str << \"\\n\" << line << \"\\n\";\n}\n\nBENCHMARK_EXPORT\nvoid ConsoleReporter::ReportRuns(const std::vector<Run>& reports) {\n  for (const auto& run : reports) {\n    // print the header:\n    // --- if none was printed yet\n    bool print_header = !printed_header_;\n    // --- or if the format is tabular and this run\n    //     has different fields from the prev header\n    print_header |= (output_options_ & OO_Tabular) &&\n                    (!internal::SameNames(run.counters, prev_counters_));\n    if (print_header) {\n      printed_header_ = true;\n      prev_counters_ = run.counters;\n      PrintHeader(run);\n    }\n    // As an alternative to printing the headers like this, we could sort\n    // the benchmarks by header and then print. But this would require\n    // waiting for the full results before printing, or printing twice.\n    PrintRunData(run);\n  }\n}\n\nstatic void IgnoreColorPrint(std::ostream& out, LogColor, const char* fmt,\n                             ...) {\n  va_list args;\n  va_start(args, fmt);\n  out << FormatString(fmt, args);\n  va_end(args);\n}\n\nstatic std::string FormatTime(double time) {\n  // For the time columns of the console printer 13 digits are reserved. One of\n  // them is a space and max two of them are the time unit (e.g ns). That puts\n  // us at 10 digits usable for the number.\n  // Align decimal places...\n  if (time < 1.0) {\n    return FormatString(\"%10.3f\", time);\n  }\n  if (time < 10.0) {\n    return FormatString(\"%10.2f\", time);\n  }\n  if (time < 100.0) {\n    return FormatString(\"%10.1f\", time);\n  }\n  // Assuming the time is at max 9.9999e+99 and we have 10 digits for the\n  // number, we get 10-1(.)-1(e)-1(sign)-2(exponent) = 5 digits to print.\n  if (time > 9999999999 /*max 10 digit number*/) {\n    return FormatString(\"%1.4e\", time);\n  }\n  return FormatString(\"%10.0f\", time);\n}\n\nBENCHMARK_EXPORT\nvoid ConsoleReporter::PrintRunData(const Run& result) {\n  typedef void(PrinterFn)(std::ostream&, LogColor, const char*, ...);\n  auto& Out = GetOutputStream();\n  PrinterFn* printer = (output_options_ & OO_Color)\n                           ? static_cast<PrinterFn*>(ColorPrintf)\n                           : IgnoreColorPrint;\n  auto name_color =\n      (result.report_big_o || result.report_rms) ? COLOR_BLUE : COLOR_GREEN;\n  printer(Out, name_color, \"%-*s \", name_field_width_,\n          result.benchmark_name().c_str());\n\n  if (internal::SkippedWithError == result.skipped) {\n    printer(Out, COLOR_RED, \"ERROR OCCURRED: \\'%s\\'\",\n            result.skip_message.c_str());\n    printer(Out, COLOR_DEFAULT, \"\\n\");\n    return;\n  } else if (internal::SkippedWithMessage == result.skipped) {\n    printer(Out, COLOR_WHITE, \"SKIPPED: \\'%s\\'\", result.skip_message.c_str());\n    printer(Out, COLOR_DEFAULT, \"\\n\");\n    return;\n  }\n\n  const double real_time = result.GetAdjustedRealTime();\n  const double cpu_time = result.GetAdjustedCPUTime();\n  const std::string real_time_str = FormatTime(real_time);\n  const std::string cpu_time_str = FormatTime(cpu_time);\n\n  if (result.report_big_o) {\n    std::string big_o = GetBigOString(result.complexity);\n    printer(Out, COLOR_YELLOW, \"%10.2f %-4s %10.2f %-4s \", real_time,\n            big_o.c_str(), cpu_time, big_o.c_str());\n  } else if (result.report_rms) {\n    printer(Out, COLOR_YELLOW, \"%10.0f %-4s %10.0f %-4s \", real_time * 100, \"%\",\n            cpu_time * 100, \"%\");\n  } else if (result.run_type != Run::RT_Aggregate ||\n             result.aggregate_unit == StatisticUnit::kTime) {\n    const char* timeLabel = GetTimeUnitString(result.time_unit);\n    printer(Out, COLOR_YELLOW, \"%s %-4s %s %-4s \", real_time_str.c_str(),\n            timeLabel, cpu_time_str.c_str(), timeLabel);\n  } else {\n    assert(result.aggregate_unit == StatisticUnit::kPercentage);\n    printer(Out, COLOR_YELLOW, \"%10.2f %-4s %10.2f %-4s \",\n            (100. * result.real_accumulated_time), \"%\",\n            (100. * result.cpu_accumulated_time), \"%\");\n  }\n\n  if (!result.report_big_o && !result.report_rms) {\n    printer(Out, COLOR_CYAN, \"%10lld\", result.iterations);\n  }\n\n  for (auto& c : result.counters) {\n    const std::size_t cNameLen =\n        std::max(std::string::size_type(10), c.first.length());\n    std::string s;\n    const char* unit = \"\";\n    if (result.run_type == Run::RT_Aggregate &&\n        result.aggregate_unit == StatisticUnit::kPercentage) {\n      s = StrFormat(\"%.2f\", 100. * c.second.value);\n      unit = \"%\";\n    } else {\n      s = HumanReadableNumber(c.second.value, c.second.oneK);\n      if (c.second.flags & Counter::kIsRate)\n        unit = (c.second.flags & Counter::kInvert) ? \"s\" : \"/s\";\n    }\n    if (output_options_ & OO_Tabular) {\n      printer(Out, COLOR_DEFAULT, \" %*s%s\", cNameLen - strlen(unit), s.c_str(),\n              unit);\n    } else {\n      printer(Out, COLOR_DEFAULT, \" %s=%s%s\", c.first.c_str(), s.c_str(), unit);\n    }\n  }\n\n  if (!result.report_label.empty()) {\n    printer(Out, COLOR_DEFAULT, \" %s\", result.report_label.c_str());\n  }\n\n  printer(Out, COLOR_DEFAULT, \"\\n\");\n}\n\n}  // end namespace benchmark\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/counter.cc",
    "content": "// Copyright 2015 Google Inc. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"counter.h\"\n\nnamespace benchmark {\nnamespace internal {\n\ndouble Finish(Counter const& c, IterationCount iterations, double cpu_time,\n              double num_threads) {\n  double v = c.value;\n  if (c.flags & Counter::kIsRate) {\n    v /= cpu_time;\n  }\n  if (c.flags & Counter::kAvgThreads) {\n    v /= num_threads;\n  }\n  if (c.flags & Counter::kIsIterationInvariant) {\n    v *= iterations;\n  }\n  if (c.flags & Counter::kAvgIterations) {\n    v /= iterations;\n  }\n\n  if (c.flags & Counter::kInvert) {  // Invert is *always* last.\n    v = 1.0 / v;\n  }\n  return v;\n}\n\nvoid Finish(UserCounters* l, IterationCount iterations, double cpu_time,\n            double num_threads) {\n  for (auto& c : *l) {\n    c.second.value = Finish(c.second, iterations, cpu_time, num_threads);\n  }\n}\n\nvoid Increment(UserCounters* l, UserCounters const& r) {\n  // add counters present in both or just in *l\n  for (auto& c : *l) {\n    auto it = r.find(c.first);\n    if (it != r.end()) {\n      c.second.value = c.second + it->second;\n    }\n  }\n  // add counters present in r, but not in *l\n  for (auto const& tc : r) {\n    auto it = l->find(tc.first);\n    if (it == l->end()) {\n      (*l)[tc.first] = tc.second;\n    }\n  }\n}\n\nbool SameNames(UserCounters const& l, UserCounters const& r) {\n  if (&l == &r) return true;\n  if (l.size() != r.size()) {\n    return false;\n  }\n  for (auto const& c : l) {\n    if (r.find(c.first) == r.end()) {\n      return false;\n    }\n  }\n  return true;\n}\n\n}  // end namespace internal\n}  // end namespace benchmark\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/counter.h",
    "content": "// Copyright 2015 Google Inc. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef BENCHMARK_COUNTER_H_\n#define BENCHMARK_COUNTER_H_\n\n#include \"benchmark/benchmark.h\"\n\nnamespace benchmark {\n\n// these counter-related functions are hidden to reduce API surface.\nnamespace internal {\nvoid Finish(UserCounters* l, IterationCount iterations, double time,\n            double num_threads);\nvoid Increment(UserCounters* l, UserCounters const& r);\nbool SameNames(UserCounters const& l, UserCounters const& r);\n}  // end namespace internal\n\n}  // end namespace benchmark\n\n#endif  // BENCHMARK_COUNTER_H_\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/csv_reporter.cc",
    "content": "// Copyright 2015 Google Inc. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include <algorithm>\n#include <cstdint>\n#include <iostream>\n#include <string>\n#include <tuple>\n#include <vector>\n\n#include \"benchmark/benchmark.h\"\n#include \"check.h\"\n#include \"complexity.h\"\n#include \"string_util.h\"\n#include \"timers.h\"\n\n// File format reference: http://edoceo.com/utilitas/csv-file-format.\n\nnamespace benchmark {\n\nnamespace {\nstd::vector<std::string> elements = {\n    \"name\",           \"iterations\",       \"real_time\",        \"cpu_time\",\n    \"time_unit\",      \"bytes_per_second\", \"items_per_second\", \"label\",\n    \"error_occurred\", \"error_message\"};\n}  // namespace\n\nstd::string CsvEscape(const std::string& s) {\n  std::string tmp;\n  tmp.reserve(s.size() + 2);\n  for (char c : s) {\n    switch (c) {\n      case '\"':\n        tmp += \"\\\"\\\"\";\n        break;\n      default:\n        tmp += c;\n        break;\n    }\n  }\n  return '\"' + tmp + '\"';\n}\n\nBENCHMARK_EXPORT\nbool CSVReporter::ReportContext(const Context& context) {\n  PrintBasicContext(&GetErrorStream(), context);\n  return true;\n}\n\nBENCHMARK_EXPORT\nvoid CSVReporter::ReportRuns(const std::vector<Run>& reports) {\n  std::ostream& Out = GetOutputStream();\n\n  if (!printed_header_) {\n    // save the names of all the user counters\n    for (const auto& run : reports) {\n      for (const auto& cnt : run.counters) {\n        if (cnt.first == \"bytes_per_second\" || cnt.first == \"items_per_second\")\n          continue;\n        user_counter_names_.insert(cnt.first);\n      }\n    }\n\n    // print the header\n    for (auto B = elements.begin(); B != elements.end();) {\n      Out << *B++;\n      if (B != elements.end()) Out << \",\";\n    }\n    for (auto B = user_counter_names_.begin();\n         B != user_counter_names_.end();) {\n      Out << \",\\\"\" << *B++ << \"\\\"\";\n    }\n    Out << \"\\n\";\n\n    printed_header_ = true;\n  } else {\n    // check that all the current counters are saved in the name set\n    for (const auto& run : reports) {\n      for (const auto& cnt : run.counters) {\n        if (cnt.first == \"bytes_per_second\" || cnt.first == \"items_per_second\")\n          continue;\n        BM_CHECK(user_counter_names_.find(cnt.first) !=\n                 user_counter_names_.end())\n            << \"All counters must be present in each run. \"\n            << \"Counter named \\\"\" << cnt.first\n            << \"\\\" was not in a run after being added to the header\";\n      }\n    }\n  }\n\n  // print results for each run\n  for (const auto& run : reports) {\n    PrintRunData(run);\n  }\n}\n\nBENCHMARK_EXPORT\nvoid CSVReporter::PrintRunData(const Run& run) {\n  std::ostream& Out = GetOutputStream();\n  Out << CsvEscape(run.benchmark_name()) << \",\";\n  if (run.skipped) {\n    Out << std::string(elements.size() - 3, ',');\n    Out << std::boolalpha << (internal::SkippedWithError == run.skipped) << \",\";\n    Out << CsvEscape(run.skip_message) << \"\\n\";\n    return;\n  }\n\n  // Do not print iteration on bigO and RMS report\n  if (!run.report_big_o && !run.report_rms) {\n    Out << run.iterations;\n  }\n  Out << \",\";\n\n  Out << run.GetAdjustedRealTime() << \",\";\n  Out << run.GetAdjustedCPUTime() << \",\";\n\n  // Do not print timeLabel on bigO and RMS report\n  if (run.report_big_o) {\n    Out << GetBigOString(run.complexity);\n  } else if (!run.report_rms) {\n    Out << GetTimeUnitString(run.time_unit);\n  }\n  Out << \",\";\n\n  if (run.counters.find(\"bytes_per_second\") != run.counters.end()) {\n    Out << run.counters.at(\"bytes_per_second\");\n  }\n  Out << \",\";\n  if (run.counters.find(\"items_per_second\") != run.counters.end()) {\n    Out << run.counters.at(\"items_per_second\");\n  }\n  Out << \",\";\n  if (!run.report_label.empty()) {\n    Out << CsvEscape(run.report_label);\n  }\n  Out << \",,\";  // for error_occurred and error_message\n\n  // Print user counters\n  for (const auto& ucn : user_counter_names_) {\n    auto it = run.counters.find(ucn);\n    if (it == run.counters.end()) {\n      Out << \",\";\n    } else {\n      Out << \",\" << it->second;\n    }\n  }\n  Out << '\\n';\n}\n\n}  // end namespace benchmark\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/cycleclock.h",
    "content": "// ----------------------------------------------------------------------\n// CycleClock\n//    A CycleClock tells you the current time in Cycles.  The \"time\"\n//    is actually time since power-on.  This is like time() but doesn't\n//    involve a system call and is much more precise.\n//\n// NOTE: Not all cpu/platform/kernel combinations guarantee that this\n// clock increments at a constant rate or is synchronized across all logical\n// cpus in a system.\n//\n// If you need the above guarantees, please consider using a different\n// API. There are efforts to provide an interface which provides a millisecond\n// granularity and implemented as a memory read. A memory read is generally\n// cheaper than the CycleClock for many architectures.\n//\n// Also, in some out of order CPU implementations, the CycleClock is not\n// serializing. So if you're trying to count at cycles granularity, your\n// data might be inaccurate due to out of order instruction execution.\n// ----------------------------------------------------------------------\n\n#ifndef BENCHMARK_CYCLECLOCK_H_\n#define BENCHMARK_CYCLECLOCK_H_\n\n#include <cstdint>\n\n#include \"benchmark/benchmark.h\"\n#include \"internal_macros.h\"\n\n#if defined(BENCHMARK_OS_MACOSX)\n#include <mach/mach_time.h>\n#endif\n// For MSVC, we want to use '_asm rdtsc' when possible (since it works\n// with even ancient MSVC compilers), and when not possible the\n// __rdtsc intrinsic, declared in <intrin.h>.  Unfortunately, in some\n// environments, <windows.h> and <intrin.h> have conflicting\n// declarations of some other intrinsics, breaking compilation.\n// Therefore, we simply declare __rdtsc ourselves. See also\n// http://connect.microsoft.com/VisualStudio/feedback/details/262047\n#if defined(COMPILER_MSVC) && !defined(_M_IX86) && !defined(_M_ARM64) && \\\n    !defined(_M_ARM64EC)\nextern \"C\" uint64_t __rdtsc();\n#pragma intrinsic(__rdtsc)\n#endif\n\n#if !defined(BENCHMARK_OS_WINDOWS) || defined(BENCHMARK_OS_MINGW)\n#include <sys/time.h>\n#include <time.h>\n#endif\n\n#ifdef BENCHMARK_OS_EMSCRIPTEN\n#include <emscripten.h>\n#endif\n\nnamespace benchmark {\n// NOTE: only i386 and x86_64 have been well tested.\n// PPC, sparc, alpha, and ia64 are based on\n//    http://peter.kuscsik.com/wordpress/?p=14\n// with modifications by m3b.  See also\n//    https://setisvn.ssl.berkeley.edu/svn/lib/fftw-3.0.1/kernel/cycle.h\nnamespace cycleclock {\n// This should return the number of cycles since power-on.  Thread-safe.\ninline BENCHMARK_ALWAYS_INLINE int64_t Now() {\n#if defined(BENCHMARK_OS_MACOSX)\n  // this goes at the top because we need ALL Macs, regardless of\n  // architecture, to return the number of \"mach time units\" that\n  // have passed since startup.  See sysinfo.cc where\n  // InitializeSystemInfo() sets the supposed cpu clock frequency of\n  // macs to the number of mach time units per second, not actual\n  // CPU clock frequency (which can change in the face of CPU\n  // frequency scaling).  Also note that when the Mac sleeps, this\n  // counter pauses; it does not continue counting, nor does it\n  // reset to zero.\n  return mach_absolute_time();\n#elif defined(BENCHMARK_OS_EMSCRIPTEN)\n  // this goes above x86-specific code because old versions of Emscripten\n  // define __x86_64__, although they have nothing to do with it.\n  return static_cast<int64_t>(emscripten_get_now() * 1e+6);\n#elif defined(__i386__)\n  int64_t ret;\n  __asm__ volatile(\"rdtsc\" : \"=A\"(ret));\n  return ret;\n#elif defined(__x86_64__) || defined(__amd64__)\n  uint64_t low, high;\n  __asm__ volatile(\"rdtsc\" : \"=a\"(low), \"=d\"(high));\n  return (high << 32) | low;\n#elif defined(__powerpc__) || defined(__ppc__)\n  // This returns a time-base, which is not always precisely a cycle-count.\n#if defined(__powerpc64__) || defined(__ppc64__)\n  int64_t tb;\n  asm volatile(\"mfspr %0, 268\" : \"=r\"(tb));\n  return tb;\n#else\n  uint32_t tbl, tbu0, tbu1;\n  asm volatile(\n      \"mftbu %0\\n\"\n      \"mftb %1\\n\"\n      \"mftbu %2\"\n      : \"=r\"(tbu0), \"=r\"(tbl), \"=r\"(tbu1));\n  tbl &= -static_cast<int32_t>(tbu0 == tbu1);\n  // high 32 bits in tbu1; low 32 bits in tbl  (tbu0 is no longer needed)\n  return (static_cast<uint64_t>(tbu1) << 32) | tbl;\n#endif\n#elif defined(__sparc__)\n  int64_t tick;\n  asm(\".byte 0x83, 0x41, 0x00, 0x00\");\n  asm(\"mov   %%g1, %0\" : \"=r\"(tick));\n  return tick;\n#elif defined(__ia64__)\n  int64_t itc;\n  asm(\"mov %0 = ar.itc\" : \"=r\"(itc));\n  return itc;\n#elif defined(COMPILER_MSVC) && defined(_M_IX86)\n  // Older MSVC compilers (like 7.x) don't seem to support the\n  // __rdtsc intrinsic properly, so I prefer to use _asm instead\n  // when I know it will work.  Otherwise, I'll use __rdtsc and hope\n  // the code is being compiled with a non-ancient compiler.\n  _asm rdtsc\n#elif defined(COMPILER_MSVC) && (defined(_M_ARM64) || defined(_M_ARM64EC))\n  // See // https://docs.microsoft.com/en-us/cpp/intrinsics/arm64-intrinsics\n  // and https://reviews.llvm.org/D53115\n  int64_t virtual_timer_value;\n  virtual_timer_value = _ReadStatusReg(ARM64_CNTVCT);\n  return virtual_timer_value;\n#elif defined(COMPILER_MSVC)\n  return __rdtsc();\n#elif defined(BENCHMARK_OS_NACL)\n  // Native Client validator on x86/x86-64 allows RDTSC instructions,\n  // and this case is handled above. Native Client validator on ARM\n  // rejects MRC instructions (used in the ARM-specific sequence below),\n  // so we handle it here. Portable Native Client compiles to\n  // architecture-agnostic bytecode, which doesn't provide any\n  // cycle counter access mnemonics.\n\n  // Native Client does not provide any API to access cycle counter.\n  // Use clock_gettime(CLOCK_MONOTONIC, ...) instead of gettimeofday\n  // because is provides nanosecond resolution (which is noticeable at\n  // least for PNaCl modules running on x86 Mac & Linux).\n  // Initialize to always return 0 if clock_gettime fails.\n  struct timespec ts = {0, 0};\n  clock_gettime(CLOCK_MONOTONIC, &ts);\n  return static_cast<int64_t>(ts.tv_sec) * 1000000000 + ts.tv_nsec;\n#elif defined(__aarch64__)\n  // System timer of ARMv8 runs at a different frequency than the CPU's.\n  // The frequency is fixed, typically in the range 1-50MHz.  It can be\n  // read at CNTFRQ special register.  We assume the OS has set up\n  // the virtual timer properly.\n  int64_t virtual_timer_value;\n  asm volatile(\"mrs %0, cntvct_el0\" : \"=r\"(virtual_timer_value));\n  return virtual_timer_value;\n#elif defined(__ARM_ARCH)\n  // V6 is the earliest arch that has a standard cyclecount\n  // Native Client validator doesn't allow MRC instructions.\n#if (__ARM_ARCH >= 6)\n  uint32_t pmccntr;\n  uint32_t pmuseren;\n  uint32_t pmcntenset;\n  // Read the user mode perf monitor counter access permissions.\n  asm volatile(\"mrc p15, 0, %0, c9, c14, 0\" : \"=r\"(pmuseren));\n  if (pmuseren & 1) {  // Allows reading perfmon counters for user mode code.\n    asm volatile(\"mrc p15, 0, %0, c9, c12, 1\" : \"=r\"(pmcntenset));\n    if (pmcntenset & 0x80000000ul) {  // Is it counting?\n      asm volatile(\"mrc p15, 0, %0, c9, c13, 0\" : \"=r\"(pmccntr));\n      // The counter is set up to count every 64th cycle\n      return static_cast<int64_t>(pmccntr) * 64;  // Should optimize to << 6\n    }\n  }\n#endif\n  struct timeval tv;\n  gettimeofday(&tv, nullptr);\n  return static_cast<int64_t>(tv.tv_sec) * 1000000 + tv.tv_usec;\n#elif defined(__mips__) || defined(__m68k__)\n  // mips apparently only allows rdtsc for superusers, so we fall\n  // back to gettimeofday.  It's possible clock_gettime would be better.\n  struct timeval tv;\n  gettimeofday(&tv, nullptr);\n  return static_cast<int64_t>(tv.tv_sec) * 1000000 + tv.tv_usec;\n#elif defined(__loongarch__) || defined(__csky__)\n  struct timeval tv;\n  gettimeofday(&tv, nullptr);\n  return static_cast<int64_t>(tv.tv_sec) * 1000000 + tv.tv_usec;\n#elif defined(__s390__)  // Covers both s390 and s390x.\n  // Return the CPU clock.\n  uint64_t tsc;\n#if defined(BENCHMARK_OS_ZOS) && defined(COMPILER_IBMXL)\n  // z/OS XL compiler HLASM syntax.\n  asm(\" stck %0\" : \"=m\"(tsc) : : \"cc\");\n#else\n  asm(\"stck %0\" : \"=Q\"(tsc) : : \"cc\");\n#endif\n  return tsc;\n#elif defined(__riscv)  // RISC-V\n  // Use RDCYCLE (and RDCYCLEH on riscv32)\n#if __riscv_xlen == 32\n  uint32_t cycles_lo, cycles_hi0, cycles_hi1;\n  // This asm also includes the PowerPC overflow handling strategy, as above.\n  // Implemented in assembly because Clang insisted on branching.\n  asm volatile(\n      \"rdcycleh %0\\n\"\n      \"rdcycle %1\\n\"\n      \"rdcycleh %2\\n\"\n      \"sub %0, %0, %2\\n\"\n      \"seqz %0, %0\\n\"\n      \"sub %0, zero, %0\\n\"\n      \"and %1, %1, %0\\n\"\n      : \"=r\"(cycles_hi0), \"=r\"(cycles_lo), \"=r\"(cycles_hi1));\n  return (static_cast<uint64_t>(cycles_hi1) << 32) | cycles_lo;\n#else\n  uint64_t cycles;\n  asm volatile(\"rdcycle %0\" : \"=r\"(cycles));\n  return cycles;\n#endif\n#elif defined(__e2k__) || defined(__elbrus__)\n  struct timeval tv;\n  gettimeofday(&tv, nullptr);\n  return static_cast<int64_t>(tv.tv_sec) * 1000000 + tv.tv_usec;\n#elif defined(__hexagon__)\n  uint64_t pcycle;\n  asm volatile(\"%0 = C15:14\" : \"=r\"(pcycle));\n  return static_cast<double>(pcycle);\n#else\n// The soft failover to a generic implementation is automatic only for ARM.\n// For other platforms the developer is expected to make an attempt to create\n// a fast implementation and use generic version if nothing better is available.\n#error You need to define CycleTimer for your OS and CPU\n#endif\n}\n}  // end namespace cycleclock\n}  // end namespace benchmark\n\n#endif  // BENCHMARK_CYCLECLOCK_H_\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/internal_macros.h",
    "content": "#ifndef BENCHMARK_INTERNAL_MACROS_H_\n#define BENCHMARK_INTERNAL_MACROS_H_\n\n/* Needed to detect STL */\n#include <cstdlib>\n\n// clang-format off\n\n#ifndef __has_feature\n#define __has_feature(x) 0\n#endif\n\n#if defined(__clang__)\n  #if defined(__ibmxl__)\n    #if !defined(COMPILER_IBMXL)\n      #define COMPILER_IBMXL\n    #endif\n  #elif !defined(COMPILER_CLANG)\n    #define COMPILER_CLANG\n  #endif\n#elif defined(_MSC_VER)\n  #if !defined(COMPILER_MSVC)\n    #define COMPILER_MSVC\n  #endif\n#elif defined(__GNUC__)\n  #if !defined(COMPILER_GCC)\n    #define COMPILER_GCC\n  #endif\n#endif\n\n#if __has_feature(cxx_attributes)\n  #define BENCHMARK_NORETURN [[noreturn]]\n#elif defined(__GNUC__)\n  #define BENCHMARK_NORETURN __attribute__((noreturn))\n#elif defined(COMPILER_MSVC)\n  #define BENCHMARK_NORETURN __declspec(noreturn)\n#else\n  #define BENCHMARK_NORETURN\n#endif\n\n#if defined(__CYGWIN__)\n  #define BENCHMARK_OS_CYGWIN 1\n#elif defined(_WIN32)\n  #define BENCHMARK_OS_WINDOWS 1\n  // WINAPI_FAMILY_PARTITION is defined in winapifamily.h.\n  // We include windows.h which implicitly includes winapifamily.h for compatibility.\n  #ifndef NOMINMAX\n    #define NOMINMAX\n  #endif\n  #include <windows.h>\n  #if defined(WINAPI_FAMILY_PARTITION)\n    #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)\n      #define BENCHMARK_OS_WINDOWS_WIN32 1\n    #elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)\n      #define BENCHMARK_OS_WINDOWS_RT 1\n    #endif\n  #endif\n  #if defined(__MINGW32__)\n    #define BENCHMARK_OS_MINGW 1\n  #endif\n#elif defined(__APPLE__)\n  #define BENCHMARK_OS_APPLE 1\n  #include \"TargetConditionals.h\"\n  #if defined(TARGET_OS_MAC)\n    #define BENCHMARK_OS_MACOSX 1\n    #if defined(TARGET_OS_IPHONE)\n      #define BENCHMARK_OS_IOS 1\n    #endif\n  #endif\n#elif defined(__FreeBSD__)\n  #define BENCHMARK_OS_FREEBSD 1\n#elif defined(__NetBSD__)\n  #define BENCHMARK_OS_NETBSD 1\n#elif defined(__OpenBSD__)\n  #define BENCHMARK_OS_OPENBSD 1\n#elif defined(__DragonFly__)\n  #define BENCHMARK_OS_DRAGONFLY 1\n#elif defined(__linux__)\n  #define BENCHMARK_OS_LINUX 1\n#elif defined(__native_client__)\n  #define BENCHMARK_OS_NACL 1\n#elif defined(__EMSCRIPTEN__)\n  #define BENCHMARK_OS_EMSCRIPTEN 1\n#elif defined(__rtems__)\n  #define BENCHMARK_OS_RTEMS 1\n#elif defined(__Fuchsia__)\n#define BENCHMARK_OS_FUCHSIA 1\n#elif defined (__SVR4) && defined (__sun)\n#define BENCHMARK_OS_SOLARIS 1\n#elif defined(__QNX__)\n#define BENCHMARK_OS_QNX 1\n#elif defined(__MVS__)\n#define BENCHMARK_OS_ZOS 1\n#elif defined(__hexagon__)\n#define BENCHMARK_OS_QURT 1\n#endif\n\n#if defined(__ANDROID__) && defined(__GLIBCXX__)\n#define BENCHMARK_STL_ANDROID_GNUSTL 1\n#endif\n\n#if !__has_feature(cxx_exceptions) && !defined(__cpp_exceptions) \\\n     && !defined(__EXCEPTIONS)\n  #define BENCHMARK_HAS_NO_EXCEPTIONS\n#endif\n\n#if defined(COMPILER_CLANG) || defined(COMPILER_GCC)\n  #define BENCHMARK_MAYBE_UNUSED __attribute__((unused))\n#else\n  #define BENCHMARK_MAYBE_UNUSED\n#endif\n\n// clang-format on\n\n#endif  // BENCHMARK_INTERNAL_MACROS_H_\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/json_reporter.cc",
    "content": "// Copyright 2015 Google Inc. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include <algorithm>\n#include <cmath>\n#include <cstdint>\n#include <iomanip>  // for setprecision\n#include <iostream>\n#include <limits>\n#include <string>\n#include <tuple>\n#include <vector>\n\n#include \"benchmark/benchmark.h\"\n#include \"complexity.h\"\n#include \"string_util.h\"\n#include \"timers.h\"\n\nnamespace benchmark {\nnamespace {\n\nstd::string StrEscape(const std::string& s) {\n  std::string tmp;\n  tmp.reserve(s.size());\n  for (char c : s) {\n    switch (c) {\n      case '\\b':\n        tmp += \"\\\\b\";\n        break;\n      case '\\f':\n        tmp += \"\\\\f\";\n        break;\n      case '\\n':\n        tmp += \"\\\\n\";\n        break;\n      case '\\r':\n        tmp += \"\\\\r\";\n        break;\n      case '\\t':\n        tmp += \"\\\\t\";\n        break;\n      case '\\\\':\n        tmp += \"\\\\\\\\\";\n        break;\n      case '\"':\n        tmp += \"\\\\\\\"\";\n        break;\n      default:\n        tmp += c;\n        break;\n    }\n  }\n  return tmp;\n}\n\nstd::string FormatKV(std::string const& key, std::string const& value) {\n  return StrFormat(\"\\\"%s\\\": \\\"%s\\\"\", StrEscape(key).c_str(),\n                   StrEscape(value).c_str());\n}\n\nstd::string FormatKV(std::string const& key, const char* value) {\n  return StrFormat(\"\\\"%s\\\": \\\"%s\\\"\", StrEscape(key).c_str(),\n                   StrEscape(value).c_str());\n}\n\nstd::string FormatKV(std::string const& key, bool value) {\n  return StrFormat(\"\\\"%s\\\": %s\", StrEscape(key).c_str(),\n                   value ? \"true\" : \"false\");\n}\n\nstd::string FormatKV(std::string const& key, int64_t value) {\n  std::stringstream ss;\n  ss << '\"' << StrEscape(key) << \"\\\": \" << value;\n  return ss.str();\n}\n\nstd::string FormatKV(std::string const& key, double value) {\n  std::stringstream ss;\n  ss << '\"' << StrEscape(key) << \"\\\": \";\n\n  if (std::isnan(value))\n    ss << (value < 0 ? \"-\" : \"\") << \"NaN\";\n  else if (std::isinf(value))\n    ss << (value < 0 ? \"-\" : \"\") << \"Infinity\";\n  else {\n    const auto max_digits10 =\n        std::numeric_limits<decltype(value)>::max_digits10;\n    const auto max_fractional_digits10 = max_digits10 - 1;\n    ss << std::scientific << std::setprecision(max_fractional_digits10)\n       << value;\n  }\n  return ss.str();\n}\n\nint64_t RoundDouble(double v) { return std::lround(v); }\n\n}  // end namespace\n\nbool JSONReporter::ReportContext(const Context& context) {\n  std::ostream& out = GetOutputStream();\n\n  out << \"{\\n\";\n  std::string inner_indent(2, ' ');\n\n  // Open context block and print context information.\n  out << inner_indent << \"\\\"context\\\": {\\n\";\n  std::string indent(4, ' ');\n\n  std::string walltime_value = LocalDateTimeString();\n  out << indent << FormatKV(\"date\", walltime_value) << \",\\n\";\n\n  out << indent << FormatKV(\"host_name\", context.sys_info.name) << \",\\n\";\n\n  if (Context::executable_name) {\n    out << indent << FormatKV(\"executable\", Context::executable_name) << \",\\n\";\n  }\n\n  CPUInfo const& info = context.cpu_info;\n  out << indent << FormatKV(\"num_cpus\", static_cast<int64_t>(info.num_cpus))\n      << \",\\n\";\n  out << indent\n      << FormatKV(\"mhz_per_cpu\",\n                  RoundDouble(info.cycles_per_second / 1000000.0))\n      << \",\\n\";\n  if (CPUInfo::Scaling::UNKNOWN != info.scaling) {\n    out << indent\n        << FormatKV(\"cpu_scaling_enabled\",\n                    info.scaling == CPUInfo::Scaling::ENABLED ? true : false)\n        << \",\\n\";\n  }\n\n  out << indent << \"\\\"caches\\\": [\\n\";\n  indent = std::string(6, ' ');\n  std::string cache_indent(8, ' ');\n  for (size_t i = 0; i < info.caches.size(); ++i) {\n    auto& CI = info.caches[i];\n    out << indent << \"{\\n\";\n    out << cache_indent << FormatKV(\"type\", CI.type) << \",\\n\";\n    out << cache_indent << FormatKV(\"level\", static_cast<int64_t>(CI.level))\n        << \",\\n\";\n    out << cache_indent << FormatKV(\"size\", static_cast<int64_t>(CI.size))\n        << \",\\n\";\n    out << cache_indent\n        << FormatKV(\"num_sharing\", static_cast<int64_t>(CI.num_sharing))\n        << \"\\n\";\n    out << indent << \"}\";\n    if (i != info.caches.size() - 1) out << \",\";\n    out << \"\\n\";\n  }\n  indent = std::string(4, ' ');\n  out << indent << \"],\\n\";\n  out << indent << \"\\\"load_avg\\\": [\";\n  for (auto it = info.load_avg.begin(); it != info.load_avg.end();) {\n    out << *it++;\n    if (it != info.load_avg.end()) out << \",\";\n  }\n  out << \"],\\n\";\n\n#if defined(NDEBUG)\n  const char build_type[] = \"release\";\n#else\n  const char build_type[] = \"debug\";\n#endif\n  out << indent << FormatKV(\"library_build_type\", build_type);\n\n  std::map<std::string, std::string>* global_context =\n      internal::GetGlobalContext();\n\n  if (global_context != nullptr) {\n    for (const auto& kv : *global_context) {\n      out << \",\\n\";\n      out << indent << FormatKV(kv.first, kv.second);\n    }\n  }\n  out << \"\\n\";\n\n  // Close context block and open the list of benchmarks.\n  out << inner_indent << \"},\\n\";\n  out << inner_indent << \"\\\"benchmarks\\\": [\\n\";\n  return true;\n}\n\nvoid JSONReporter::ReportRuns(std::vector<Run> const& reports) {\n  if (reports.empty()) {\n    return;\n  }\n  std::string indent(4, ' ');\n  std::ostream& out = GetOutputStream();\n  if (!first_report_) {\n    out << \",\\n\";\n  }\n  first_report_ = false;\n\n  for (auto it = reports.begin(); it != reports.end(); ++it) {\n    out << indent << \"{\\n\";\n    PrintRunData(*it);\n    out << indent << '}';\n    auto it_cp = it;\n    if (++it_cp != reports.end()) {\n      out << \",\\n\";\n    }\n  }\n}\n\nvoid JSONReporter::Finalize() {\n  // Close the list of benchmarks and the top level object.\n  GetOutputStream() << \"\\n  ]\\n}\\n\";\n}\n\nvoid JSONReporter::PrintRunData(Run const& run) {\n  std::string indent(6, ' ');\n  std::ostream& out = GetOutputStream();\n  out << indent << FormatKV(\"name\", run.benchmark_name()) << \",\\n\";\n  out << indent << FormatKV(\"family_index\", run.family_index) << \",\\n\";\n  out << indent\n      << FormatKV(\"per_family_instance_index\", run.per_family_instance_index)\n      << \",\\n\";\n  out << indent << FormatKV(\"run_name\", run.run_name.str()) << \",\\n\";\n  out << indent << FormatKV(\"run_type\", [&run]() -> const char* {\n    switch (run.run_type) {\n      case BenchmarkReporter::Run::RT_Iteration:\n        return \"iteration\";\n      case BenchmarkReporter::Run::RT_Aggregate:\n        return \"aggregate\";\n    }\n    BENCHMARK_UNREACHABLE();\n  }()) << \",\\n\";\n  out << indent << FormatKV(\"repetitions\", run.repetitions) << \",\\n\";\n  if (run.run_type != BenchmarkReporter::Run::RT_Aggregate) {\n    out << indent << FormatKV(\"repetition_index\", run.repetition_index)\n        << \",\\n\";\n  }\n  out << indent << FormatKV(\"threads\", run.threads) << \",\\n\";\n  if (run.run_type == BenchmarkReporter::Run::RT_Aggregate) {\n    out << indent << FormatKV(\"aggregate_name\", run.aggregate_name) << \",\\n\";\n    out << indent << FormatKV(\"aggregate_unit\", [&run]() -> const char* {\n      switch (run.aggregate_unit) {\n        case StatisticUnit::kTime:\n          return \"time\";\n        case StatisticUnit::kPercentage:\n          return \"percentage\";\n      }\n      BENCHMARK_UNREACHABLE();\n    }()) << \",\\n\";\n  }\n  if (internal::SkippedWithError == run.skipped) {\n    out << indent << FormatKV(\"error_occurred\", true) << \",\\n\";\n    out << indent << FormatKV(\"error_message\", run.skip_message) << \",\\n\";\n  } else if (internal::SkippedWithMessage == run.skipped) {\n    out << indent << FormatKV(\"skipped\", true) << \",\\n\";\n    out << indent << FormatKV(\"skip_message\", run.skip_message) << \",\\n\";\n  }\n  if (!run.report_big_o && !run.report_rms) {\n    out << indent << FormatKV(\"iterations\", run.iterations) << \",\\n\";\n    if (run.run_type != Run::RT_Aggregate ||\n        run.aggregate_unit == StatisticUnit::kTime) {\n      out << indent << FormatKV(\"real_time\", run.GetAdjustedRealTime())\n          << \",\\n\";\n      out << indent << FormatKV(\"cpu_time\", run.GetAdjustedCPUTime());\n    } else {\n      assert(run.aggregate_unit == StatisticUnit::kPercentage);\n      out << indent << FormatKV(\"real_time\", run.real_accumulated_time)\n          << \",\\n\";\n      out << indent << FormatKV(\"cpu_time\", run.cpu_accumulated_time);\n    }\n    out << \",\\n\"\n        << indent << FormatKV(\"time_unit\", GetTimeUnitString(run.time_unit));\n  } else if (run.report_big_o) {\n    out << indent << FormatKV(\"cpu_coefficient\", run.GetAdjustedCPUTime())\n        << \",\\n\";\n    out << indent << FormatKV(\"real_coefficient\", run.GetAdjustedRealTime())\n        << \",\\n\";\n    out << indent << FormatKV(\"big_o\", GetBigOString(run.complexity)) << \",\\n\";\n    out << indent << FormatKV(\"time_unit\", GetTimeUnitString(run.time_unit));\n  } else if (run.report_rms) {\n    out << indent << FormatKV(\"rms\", run.GetAdjustedCPUTime());\n  }\n\n  for (auto& c : run.counters) {\n    out << \",\\n\" << indent << FormatKV(c.first, c.second);\n  }\n\n  if (run.memory_result) {\n    const MemoryManager::Result memory_result = *run.memory_result;\n    out << \",\\n\" << indent << FormatKV(\"allocs_per_iter\", run.allocs_per_iter);\n    out << \",\\n\"\n        << indent << FormatKV(\"max_bytes_used\", memory_result.max_bytes_used);\n\n    auto report_if_present = [&out, &indent](const std::string& label,\n                                             int64_t val) {\n      if (val != MemoryManager::TombstoneValue)\n        out << \",\\n\" << indent << FormatKV(label, val);\n    };\n\n    report_if_present(\"total_allocated_bytes\",\n                      memory_result.total_allocated_bytes);\n    report_if_present(\"net_heap_growth\", memory_result.net_heap_growth);\n  }\n\n  if (!run.report_label.empty()) {\n    out << \",\\n\" << indent << FormatKV(\"label\", run.report_label);\n  }\n  out << '\\n';\n}\n\nconst int64_t MemoryManager::TombstoneValue =\n    std::numeric_limits<int64_t>::max();\n\n}  // end namespace benchmark\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/log.h",
    "content": "#ifndef BENCHMARK_LOG_H_\n#define BENCHMARK_LOG_H_\n\n#include <iostream>\n#include <ostream>\n\n// NOTE: this is also defined in benchmark.h but we're trying to avoid a\n// dependency.\n// The _MSVC_LANG check should detect Visual Studio 2015 Update 3 and newer.\n#if __cplusplus >= 201103L || (defined(_MSVC_LANG) && _MSVC_LANG >= 201103L)\n#define BENCHMARK_HAS_CXX11\n#endif\n\nnamespace benchmark {\nnamespace internal {\n\ntypedef std::basic_ostream<char>&(EndLType)(std::basic_ostream<char>&);\n\nclass LogType {\n  friend LogType& GetNullLogInstance();\n  friend LogType& GetErrorLogInstance();\n\n  // FIXME: Add locking to output.\n  template <class Tp>\n  friend LogType& operator<<(LogType&, Tp const&);\n  friend LogType& operator<<(LogType&, EndLType*);\n\n private:\n  LogType(std::ostream* out) : out_(out) {}\n  std::ostream* out_;\n\n  // NOTE: we could use BENCHMARK_DISALLOW_COPY_AND_ASSIGN but we shouldn't have\n  // a dependency on benchmark.h from here.\n#ifndef BENCHMARK_HAS_CXX11\n  LogType(const LogType&);\n  LogType& operator=(const LogType&);\n#else\n  LogType(const LogType&) = delete;\n  LogType& operator=(const LogType&) = delete;\n#endif\n};\n\ntemplate <class Tp>\nLogType& operator<<(LogType& log, Tp const& value) {\n  if (log.out_) {\n    *log.out_ << value;\n  }\n  return log;\n}\n\ninline LogType& operator<<(LogType& log, EndLType* m) {\n  if (log.out_) {\n    *log.out_ << m;\n  }\n  return log;\n}\n\ninline int& LogLevel() {\n  static int log_level = 0;\n  return log_level;\n}\n\ninline LogType& GetNullLogInstance() {\n  static LogType null_log(static_cast<std::ostream*>(nullptr));\n  return null_log;\n}\n\ninline LogType& GetErrorLogInstance() {\n  static LogType error_log(&std::clog);\n  return error_log;\n}\n\ninline LogType& GetLogInstanceForLevel(int level) {\n  if (level <= LogLevel()) {\n    return GetErrorLogInstance();\n  }\n  return GetNullLogInstance();\n}\n\n}  // end namespace internal\n}  // end namespace benchmark\n\n// clang-format off\n#define BM_VLOG(x)                                                               \\\n  (::benchmark::internal::GetLogInstanceForLevel(x) << \"-- LOG(\" << x << \"):\" \\\n                                                                         \" \")\n// clang-format on\n#endif\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/mutex.h",
    "content": "#ifndef BENCHMARK_MUTEX_H_\n#define BENCHMARK_MUTEX_H_\n\n#include <condition_variable>\n#include <mutex>\n\n#include \"check.h\"\n\n// Enable thread safety attributes only with clang.\n// The attributes can be safely erased when compiling with other compilers.\n#if defined(HAVE_THREAD_SAFETY_ATTRIBUTES)\n#define THREAD_ANNOTATION_ATTRIBUTE_(x) __attribute__((x))\n#else\n#define THREAD_ANNOTATION_ATTRIBUTE_(x)  // no-op\n#endif\n\n#define CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE_(capability(x))\n\n#define SCOPED_CAPABILITY THREAD_ANNOTATION_ATTRIBUTE_(scoped_lockable)\n\n#define GUARDED_BY(x) THREAD_ANNOTATION_ATTRIBUTE_(guarded_by(x))\n\n#define PT_GUARDED_BY(x) THREAD_ANNOTATION_ATTRIBUTE_(pt_guarded_by(x))\n\n#define ACQUIRED_BEFORE(...) \\\n  THREAD_ANNOTATION_ATTRIBUTE_(acquired_before(__VA_ARGS__))\n\n#define ACQUIRED_AFTER(...) \\\n  THREAD_ANNOTATION_ATTRIBUTE_(acquired_after(__VA_ARGS__))\n\n#define REQUIRES(...) \\\n  THREAD_ANNOTATION_ATTRIBUTE_(requires_capability(__VA_ARGS__))\n\n#define REQUIRES_SHARED(...) \\\n  THREAD_ANNOTATION_ATTRIBUTE_(requires_shared_capability(__VA_ARGS__))\n\n#define ACQUIRE(...) \\\n  THREAD_ANNOTATION_ATTRIBUTE_(acquire_capability(__VA_ARGS__))\n\n#define ACQUIRE_SHARED(...) \\\n  THREAD_ANNOTATION_ATTRIBUTE_(acquire_shared_capability(__VA_ARGS__))\n\n#define RELEASE(...) \\\n  THREAD_ANNOTATION_ATTRIBUTE_(release_capability(__VA_ARGS__))\n\n#define RELEASE_SHARED(...) \\\n  THREAD_ANNOTATION_ATTRIBUTE_(release_shared_capability(__VA_ARGS__))\n\n#define TRY_ACQUIRE(...) \\\n  THREAD_ANNOTATION_ATTRIBUTE_(try_acquire_capability(__VA_ARGS__))\n\n#define TRY_ACQUIRE_SHARED(...) \\\n  THREAD_ANNOTATION_ATTRIBUTE_(try_acquire_shared_capability(__VA_ARGS__))\n\n#define EXCLUDES(...) THREAD_ANNOTATION_ATTRIBUTE_(locks_excluded(__VA_ARGS__))\n\n#define ASSERT_CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE_(assert_capability(x))\n\n#define ASSERT_SHARED_CAPABILITY(x) \\\n  THREAD_ANNOTATION_ATTRIBUTE_(assert_shared_capability(x))\n\n#define RETURN_CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE_(lock_returned(x))\n\n#define NO_THREAD_SAFETY_ANALYSIS \\\n  THREAD_ANNOTATION_ATTRIBUTE_(no_thread_safety_analysis)\n\nnamespace benchmark {\n\ntypedef std::condition_variable Condition;\n\n// NOTE: Wrappers for std::mutex and std::unique_lock are provided so that\n// we can annotate them with thread safety attributes and use the\n// -Wthread-safety warning with clang. The standard library types cannot be\n// used directly because they do not provide the required annotations.\nclass CAPABILITY(\"mutex\") Mutex {\n public:\n  Mutex() {}\n\n  void lock() ACQUIRE() { mut_.lock(); }\n  void unlock() RELEASE() { mut_.unlock(); }\n  std::mutex& native_handle() { return mut_; }\n\n private:\n  std::mutex mut_;\n};\n\nclass SCOPED_CAPABILITY MutexLock {\n  typedef std::unique_lock<std::mutex> MutexLockImp;\n\n public:\n  MutexLock(Mutex& m) ACQUIRE(m) : ml_(m.native_handle()) {}\n  ~MutexLock() RELEASE() {}\n  MutexLockImp& native_handle() { return ml_; }\n\n private:\n  MutexLockImp ml_;\n};\n\nclass Barrier {\n public:\n  Barrier(int num_threads) : running_threads_(num_threads) {}\n\n  // Called by each thread\n  bool wait() EXCLUDES(lock_) {\n    bool last_thread = false;\n    {\n      MutexLock ml(lock_);\n      last_thread = createBarrier(ml);\n    }\n    if (last_thread) phase_condition_.notify_all();\n    return last_thread;\n  }\n\n  void removeThread() EXCLUDES(lock_) {\n    MutexLock ml(lock_);\n    --running_threads_;\n    if (entered_ != 0) phase_condition_.notify_all();\n  }\n\n private:\n  Mutex lock_;\n  Condition phase_condition_;\n  int running_threads_;\n\n  // State for barrier management\n  int phase_number_ = 0;\n  int entered_ = 0;  // Number of threads that have entered this barrier\n\n  // Enter the barrier and wait until all other threads have also\n  // entered the barrier.  Returns iff this is the last thread to\n  // enter the barrier.\n  bool createBarrier(MutexLock& ml) REQUIRES(lock_) {\n    BM_CHECK_LT(entered_, running_threads_);\n    entered_++;\n    if (entered_ < running_threads_) {\n      // Wait for all threads to enter\n      int phase_number_cp = phase_number_;\n      auto cb = [this, phase_number_cp]() {\n        return this->phase_number_ > phase_number_cp ||\n               entered_ == running_threads_;  // A thread has aborted in error\n      };\n      phase_condition_.wait(ml.native_handle(), cb);\n      if (phase_number_ > phase_number_cp) return false;\n      // else (running_threads_ == entered_) and we are the last thread.\n    }\n    // Last thread has reached the barrier\n    phase_number_++;\n    entered_ = 0;\n    return true;\n  }\n};\n\n}  // end namespace benchmark\n\n#endif  // BENCHMARK_MUTEX_H_\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/perf_counters.cc",
    "content": "// Copyright 2021 Google Inc. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"perf_counters.h\"\n\n#include <cstring>\n#include <memory>\n#include <vector>\n\n#if defined HAVE_LIBPFM\n#include \"perfmon/pfmlib.h\"\n#include \"perfmon/pfmlib_perf_event.h\"\n#endif\n\nnamespace benchmark {\nnamespace internal {\n\nconstexpr size_t PerfCounterValues::kMaxCounters;\n\n#if defined HAVE_LIBPFM\n\nsize_t PerfCounterValues::Read(const std::vector<int>& leaders) {\n  // Create a pointer for multiple reads\n  const size_t bufsize = values_.size() * sizeof(values_[0]);\n  char* ptr = reinterpret_cast<char*>(values_.data());\n  size_t size = bufsize;\n  for (int lead : leaders) {\n    auto read_bytes = ::read(lead, ptr, size);\n    if (read_bytes >= ssize_t(sizeof(uint64_t))) {\n      // Actual data bytes are all bytes minus initial padding\n      std::size_t data_bytes = read_bytes - sizeof(uint64_t);\n      // This should be very cheap since it's in hot cache\n      std::memmove(ptr, ptr + sizeof(uint64_t), data_bytes);\n      // Increment our counters\n      ptr += data_bytes;\n      size -= data_bytes;\n    } else {\n      int err = errno;\n      GetErrorLogInstance() << \"Error reading lead \" << lead << \" errno:\" << err\n                            << \" \" << ::strerror(err) << \"\\n\";\n      return 0;\n    }\n  }\n  return (bufsize - size) / sizeof(uint64_t);\n}\n\nconst bool PerfCounters::kSupported = true;\n\nbool PerfCounters::Initialize() { return pfm_initialize() == PFM_SUCCESS; }\n\nbool PerfCounters::IsCounterSupported(const std::string& name) {\n  perf_event_attr_t attr;\n  std::memset(&attr, 0, sizeof(attr));\n  pfm_perf_encode_arg_t arg;\n  std::memset(&arg, 0, sizeof(arg));\n  arg.attr = &attr;\n  const int mode = PFM_PLM3;  // user mode only\n  int ret = pfm_get_os_event_encoding(name.c_str(), mode, PFM_OS_PERF_EVENT_EXT,\n                                      &arg);\n  return (ret == PFM_SUCCESS);\n}\n\nPerfCounters PerfCounters::Create(\n    const std::vector<std::string>& counter_names) {\n  // Valid counters will populate these arrays but we start empty\n  std::vector<std::string> valid_names;\n  std::vector<int> counter_ids;\n  std::vector<int> leader_ids;\n\n  // Resize to the maximum possible\n  valid_names.reserve(counter_names.size());\n  counter_ids.reserve(counter_names.size());\n\n  const int kCounterMode = PFM_PLM3;  // user mode only\n\n  // Group leads will be assigned on demand. The idea is that once we cannot\n  // create a counter descriptor, the reason is that this group has maxed out\n  // so we set the group_id again to -1 and retry - giving the algorithm a\n  // chance to create a new group leader to hold the next set of counters.\n  int group_id = -1;\n\n  // Loop through all performance counters\n  for (size_t i = 0; i < counter_names.size(); ++i) {\n    // we are about to push into the valid names vector\n    // check if we did not reach the maximum\n    if (valid_names.size() == PerfCounterValues::kMaxCounters) {\n      // Log a message if we maxed out and stop adding\n      GetErrorLogInstance()\n          << counter_names.size() << \" counters were requested. The maximum is \"\n          << PerfCounterValues::kMaxCounters << \" and \" << valid_names.size()\n          << \" were already added. All remaining counters will be ignored\\n\";\n      // stop the loop and return what we have already\n      break;\n    }\n\n    // Check if this name is empty\n    const auto& name = counter_names[i];\n    if (name.empty()) {\n      GetErrorLogInstance()\n          << \"A performance counter name was the empty string\\n\";\n      continue;\n    }\n\n    // Here first means first in group, ie the group leader\n    const bool is_first = (group_id < 0);\n\n    // This struct will be populated by libpfm from the counter string\n    // and then fed into the syscall perf_event_open\n    struct perf_event_attr attr {};\n    attr.size = sizeof(attr);\n\n    // This is the input struct to libpfm.\n    pfm_perf_encode_arg_t arg{};\n    arg.attr = &attr;\n    const int pfm_get = pfm_get_os_event_encoding(name.c_str(), kCounterMode,\n                                                  PFM_OS_PERF_EVENT, &arg);\n    if (pfm_get != PFM_SUCCESS) {\n      GetErrorLogInstance()\n          << \"Unknown performance counter name: \" << name << \"\\n\";\n      continue;\n    }\n\n    // We then proceed to populate the remaining fields in our attribute struct\n    // Note: the man page for perf_event_create suggests inherit = true and\n    // read_format = PERF_FORMAT_GROUP don't work together, but that's not the\n    // case.\n    attr.disabled = is_first;\n    attr.inherit = true;\n    attr.pinned = is_first;\n    attr.exclude_kernel = true;\n    attr.exclude_user = false;\n    attr.exclude_hv = true;\n\n    // Read all counters in a group in one read.\n    attr.read_format = PERF_FORMAT_GROUP;\n\n    int id = -1;\n    while (id < 0) {\n      static constexpr size_t kNrOfSyscallRetries = 5;\n      // Retry syscall as it was interrupted often (b/64774091).\n      for (size_t num_retries = 0; num_retries < kNrOfSyscallRetries;\n           ++num_retries) {\n        id = perf_event_open(&attr, 0, -1, group_id, 0);\n        if (id >= 0 || errno != EINTR) {\n          break;\n        }\n      }\n      if (id < 0) {\n        // If the file descriptor is negative we might have reached a limit\n        // in the current group. Set the group_id to -1 and retry\n        if (group_id >= 0) {\n          // Create a new group\n          group_id = -1;\n        } else {\n          // At this point we have already retried to set a new group id and\n          // failed. We then give up.\n          break;\n        }\n      }\n    }\n\n    // We failed to get a new file descriptor. We might have reached a hard\n    // hardware limit that cannot be resolved even with group multiplexing\n    if (id < 0) {\n      GetErrorLogInstance() << \"***WARNING** Failed to get a file descriptor \"\n                               \"for performance counter \"\n                            << name << \". Ignoring\\n\";\n\n      // We give up on this counter but try to keep going\n      // as the others would be fine\n      continue;\n    }\n    if (group_id < 0) {\n      // This is a leader, store and assign it to the current file descriptor\n      leader_ids.push_back(id);\n      group_id = id;\n    }\n    // This is a valid counter, add it to our descriptor's list\n    counter_ids.push_back(id);\n    valid_names.push_back(name);\n  }\n\n  // Loop through all group leaders activating them\n  // There is another option of starting ALL counters in a process but\n  // that would be far reaching an intrusion. If the user is using PMCs\n  // by themselves then this would have a side effect on them. It is\n  // friendlier to loop through all groups individually.\n  for (int lead : leader_ids) {\n    if (ioctl(lead, PERF_EVENT_IOC_ENABLE) != 0) {\n      // This should never happen but if it does, we give up on the\n      // entire batch as recovery would be a mess.\n      GetErrorLogInstance() << \"***WARNING*** Failed to start counters. \"\n                               \"Claring out all counters.\\n\";\n\n      // Close all peformance counters\n      for (int id : counter_ids) {\n        ::close(id);\n      }\n\n      // Return an empty object so our internal state is still good and\n      // the process can continue normally without impact\n      return NoCounters();\n    }\n  }\n\n  return PerfCounters(std::move(valid_names), std::move(counter_ids),\n                      std::move(leader_ids));\n}\n\nvoid PerfCounters::CloseCounters() const {\n  if (counter_ids_.empty()) {\n    return;\n  }\n  for (int lead : leader_ids_) {\n    ioctl(lead, PERF_EVENT_IOC_DISABLE);\n  }\n  for (int fd : counter_ids_) {\n    close(fd);\n  }\n}\n#else   // defined HAVE_LIBPFM\nsize_t PerfCounterValues::Read(const std::vector<int>&) { return 0; }\n\nconst bool PerfCounters::kSupported = false;\n\nbool PerfCounters::Initialize() { return false; }\n\nbool PerfCounters::IsCounterSupported(const std::string&) { return false; }\n\nPerfCounters PerfCounters::Create(\n    const std::vector<std::string>& counter_names) {\n  if (!counter_names.empty()) {\n    GetErrorLogInstance() << \"Performance counters not supported.\";\n  }\n  return NoCounters();\n}\n\nvoid PerfCounters::CloseCounters() const {}\n#endif  // defined HAVE_LIBPFM\n\nPerfCountersMeasurement::PerfCountersMeasurement(\n    const std::vector<std::string>& counter_names)\n    : start_values_(counter_names.size()), end_values_(counter_names.size()) {\n  counters_ = PerfCounters::Create(counter_names);\n}\n\nPerfCounters& PerfCounters::operator=(PerfCounters&& other) noexcept {\n  if (this != &other) {\n    CloseCounters();\n\n    counter_ids_ = std::move(other.counter_ids_);\n    leader_ids_ = std::move(other.leader_ids_);\n    counter_names_ = std::move(other.counter_names_);\n  }\n  return *this;\n}\n}  // namespace internal\n}  // namespace benchmark\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/perf_counters.h",
    "content": "// Copyright 2021 Google Inc. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef BENCHMARK_PERF_COUNTERS_H\n#define BENCHMARK_PERF_COUNTERS_H\n\n#include <array>\n#include <cstdint>\n#include <cstring>\n#include <memory>\n#include <vector>\n\n#include \"benchmark/benchmark.h\"\n#include \"check.h\"\n#include \"log.h\"\n#include \"mutex.h\"\n\n#ifndef BENCHMARK_OS_WINDOWS\n#include <unistd.h>\n#endif\n\n#if defined(_MSC_VER)\n#pragma warning(push)\n// C4251: <symbol> needs to have dll-interface to be used by clients of class\n#pragma warning(disable : 4251)\n#endif\n\nnamespace benchmark {\nnamespace internal {\n\n// Typically, we can only read a small number of counters. There is also a\n// padding preceding counter values, when reading multiple counters with one\n// syscall (which is desirable). PerfCounterValues abstracts these details.\n// The implementation ensures the storage is inlined, and allows 0-based\n// indexing into the counter values.\n// The object is used in conjunction with a PerfCounters object, by passing it\n// to Snapshot(). The Read() method relocates individual reads, discarding\n// the initial padding from each group leader in the values buffer such that\n// all user accesses through the [] operator are correct.\nclass BENCHMARK_EXPORT PerfCounterValues {\n public:\n  explicit PerfCounterValues(size_t nr_counters) : nr_counters_(nr_counters) {\n    BM_CHECK_LE(nr_counters_, kMaxCounters);\n  }\n\n  // We are reading correctly now so the values don't need to skip padding\n  uint64_t operator[](size_t pos) const { return values_[pos]; }\n\n  // Increased the maximum to 32 only since the buffer\n  // is std::array<> backed\n  static constexpr size_t kMaxCounters = 32;\n\n private:\n  friend class PerfCounters;\n  // Get the byte buffer in which perf counters can be captured.\n  // This is used by PerfCounters::Read\n  std::pair<char*, size_t> get_data_buffer() {\n    return {reinterpret_cast<char*>(values_.data()),\n            sizeof(uint64_t) * (kPadding + nr_counters_)};\n  }\n\n  // This reading is complex and as the goal of this class is to\n  // abstract away the intrincacies of the reading process, this is\n  // a better place for it\n  size_t Read(const std::vector<int>& leaders);\n\n  // Move the padding to 2 due to the reading algorithm (1st padding plus a\n  // current read padding)\n  static constexpr size_t kPadding = 2;\n  std::array<uint64_t, kPadding + kMaxCounters> values_;\n  const size_t nr_counters_;\n};\n\n// Collect PMU counters. The object, once constructed, is ready to be used by\n// calling read(). PMU counter collection is enabled from the time create() is\n// called, to obtain the object, until the object's destructor is called.\nclass BENCHMARK_EXPORT PerfCounters final {\n public:\n  // True iff this platform supports performance counters.\n  static const bool kSupported;\n\n  // Returns an empty object\n  static PerfCounters NoCounters() { return PerfCounters(); }\n\n  ~PerfCounters() { CloseCounters(); }\n  PerfCounters() = default;\n  PerfCounters(PerfCounters&&) = default;\n  PerfCounters(const PerfCounters&) = delete;\n  PerfCounters& operator=(PerfCounters&&) noexcept;\n  PerfCounters& operator=(const PerfCounters&) = delete;\n\n  // Platform-specific implementations may choose to do some library\n  // initialization here.\n  static bool Initialize();\n\n  // Check if the given counter is supported, if the app wants to\n  // check before passing\n  static bool IsCounterSupported(const std::string& name);\n\n  // Return a PerfCounters object ready to read the counters with the names\n  // specified. The values are user-mode only. The counter name format is\n  // implementation and OS specific.\n  // In case of failure, this method will in the worst case return an\n  // empty object whose state will still be valid.\n  static PerfCounters Create(const std::vector<std::string>& counter_names);\n\n  // Take a snapshot of the current value of the counters into the provided\n  // valid PerfCounterValues storage. The values are populated such that:\n  // names()[i]'s value is (*values)[i]\n  BENCHMARK_ALWAYS_INLINE bool Snapshot(PerfCounterValues* values) const {\n#ifndef BENCHMARK_OS_WINDOWS\n    assert(values != nullptr);\n    return values->Read(leader_ids_) == counter_ids_.size();\n#else\n    (void)values;\n    return false;\n#endif\n  }\n\n  const std::vector<std::string>& names() const { return counter_names_; }\n  size_t num_counters() const { return counter_names_.size(); }\n\n private:\n  PerfCounters(const std::vector<std::string>& counter_names,\n               std::vector<int>&& counter_ids, std::vector<int>&& leader_ids)\n      : counter_ids_(std::move(counter_ids)),\n        leader_ids_(std::move(leader_ids)),\n        counter_names_(counter_names) {}\n\n  void CloseCounters() const;\n\n  std::vector<int> counter_ids_;\n  std::vector<int> leader_ids_;\n  std::vector<std::string> counter_names_;\n};\n\n// Typical usage of the above primitives.\nclass BENCHMARK_EXPORT PerfCountersMeasurement final {\n public:\n  PerfCountersMeasurement(const std::vector<std::string>& counter_names);\n\n  size_t num_counters() const { return counters_.num_counters(); }\n\n  std::vector<std::string> names() const { return counters_.names(); }\n\n  BENCHMARK_ALWAYS_INLINE bool Start() {\n    if (num_counters() == 0) return true;\n    // Tell the compiler to not move instructions above/below where we take\n    // the snapshot.\n    ClobberMemory();\n    valid_read_ &= counters_.Snapshot(&start_values_);\n    ClobberMemory();\n\n    return valid_read_;\n  }\n\n  BENCHMARK_ALWAYS_INLINE bool Stop(\n      std::vector<std::pair<std::string, double>>& measurements) {\n    if (num_counters() == 0) return true;\n    // Tell the compiler to not move instructions above/below where we take\n    // the snapshot.\n    ClobberMemory();\n    valid_read_ &= counters_.Snapshot(&end_values_);\n    ClobberMemory();\n\n    for (size_t i = 0; i < counters_.names().size(); ++i) {\n      double measurement = static_cast<double>(end_values_[i]) -\n                           static_cast<double>(start_values_[i]);\n      measurements.push_back({counters_.names()[i], measurement});\n    }\n\n    return valid_read_;\n  }\n\n private:\n  PerfCounters counters_;\n  bool valid_read_ = true;\n  PerfCounterValues start_values_;\n  PerfCounterValues end_values_;\n};\n\nBENCHMARK_UNUSED static bool perf_init_anchor = PerfCounters::Initialize();\n\n}  // namespace internal\n}  // namespace benchmark\n\n#if defined(_MSC_VER)\n#pragma warning(pop)\n#endif\n\n#endif  // BENCHMARK_PERF_COUNTERS_H\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/re.h",
    "content": "// Copyright 2015 Google Inc. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef BENCHMARK_RE_H_\n#define BENCHMARK_RE_H_\n\n#include \"internal_macros.h\"\n\n// clang-format off\n\n#if !defined(HAVE_STD_REGEX) && \\\n    !defined(HAVE_GNU_POSIX_REGEX) && \\\n    !defined(HAVE_POSIX_REGEX)\n  // No explicit regex selection; detect based on builtin hints.\n  #if defined(BENCHMARK_OS_LINUX) || defined(BENCHMARK_OS_APPLE)\n    #define HAVE_POSIX_REGEX 1\n  #elif __cplusplus >= 199711L\n    #define HAVE_STD_REGEX 1\n  #endif\n#endif\n\n// Prefer C regex libraries when compiling w/o exceptions so that we can\n// correctly report errors.\n#if defined(BENCHMARK_HAS_NO_EXCEPTIONS) && \\\n    defined(HAVE_STD_REGEX) && \\\n    (defined(HAVE_GNU_POSIX_REGEX) || defined(HAVE_POSIX_REGEX))\n  #undef HAVE_STD_REGEX\n#endif\n\n#if defined(HAVE_STD_REGEX)\n  #include <regex>\n#elif defined(HAVE_GNU_POSIX_REGEX)\n  #include <gnuregex.h>\n#elif defined(HAVE_POSIX_REGEX)\n  #include <regex.h>\n#else\n#error No regular expression backend was found!\n#endif\n\n// clang-format on\n\n#include <string>\n\n#include \"check.h\"\n\nnamespace benchmark {\n\n// A wrapper around the POSIX regular expression API that provides automatic\n// cleanup\nclass Regex {\n public:\n  Regex() : init_(false) {}\n\n  ~Regex();\n\n  // Compile a regular expression matcher from spec.  Returns true on success.\n  //\n  // On failure (and if error is not nullptr), error is populated with a human\n  // readable error message if an error occurs.\n  bool Init(const std::string& spec, std::string* error);\n\n  // Returns whether str matches the compiled regular expression.\n  bool Match(const std::string& str);\n\n private:\n  bool init_;\n// Underlying regular expression object\n#if defined(HAVE_STD_REGEX)\n  std::regex re_;\n#elif defined(HAVE_POSIX_REGEX) || defined(HAVE_GNU_POSIX_REGEX)\n  regex_t re_;\n#else\n#error No regular expression backend implementation available\n#endif\n};\n\n#if defined(HAVE_STD_REGEX)\n\ninline bool Regex::Init(const std::string& spec, std::string* error) {\n#ifdef BENCHMARK_HAS_NO_EXCEPTIONS\n  ((void)error);  // suppress unused warning\n#else\n  try {\n#endif\n  re_ = std::regex(spec, std::regex_constants::extended);\n  init_ = true;\n#ifndef BENCHMARK_HAS_NO_EXCEPTIONS\n}\ncatch (const std::regex_error& e) {\n  if (error) {\n    *error = e.what();\n  }\n}\n#endif\nreturn init_;\n}\n\ninline Regex::~Regex() {}\n\ninline bool Regex::Match(const std::string& str) {\n  if (!init_) {\n    return false;\n  }\n  return std::regex_search(str, re_);\n}\n\n#else\ninline bool Regex::Init(const std::string& spec, std::string* error) {\n  int ec = regcomp(&re_, spec.c_str(), REG_EXTENDED | REG_NOSUB);\n  if (ec != 0) {\n    if (error) {\n      size_t needed = regerror(ec, &re_, nullptr, 0);\n      char* errbuf = new char[needed];\n      regerror(ec, &re_, errbuf, needed);\n\n      // regerror returns the number of bytes necessary to null terminate\n      // the string, so we move that when assigning to error.\n      BM_CHECK_NE(needed, 0);\n      error->assign(errbuf, needed - 1);\n\n      delete[] errbuf;\n    }\n\n    return false;\n  }\n\n  init_ = true;\n  return true;\n}\n\ninline Regex::~Regex() {\n  if (init_) {\n    regfree(&re_);\n  }\n}\n\ninline bool Regex::Match(const std::string& str) {\n  if (!init_) {\n    return false;\n  }\n  return regexec(&re_, str.c_str(), 0, nullptr, 0) == 0;\n}\n#endif\n\n}  // end namespace benchmark\n\n#endif  // BENCHMARK_RE_H_\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/reporter.cc",
    "content": "// Copyright 2015 Google Inc. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include <cstdlib>\n#include <iostream>\n#include <map>\n#include <string>\n#include <tuple>\n#include <vector>\n\n#include \"benchmark/benchmark.h\"\n#include \"check.h\"\n#include \"string_util.h\"\n#include \"timers.h\"\n\nnamespace benchmark {\n\nBenchmarkReporter::BenchmarkReporter()\n    : output_stream_(&std::cout), error_stream_(&std::cerr) {}\n\nBenchmarkReporter::~BenchmarkReporter() {}\n\nvoid BenchmarkReporter::PrintBasicContext(std::ostream *out,\n                                          Context const &context) {\n  BM_CHECK(out) << \"cannot be null\";\n  auto &Out = *out;\n\n#ifndef BENCHMARK_OS_QURT\n  // Date/time information is not available on QuRT.\n  // Attempting to get it via this call cause the binary to crash.\n  Out << LocalDateTimeString() << \"\\n\";\n#endif\n\n  if (context.executable_name)\n    Out << \"Running \" << context.executable_name << \"\\n\";\n\n  const CPUInfo &info = context.cpu_info;\n  Out << \"Run on (\" << info.num_cpus << \" X \"\n      << (info.cycles_per_second / 1000000.0) << \" MHz CPU \"\n      << ((info.num_cpus > 1) ? \"s\" : \"\") << \")\\n\";\n  if (info.caches.size() != 0) {\n    Out << \"CPU Caches:\\n\";\n    for (auto &CInfo : info.caches) {\n      Out << \"  L\" << CInfo.level << \" \" << CInfo.type << \" \"\n          << (CInfo.size / 1024) << \" KiB\";\n      if (CInfo.num_sharing != 0)\n        Out << \" (x\" << (info.num_cpus / CInfo.num_sharing) << \")\";\n      Out << \"\\n\";\n    }\n  }\n  if (!info.load_avg.empty()) {\n    Out << \"Load Average: \";\n    for (auto It = info.load_avg.begin(); It != info.load_avg.end();) {\n      Out << StrFormat(\"%.2f\", *It++);\n      if (It != info.load_avg.end()) Out << \", \";\n    }\n    Out << \"\\n\";\n  }\n\n  std::map<std::string, std::string> *global_context =\n      internal::GetGlobalContext();\n\n  if (global_context != nullptr) {\n    for (const auto &kv : *global_context) {\n      Out << kv.first << \": \" << kv.second << \"\\n\";\n    }\n  }\n\n  if (CPUInfo::Scaling::ENABLED == info.scaling) {\n    Out << \"***WARNING*** CPU scaling is enabled, the benchmark \"\n           \"real time measurements may be noisy and will incur extra \"\n           \"overhead.\\n\";\n  }\n\n#ifndef NDEBUG\n  Out << \"***WARNING*** Library was built as DEBUG. Timings may be \"\n         \"affected.\\n\";\n#endif\n}\n\n// No initializer because it's already initialized to NULL.\nconst char *BenchmarkReporter::Context::executable_name;\n\nBenchmarkReporter::Context::Context()\n    : cpu_info(CPUInfo::Get()), sys_info(SystemInfo::Get()) {}\n\nstd::string BenchmarkReporter::Run::benchmark_name() const {\n  std::string name = run_name.str();\n  if (run_type == RT_Aggregate) {\n    name += \"_\" + aggregate_name;\n  }\n  return name;\n}\n\ndouble BenchmarkReporter::Run::GetAdjustedRealTime() const {\n  double new_time = real_accumulated_time * GetTimeUnitMultiplier(time_unit);\n  if (iterations != 0) new_time /= static_cast<double>(iterations);\n  return new_time;\n}\n\ndouble BenchmarkReporter::Run::GetAdjustedCPUTime() const {\n  double new_time = cpu_accumulated_time * GetTimeUnitMultiplier(time_unit);\n  if (iterations != 0) new_time /= static_cast<double>(iterations);\n  return new_time;\n}\n\n}  // end namespace benchmark\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/statistics.cc",
    "content": "// Copyright 2016 Ismael Jimenez Martinez. All rights reserved.\n// Copyright 2017 Roman Lebedev. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"statistics.h\"\n\n#include <algorithm>\n#include <cmath>\n#include <numeric>\n#include <string>\n#include <vector>\n\n#include \"benchmark/benchmark.h\"\n#include \"check.h\"\n\nnamespace benchmark {\n\nauto StatisticsSum = [](const std::vector<double>& v) {\n  return std::accumulate(v.begin(), v.end(), 0.0);\n};\n\ndouble StatisticsMean(const std::vector<double>& v) {\n  if (v.empty()) return 0.0;\n  return StatisticsSum(v) * (1.0 / v.size());\n}\n\ndouble StatisticsMedian(const std::vector<double>& v) {\n  if (v.size() < 3) return StatisticsMean(v);\n  std::vector<double> copy(v);\n\n  auto center = copy.begin() + v.size() / 2;\n  std::nth_element(copy.begin(), center, copy.end());\n\n  // did we have an odd number of samples?\n  // if yes, then center is the median\n  // it no, then we are looking for the average between center and the value\n  // before\n  if (v.size() % 2 == 1) return *center;\n  auto center2 = copy.begin() + v.size() / 2 - 1;\n  std::nth_element(copy.begin(), center2, copy.end());\n  return (*center + *center2) / 2.0;\n}\n\n// Return the sum of the squares of this sample set\nauto SumSquares = [](const std::vector<double>& v) {\n  return std::inner_product(v.begin(), v.end(), v.begin(), 0.0);\n};\n\nauto Sqr = [](const double dat) { return dat * dat; };\nauto Sqrt = [](const double dat) {\n  // Avoid NaN due to imprecision in the calculations\n  if (dat < 0.0) return 0.0;\n  return std::sqrt(dat);\n};\n\ndouble StatisticsStdDev(const std::vector<double>& v) {\n  const auto mean = StatisticsMean(v);\n  if (v.empty()) return mean;\n\n  // Sample standard deviation is undefined for n = 1\n  if (v.size() == 1) return 0.0;\n\n  const double avg_squares = SumSquares(v) * (1.0 / v.size());\n  return Sqrt(v.size() / (v.size() - 1.0) * (avg_squares - Sqr(mean)));\n}\n\ndouble StatisticsCV(const std::vector<double>& v) {\n  if (v.size() < 2) return 0.0;\n\n  const auto stddev = StatisticsStdDev(v);\n  const auto mean = StatisticsMean(v);\n\n  return stddev / mean;\n}\n\nstd::vector<BenchmarkReporter::Run> ComputeStats(\n    const std::vector<BenchmarkReporter::Run>& reports) {\n  typedef BenchmarkReporter::Run Run;\n  std::vector<Run> results;\n\n  auto error_count = std::count_if(reports.begin(), reports.end(),\n                                   [](Run const& run) { return run.skipped; });\n\n  if (reports.size() - error_count < 2) {\n    // We don't report aggregated data if there was a single run.\n    return results;\n  }\n\n  // Accumulators.\n  std::vector<double> real_accumulated_time_stat;\n  std::vector<double> cpu_accumulated_time_stat;\n\n  real_accumulated_time_stat.reserve(reports.size());\n  cpu_accumulated_time_stat.reserve(reports.size());\n\n  // All repetitions should be run with the same number of iterations so we\n  // can take this information from the first benchmark.\n  const IterationCount run_iterations = reports.front().iterations;\n  // create stats for user counters\n  struct CounterStat {\n    Counter c;\n    std::vector<double> s;\n  };\n  std::map<std::string, CounterStat> counter_stats;\n  for (Run const& r : reports) {\n    for (auto const& cnt : r.counters) {\n      auto it = counter_stats.find(cnt.first);\n      if (it == counter_stats.end()) {\n        it = counter_stats\n                 .emplace(cnt.first,\n                          CounterStat{cnt.second, std::vector<double>{}})\n                 .first;\n        it->second.s.reserve(reports.size());\n      } else {\n        BM_CHECK_EQ(it->second.c.flags, cnt.second.flags);\n      }\n    }\n  }\n\n  // Populate the accumulators.\n  for (Run const& run : reports) {\n    BM_CHECK_EQ(reports[0].benchmark_name(), run.benchmark_name());\n    BM_CHECK_EQ(run_iterations, run.iterations);\n    if (run.skipped) continue;\n    real_accumulated_time_stat.emplace_back(run.real_accumulated_time);\n    cpu_accumulated_time_stat.emplace_back(run.cpu_accumulated_time);\n    // user counters\n    for (auto const& cnt : run.counters) {\n      auto it = counter_stats.find(cnt.first);\n      BM_CHECK_NE(it, counter_stats.end());\n      it->second.s.emplace_back(cnt.second);\n    }\n  }\n\n  // Only add label if it is same for all runs\n  std::string report_label = reports[0].report_label;\n  for (std::size_t i = 1; i < reports.size(); i++) {\n    if (reports[i].report_label != report_label) {\n      report_label = \"\";\n      break;\n    }\n  }\n\n  const double iteration_rescale_factor =\n      double(reports.size()) / double(run_iterations);\n\n  for (const auto& Stat : *reports[0].statistics) {\n    // Get the data from the accumulator to BenchmarkReporter::Run's.\n    Run data;\n    data.run_name = reports[0].run_name;\n    data.family_index = reports[0].family_index;\n    data.per_family_instance_index = reports[0].per_family_instance_index;\n    data.run_type = BenchmarkReporter::Run::RT_Aggregate;\n    data.threads = reports[0].threads;\n    data.repetitions = reports[0].repetitions;\n    data.repetition_index = Run::no_repetition_index;\n    data.aggregate_name = Stat.name_;\n    data.aggregate_unit = Stat.unit_;\n    data.report_label = report_label;\n\n    // It is incorrect to say that an aggregate is computed over\n    // run's iterations, because those iterations already got averaged.\n    // Similarly, if there are N repetitions with 1 iterations each,\n    // an aggregate will be computed over N measurements, not 1.\n    // Thus it is best to simply use the count of separate reports.\n    data.iterations = reports.size();\n\n    data.real_accumulated_time = Stat.compute_(real_accumulated_time_stat);\n    data.cpu_accumulated_time = Stat.compute_(cpu_accumulated_time_stat);\n\n    if (data.aggregate_unit == StatisticUnit::kTime) {\n      // We will divide these times by data.iterations when reporting, but the\n      // data.iterations is not necessarily the scale of these measurements,\n      // because in each repetition, these timers are sum over all the iters.\n      // And if we want to say that the stats are over N repetitions and not\n      // M iterations, we need to multiply these by (N/M).\n      data.real_accumulated_time *= iteration_rescale_factor;\n      data.cpu_accumulated_time *= iteration_rescale_factor;\n    }\n\n    data.time_unit = reports[0].time_unit;\n\n    // user counters\n    for (auto const& kv : counter_stats) {\n      // Do *NOT* rescale the custom counters. They are already properly scaled.\n      const auto uc_stat = Stat.compute_(kv.second.s);\n      auto c = Counter(uc_stat, counter_stats[kv.first].c.flags,\n                       counter_stats[kv.first].c.oneK);\n      data.counters[kv.first] = c;\n    }\n\n    results.push_back(data);\n  }\n\n  return results;\n}\n\n}  // end namespace benchmark\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/statistics.h",
    "content": "// Copyright 2016 Ismael Jimenez Martinez. All rights reserved.\n// Copyright 2017 Roman Lebedev. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef STATISTICS_H_\n#define STATISTICS_H_\n\n#include <vector>\n\n#include \"benchmark/benchmark.h\"\n\nnamespace benchmark {\n\n// Return a vector containing the mean, median and standard deviation\n// information (and any user-specified info) for the specified list of reports.\n// If 'reports' contains less than two non-errored runs an empty vector is\n// returned\nBENCHMARK_EXPORT\nstd::vector<BenchmarkReporter::Run> ComputeStats(\n    const std::vector<BenchmarkReporter::Run>& reports);\n\nBENCHMARK_EXPORT\ndouble StatisticsMean(const std::vector<double>& v);\nBENCHMARK_EXPORT\ndouble StatisticsMedian(const std::vector<double>& v);\nBENCHMARK_EXPORT\ndouble StatisticsStdDev(const std::vector<double>& v);\nBENCHMARK_EXPORT\ndouble StatisticsCV(const std::vector<double>& v);\n\n}  // end namespace benchmark\n\n#endif  // STATISTICS_H_\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/string_util.cc",
    "content": "#include \"string_util.h\"\n\n#include <array>\n#ifdef BENCHMARK_STL_ANDROID_GNUSTL\n#include <cerrno>\n#endif\n#include <cmath>\n#include <cstdarg>\n#include <cstdio>\n#include <memory>\n#include <sstream>\n\n#include \"arraysize.h\"\n\nnamespace benchmark {\nnamespace {\n\n// kilo, Mega, Giga, Tera, Peta, Exa, Zetta, Yotta.\nconst char kBigSIUnits[] = \"kMGTPEZY\";\n// Kibi, Mebi, Gibi, Tebi, Pebi, Exbi, Zebi, Yobi.\nconst char kBigIECUnits[] = \"KMGTPEZY\";\n// milli, micro, nano, pico, femto, atto, zepto, yocto.\nconst char kSmallSIUnits[] = \"munpfazy\";\n\n// We require that all three arrays have the same size.\nstatic_assert(arraysize(kBigSIUnits) == arraysize(kBigIECUnits),\n              \"SI and IEC unit arrays must be the same size\");\nstatic_assert(arraysize(kSmallSIUnits) == arraysize(kBigSIUnits),\n              \"Small SI and Big SI unit arrays must be the same size\");\n\nstatic const int64_t kUnitsSize = arraysize(kBigSIUnits);\n\nvoid ToExponentAndMantissa(double val, double thresh, int precision,\n                           double one_k, std::string* mantissa,\n                           int64_t* exponent) {\n  std::stringstream mantissa_stream;\n\n  if (val < 0) {\n    mantissa_stream << \"-\";\n    val = -val;\n  }\n\n  // Adjust threshold so that it never excludes things which can't be rendered\n  // in 'precision' digits.\n  const double adjusted_threshold =\n      std::max(thresh, 1.0 / std::pow(10.0, precision));\n  const double big_threshold = adjusted_threshold * one_k;\n  const double small_threshold = adjusted_threshold;\n  // Values in ]simple_threshold,small_threshold[ will be printed as-is\n  const double simple_threshold = 0.01;\n\n  if (val > big_threshold) {\n    // Positive powers\n    double scaled = val;\n    for (size_t i = 0; i < arraysize(kBigSIUnits); ++i) {\n      scaled /= one_k;\n      if (scaled <= big_threshold) {\n        mantissa_stream << scaled;\n        *exponent = i + 1;\n        *mantissa = mantissa_stream.str();\n        return;\n      }\n    }\n    mantissa_stream << val;\n    *exponent = 0;\n  } else if (val < small_threshold) {\n    // Negative powers\n    if (val < simple_threshold) {\n      double scaled = val;\n      for (size_t i = 0; i < arraysize(kSmallSIUnits); ++i) {\n        scaled *= one_k;\n        if (scaled >= small_threshold) {\n          mantissa_stream << scaled;\n          *exponent = -static_cast<int64_t>(i + 1);\n          *mantissa = mantissa_stream.str();\n          return;\n        }\n      }\n    }\n    mantissa_stream << val;\n    *exponent = 0;\n  } else {\n    mantissa_stream << val;\n    *exponent = 0;\n  }\n  *mantissa = mantissa_stream.str();\n}\n\nstd::string ExponentToPrefix(int64_t exponent, bool iec) {\n  if (exponent == 0) return \"\";\n\n  const int64_t index = (exponent > 0 ? exponent - 1 : -exponent - 1);\n  if (index >= kUnitsSize) return \"\";\n\n  const char* array =\n      (exponent > 0 ? (iec ? kBigIECUnits : kBigSIUnits) : kSmallSIUnits);\n  if (iec) {\n    return array[index] + std::string(\"i\");\n  }\n  return std::string(1, array[index]);\n}\n\nstd::string ToBinaryStringFullySpecified(double value, double threshold,\n                                         int precision, double one_k = 1024.0) {\n  std::string mantissa;\n  int64_t exponent;\n  ToExponentAndMantissa(value, threshold, precision, one_k, &mantissa,\n                        &exponent);\n  return mantissa + ExponentToPrefix(exponent, false);\n}\n\n}  // end namespace\n\nvoid AppendHumanReadable(int n, std::string* str) {\n  std::stringstream ss;\n  // Round down to the nearest SI prefix.\n  ss << ToBinaryStringFullySpecified(n, 1.0, 0);\n  *str += ss.str();\n}\n\nstd::string HumanReadableNumber(double n, double one_k) {\n  // 1.1 means that figures up to 1.1k should be shown with the next unit down;\n  // this softens edge effects.\n  // 1 means that we should show one decimal place of precision.\n  return ToBinaryStringFullySpecified(n, 1.1, 1, one_k);\n}\n\nstd::string StrFormatImp(const char* msg, va_list args) {\n  // we might need a second shot at this, so pre-emptivly make a copy\n  va_list args_cp;\n  va_copy(args_cp, args);\n\n  // TODO(ericwf): use std::array for first attempt to avoid one memory\n  // allocation guess what the size might be\n  std::array<char, 256> local_buff;\n\n  // 2015-10-08: vsnprintf is used instead of snd::vsnprintf due to a limitation\n  // in the android-ndk\n  auto ret = vsnprintf(local_buff.data(), local_buff.size(), msg, args_cp);\n\n  va_end(args_cp);\n\n  // handle empty expansion\n  if (ret == 0) return std::string{};\n  if (static_cast<std::size_t>(ret) < local_buff.size())\n    return std::string(local_buff.data());\n\n  // we did not provide a long enough buffer on our first attempt.\n  // add 1 to size to account for null-byte in size cast to prevent overflow\n  std::size_t size = static_cast<std::size_t>(ret) + 1;\n  auto buff_ptr = std::unique_ptr<char[]>(new char[size]);\n  // 2015-10-08: vsnprintf is used instead of snd::vsnprintf due to a limitation\n  // in the android-ndk\n  vsnprintf(buff_ptr.get(), size, msg, args);\n  return std::string(buff_ptr.get());\n}\n\nstd::string StrFormat(const char* format, ...) {\n  va_list args;\n  va_start(args, format);\n  std::string tmp = StrFormatImp(format, args);\n  va_end(args);\n  return tmp;\n}\n\nstd::vector<std::string> StrSplit(const std::string& str, char delim) {\n  if (str.empty()) return {};\n  std::vector<std::string> ret;\n  size_t first = 0;\n  size_t next = str.find(delim);\n  for (; next != std::string::npos;\n       first = next + 1, next = str.find(delim, first)) {\n    ret.push_back(str.substr(first, next - first));\n  }\n  ret.push_back(str.substr(first));\n  return ret;\n}\n\n#ifdef BENCHMARK_STL_ANDROID_GNUSTL\n/*\n * GNU STL in Android NDK lacks support for some C++11 functions, including\n * stoul, stoi, stod. We reimplement them here using C functions strtoul,\n * strtol, strtod. Note that reimplemented functions are in benchmark::\n * namespace, not std:: namespace.\n */\nunsigned long stoul(const std::string& str, size_t* pos, int base) {\n  /* Record previous errno */\n  const int oldErrno = errno;\n  errno = 0;\n\n  const char* strStart = str.c_str();\n  char* strEnd = const_cast<char*>(strStart);\n  const unsigned long result = strtoul(strStart, &strEnd, base);\n\n  const int strtoulErrno = errno;\n  /* Restore previous errno */\n  errno = oldErrno;\n\n  /* Check for errors and return */\n  if (strtoulErrno == ERANGE) {\n    throw std::out_of_range(\"stoul failed: \" + str +\n                            \" is outside of range of unsigned long\");\n  } else if (strEnd == strStart || strtoulErrno != 0) {\n    throw std::invalid_argument(\"stoul failed: \" + str + \" is not an integer\");\n  }\n  if (pos != nullptr) {\n    *pos = static_cast<size_t>(strEnd - strStart);\n  }\n  return result;\n}\n\nint stoi(const std::string& str, size_t* pos, int base) {\n  /* Record previous errno */\n  const int oldErrno = errno;\n  errno = 0;\n\n  const char* strStart = str.c_str();\n  char* strEnd = const_cast<char*>(strStart);\n  const long result = strtol(strStart, &strEnd, base);\n\n  const int strtolErrno = errno;\n  /* Restore previous errno */\n  errno = oldErrno;\n\n  /* Check for errors and return */\n  if (strtolErrno == ERANGE || long(int(result)) != result) {\n    throw std::out_of_range(\"stoul failed: \" + str +\n                            \" is outside of range of int\");\n  } else if (strEnd == strStart || strtolErrno != 0) {\n    throw std::invalid_argument(\"stoul failed: \" + str + \" is not an integer\");\n  }\n  if (pos != nullptr) {\n    *pos = static_cast<size_t>(strEnd - strStart);\n  }\n  return int(result);\n}\n\ndouble stod(const std::string& str, size_t* pos) {\n  /* Record previous errno */\n  const int oldErrno = errno;\n  errno = 0;\n\n  const char* strStart = str.c_str();\n  char* strEnd = const_cast<char*>(strStart);\n  const double result = strtod(strStart, &strEnd);\n\n  /* Restore previous errno */\n  const int strtodErrno = errno;\n  errno = oldErrno;\n\n  /* Check for errors and return */\n  if (strtodErrno == ERANGE) {\n    throw std::out_of_range(\"stoul failed: \" + str +\n                            \" is outside of range of int\");\n  } else if (strEnd == strStart || strtodErrno != 0) {\n    throw std::invalid_argument(\"stoul failed: \" + str + \" is not an integer\");\n  }\n  if (pos != nullptr) {\n    *pos = static_cast<size_t>(strEnd - strStart);\n  }\n  return result;\n}\n#endif\n\n}  // end namespace benchmark\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/string_util.h",
    "content": "#ifndef BENCHMARK_STRING_UTIL_H_\n#define BENCHMARK_STRING_UTIL_H_\n\n#include <sstream>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"benchmark/export.h\"\n#include \"check.h\"\n#include \"internal_macros.h\"\n\nnamespace benchmark {\n\nvoid AppendHumanReadable(int n, std::string* str);\n\nstd::string HumanReadableNumber(double n, double one_k = 1024.0);\n\nBENCHMARK_EXPORT\n#if defined(__MINGW32__)\n__attribute__((format(__MINGW_PRINTF_FORMAT, 1, 2)))\n#elif defined(__GNUC__)\n__attribute__((format(printf, 1, 2)))\n#endif\nstd::string\nStrFormat(const char* format, ...);\n\ninline std::ostream& StrCatImp(std::ostream& out) BENCHMARK_NOEXCEPT {\n  return out;\n}\n\ntemplate <class First, class... Rest>\ninline std::ostream& StrCatImp(std::ostream& out, First&& f, Rest&&... rest) {\n  out << std::forward<First>(f);\n  return StrCatImp(out, std::forward<Rest>(rest)...);\n}\n\ntemplate <class... Args>\ninline std::string StrCat(Args&&... args) {\n  std::ostringstream ss;\n  StrCatImp(ss, std::forward<Args>(args)...);\n  return ss.str();\n}\n\nBENCHMARK_EXPORT\nstd::vector<std::string> StrSplit(const std::string& str, char delim);\n\n// Disable lint checking for this block since it re-implements C functions.\n// NOLINTBEGIN\n#ifdef BENCHMARK_STL_ANDROID_GNUSTL\n/*\n * GNU STL in Android NDK lacks support for some C++11 functions, including\n * stoul, stoi, stod. We reimplement them here using C functions strtoul,\n * strtol, strtod. Note that reimplemented functions are in benchmark::\n * namespace, not std:: namespace.\n */\nunsigned long stoul(const std::string& str, size_t* pos = nullptr,\n                    int base = 10);\nint stoi(const std::string& str, size_t* pos = nullptr, int base = 10);\ndouble stod(const std::string& str, size_t* pos = nullptr);\n#else\nusing std::stod;   // NOLINT(misc-unused-using-decls)\nusing std::stoi;   // NOLINT(misc-unused-using-decls)\nusing std::stoul;  // NOLINT(misc-unused-using-decls)\n#endif\n// NOLINTEND\n\n}  // end namespace benchmark\n\n#endif  // BENCHMARK_STRING_UTIL_H_\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/sysinfo.cc",
    "content": "// Copyright 2015 Google Inc. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"internal_macros.h\"\n\n#ifdef BENCHMARK_OS_WINDOWS\n#include <shlwapi.h>\n#undef StrCat  // Don't let StrCat in string_util.h be renamed to lstrcatA\n#include <versionhelpers.h>\n#include <windows.h>\n\n#include <codecvt>\n#else\n#include <fcntl.h>\n#if !defined(BENCHMARK_OS_FUCHSIA) && !defined(BENCHMARK_OS_QURT)\n#include <sys/resource.h>\n#endif\n#include <sys/time.h>\n#include <sys/types.h>  // this header must be included before 'sys/sysctl.h' to avoid compilation error on FreeBSD\n#include <unistd.h>\n#if defined BENCHMARK_OS_FREEBSD || defined BENCHMARK_OS_MACOSX || \\\n    defined BENCHMARK_OS_NETBSD || defined BENCHMARK_OS_OPENBSD || \\\n    defined BENCHMARK_OS_DRAGONFLY\n#define BENCHMARK_HAS_SYSCTL\n#include <sys/sysctl.h>\n#endif\n#endif\n#if defined(BENCHMARK_OS_SOLARIS)\n#include <kstat.h>\n#include <netdb.h>\n#endif\n#if defined(BENCHMARK_OS_QNX)\n#include <sys/syspage.h>\n#endif\n#if defined(BENCHMARK_OS_QURT)\n#include <qurt.h>\n#endif\n#if defined(BENCHMARK_HAS_PTHREAD_AFFINITY)\n#include <pthread.h>\n#endif\n\n#include <algorithm>\n#include <array>\n#include <bitset>\n#include <cerrno>\n#include <climits>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <fstream>\n#include <iostream>\n#include <iterator>\n#include <limits>\n#include <locale>\n#include <memory>\n#include <random>\n#include <sstream>\n#include <utility>\n\n#include \"benchmark/benchmark.h\"\n#include \"check.h\"\n#include \"cycleclock.h\"\n#include \"internal_macros.h\"\n#include \"log.h\"\n#include \"string_util.h\"\n#include \"timers.h\"\n\nnamespace benchmark {\nnamespace {\n\nvoid PrintImp(std::ostream& out) { out << std::endl; }\n\ntemplate <class First, class... Rest>\nvoid PrintImp(std::ostream& out, First&& f, Rest&&... rest) {\n  out << std::forward<First>(f);\n  PrintImp(out, std::forward<Rest>(rest)...);\n}\n\ntemplate <class... Args>\nBENCHMARK_NORETURN void PrintErrorAndDie(Args&&... args) {\n  PrintImp(std::cerr, std::forward<Args>(args)...);\n  std::exit(EXIT_FAILURE);\n}\n\n#ifdef BENCHMARK_HAS_SYSCTL\n\n/// ValueUnion - A type used to correctly alias the byte-for-byte output of\n/// `sysctl` with the result type it's to be interpreted as.\nstruct ValueUnion {\n  union DataT {\n    int32_t int32_value;\n    int64_t int64_value;\n    // For correct aliasing of union members from bytes.\n    char bytes[8];\n  };\n  using DataPtr = std::unique_ptr<DataT, decltype(&std::free)>;\n\n  // The size of the data union member + its trailing array size.\n  std::size_t size;\n  DataPtr buff;\n\n public:\n  ValueUnion() : size(0), buff(nullptr, &std::free) {}\n\n  explicit ValueUnion(std::size_t buff_size)\n      : size(sizeof(DataT) + buff_size),\n        buff(::new (std::malloc(size)) DataT(), &std::free) {}\n\n  ValueUnion(ValueUnion&& other) = default;\n\n  explicit operator bool() const { return bool(buff); }\n\n  char* data() const { return buff->bytes; }\n\n  std::string GetAsString() const { return std::string(data()); }\n\n  int64_t GetAsInteger() const {\n    if (size == sizeof(buff->int32_value))\n      return buff->int32_value;\n    else if (size == sizeof(buff->int64_value))\n      return buff->int64_value;\n    BENCHMARK_UNREACHABLE();\n  }\n\n  template <class T, int N>\n  std::array<T, N> GetAsArray() {\n    const int arr_size = sizeof(T) * N;\n    BM_CHECK_LE(arr_size, size);\n    std::array<T, N> arr;\n    std::memcpy(arr.data(), data(), arr_size);\n    return arr;\n  }\n};\n\nValueUnion GetSysctlImp(std::string const& name) {\n#if defined BENCHMARK_OS_OPENBSD\n  int mib[2];\n\n  mib[0] = CTL_HW;\n  if ((name == \"hw.ncpu\") || (name == \"hw.cpuspeed\")) {\n    ValueUnion buff(sizeof(int));\n\n    if (name == \"hw.ncpu\") {\n      mib[1] = HW_NCPU;\n    } else {\n      mib[1] = HW_CPUSPEED;\n    }\n\n    if (sysctl(mib, 2, buff.data(), &buff.Size, nullptr, 0) == -1) {\n      return ValueUnion();\n    }\n    return buff;\n  }\n  return ValueUnion();\n#else\n  std::size_t cur_buff_size = 0;\n  if (sysctlbyname(name.c_str(), nullptr, &cur_buff_size, nullptr, 0) == -1)\n    return ValueUnion();\n\n  ValueUnion buff(cur_buff_size);\n  if (sysctlbyname(name.c_str(), buff.data(), &buff.size, nullptr, 0) == 0)\n    return buff;\n  return ValueUnion();\n#endif\n}\n\nBENCHMARK_MAYBE_UNUSED\nbool GetSysctl(std::string const& name, std::string* out) {\n  out->clear();\n  auto buff = GetSysctlImp(name);\n  if (!buff) return false;\n  out->assign(buff.data());\n  return true;\n}\n\ntemplate <class Tp,\n          class = typename std::enable_if<std::is_integral<Tp>::value>::type>\nbool GetSysctl(std::string const& name, Tp* out) {\n  *out = 0;\n  auto buff = GetSysctlImp(name);\n  if (!buff) return false;\n  *out = static_cast<Tp>(buff.GetAsInteger());\n  return true;\n}\n\ntemplate <class Tp, size_t N>\nbool GetSysctl(std::string const& name, std::array<Tp, N>* out) {\n  auto buff = GetSysctlImp(name);\n  if (!buff) return false;\n  *out = buff.GetAsArray<Tp, N>();\n  return true;\n}\n#endif\n\ntemplate <class ArgT>\nbool ReadFromFile(std::string const& fname, ArgT* arg) {\n  *arg = ArgT();\n  std::ifstream f(fname.c_str());\n  if (!f.is_open()) return false;\n  f >> *arg;\n  return f.good();\n}\n\nCPUInfo::Scaling CpuScaling(int num_cpus) {\n  // We don't have a valid CPU count, so don't even bother.\n  if (num_cpus <= 0) return CPUInfo::Scaling::UNKNOWN;\n#if defined(BENCHMARK_OS_QNX)\n  return CPUInfo::Scaling::UNKNOWN;\n#elif !defined(BENCHMARK_OS_WINDOWS)\n  // On Linux, the CPUfreq subsystem exposes CPU information as files on the\n  // local file system. If reading the exported files fails, then we may not be\n  // running on Linux, so we silently ignore all the read errors.\n  std::string res;\n  for (int cpu = 0; cpu < num_cpus; ++cpu) {\n    std::string governor_file =\n        StrCat(\"/sys/devices/system/cpu/cpu\", cpu, \"/cpufreq/scaling_governor\");\n    if (ReadFromFile(governor_file, &res) && res != \"performance\")\n      return CPUInfo::Scaling::ENABLED;\n  }\n  return CPUInfo::Scaling::DISABLED;\n#else\n  return CPUInfo::Scaling::UNKNOWN;\n#endif\n}\n\nint CountSetBitsInCPUMap(std::string val) {\n  auto CountBits = [](std::string part) {\n    using CPUMask = std::bitset<sizeof(std::uintptr_t) * CHAR_BIT>;\n    part = \"0x\" + part;\n    CPUMask mask(benchmark::stoul(part, nullptr, 16));\n    return static_cast<int>(mask.count());\n  };\n  std::size_t pos;\n  int total = 0;\n  while ((pos = val.find(',')) != std::string::npos) {\n    total += CountBits(val.substr(0, pos));\n    val = val.substr(pos + 1);\n  }\n  if (!val.empty()) {\n    total += CountBits(val);\n  }\n  return total;\n}\n\nBENCHMARK_MAYBE_UNUSED\nstd::vector<CPUInfo::CacheInfo> GetCacheSizesFromKVFS() {\n  std::vector<CPUInfo::CacheInfo> res;\n  std::string dir = \"/sys/devices/system/cpu/cpu0/cache/\";\n  int idx = 0;\n  while (true) {\n    CPUInfo::CacheInfo info;\n    std::string fpath = StrCat(dir, \"index\", idx++, \"/\");\n    std::ifstream f(StrCat(fpath, \"size\").c_str());\n    if (!f.is_open()) break;\n    std::string suffix;\n    f >> info.size;\n    if (f.fail())\n      PrintErrorAndDie(\"Failed while reading file '\", fpath, \"size'\");\n    if (f.good()) {\n      f >> suffix;\n      if (f.bad())\n        PrintErrorAndDie(\n            \"Invalid cache size format: failed to read size suffix\");\n      else if (f && suffix != \"K\")\n        PrintErrorAndDie(\"Invalid cache size format: Expected bytes \", suffix);\n      else if (suffix == \"K\")\n        info.size *= 1024;\n    }\n    if (!ReadFromFile(StrCat(fpath, \"type\"), &info.type))\n      PrintErrorAndDie(\"Failed to read from file \", fpath, \"type\");\n    if (!ReadFromFile(StrCat(fpath, \"level\"), &info.level))\n      PrintErrorAndDie(\"Failed to read from file \", fpath, \"level\");\n    std::string map_str;\n    if (!ReadFromFile(StrCat(fpath, \"shared_cpu_map\"), &map_str))\n      PrintErrorAndDie(\"Failed to read from file \", fpath, \"shared_cpu_map\");\n    info.num_sharing = CountSetBitsInCPUMap(map_str);\n    res.push_back(info);\n  }\n\n  return res;\n}\n\n#ifdef BENCHMARK_OS_MACOSX\nstd::vector<CPUInfo::CacheInfo> GetCacheSizesMacOSX() {\n  std::vector<CPUInfo::CacheInfo> res;\n  std::array<int, 4> cache_counts{{0, 0, 0, 0}};\n  GetSysctl(\"hw.cacheconfig\", &cache_counts);\n\n  struct {\n    std::string name;\n    std::string type;\n    int level;\n    int num_sharing;\n  } cases[] = {{\"hw.l1dcachesize\", \"Data\", 1, cache_counts[1]},\n               {\"hw.l1icachesize\", \"Instruction\", 1, cache_counts[1]},\n               {\"hw.l2cachesize\", \"Unified\", 2, cache_counts[2]},\n               {\"hw.l3cachesize\", \"Unified\", 3, cache_counts[3]}};\n  for (auto& c : cases) {\n    int val;\n    if (!GetSysctl(c.name, &val)) continue;\n    CPUInfo::CacheInfo info;\n    info.type = c.type;\n    info.level = c.level;\n    info.size = val;\n    info.num_sharing = c.num_sharing;\n    res.push_back(std::move(info));\n  }\n  return res;\n}\n#elif defined(BENCHMARK_OS_WINDOWS)\nstd::vector<CPUInfo::CacheInfo> GetCacheSizesWindows() {\n  std::vector<CPUInfo::CacheInfo> res;\n  DWORD buffer_size = 0;\n  using PInfo = SYSTEM_LOGICAL_PROCESSOR_INFORMATION;\n  using CInfo = CACHE_DESCRIPTOR;\n\n  using UPtr = std::unique_ptr<PInfo, decltype(&std::free)>;\n  GetLogicalProcessorInformation(nullptr, &buffer_size);\n  UPtr buff((PInfo*)malloc(buffer_size), &std::free);\n  if (!GetLogicalProcessorInformation(buff.get(), &buffer_size))\n    PrintErrorAndDie(\"Failed during call to GetLogicalProcessorInformation: \",\n                     GetLastError());\n\n  PInfo* it = buff.get();\n  PInfo* end = buff.get() + (buffer_size / sizeof(PInfo));\n\n  for (; it != end; ++it) {\n    if (it->Relationship != RelationCache) continue;\n    using BitSet = std::bitset<sizeof(ULONG_PTR) * CHAR_BIT>;\n    BitSet b(it->ProcessorMask);\n    // To prevent duplicates, only consider caches where CPU 0 is specified\n    if (!b.test(0)) continue;\n    const CInfo& cache = it->Cache;\n    CPUInfo::CacheInfo C;\n    C.num_sharing = static_cast<int>(b.count());\n    C.level = cache.Level;\n    C.size = cache.Size;\n    C.type = \"Unknown\";\n    switch (cache.Type) {\n      case CacheUnified:\n        C.type = \"Unified\";\n        break;\n      case CacheInstruction:\n        C.type = \"Instruction\";\n        break;\n      case CacheData:\n        C.type = \"Data\";\n        break;\n      case CacheTrace:\n        C.type = \"Trace\";\n        break;\n    }\n    res.push_back(C);\n  }\n  return res;\n}\n#elif BENCHMARK_OS_QNX\nstd::vector<CPUInfo::CacheInfo> GetCacheSizesQNX() {\n  std::vector<CPUInfo::CacheInfo> res;\n  struct cacheattr_entry* cache = SYSPAGE_ENTRY(cacheattr);\n  uint32_t const elsize = SYSPAGE_ELEMENT_SIZE(cacheattr);\n  int num = SYSPAGE_ENTRY_SIZE(cacheattr) / elsize;\n  for (int i = 0; i < num; ++i) {\n    CPUInfo::CacheInfo info;\n    switch (cache->flags) {\n      case CACHE_FLAG_INSTR:\n        info.type = \"Instruction\";\n        info.level = 1;\n        break;\n      case CACHE_FLAG_DATA:\n        info.type = \"Data\";\n        info.level = 1;\n        break;\n      case CACHE_FLAG_UNIFIED:\n        info.type = \"Unified\";\n        info.level = 2;\n        break;\n      case CACHE_FLAG_SHARED:\n        info.type = \"Shared\";\n        info.level = 3;\n        break;\n      default:\n        continue;\n        break;\n    }\n    info.size = cache->line_size * cache->num_lines;\n    info.num_sharing = 0;\n    res.push_back(std::move(info));\n    cache = SYSPAGE_ARRAY_ADJ_OFFSET(cacheattr, cache, elsize);\n  }\n  return res;\n}\n#endif\n\nstd::vector<CPUInfo::CacheInfo> GetCacheSizes() {\n#ifdef BENCHMARK_OS_MACOSX\n  return GetCacheSizesMacOSX();\n#elif defined(BENCHMARK_OS_WINDOWS)\n  return GetCacheSizesWindows();\n#elif defined(BENCHMARK_OS_QNX)\n  return GetCacheSizesQNX();\n#elif defined(BENCHMARK_OS_QURT)\n  return std::vector<CPUInfo::CacheInfo>();\n#else\n  return GetCacheSizesFromKVFS();\n#endif\n}\n\nstd::string GetSystemName() {\n#if defined(BENCHMARK_OS_WINDOWS)\n  std::string str;\n  static constexpr int COUNT = MAX_COMPUTERNAME_LENGTH + 1;\n  TCHAR hostname[COUNT] = {'\\0'};\n  DWORD DWCOUNT = COUNT;\n  if (!GetComputerName(hostname, &DWCOUNT)) return std::string(\"\");\n#ifndef UNICODE\n  str = std::string(hostname, DWCOUNT);\n#else\n  // `WideCharToMultiByte` returns `0` when conversion fails.\n  int len = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, hostname,\n                                DWCOUNT, NULL, 0, NULL, NULL);\n  str.resize(len);\n  WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, hostname, DWCOUNT, &str[0],\n                      str.size(), NULL, NULL);\n#endif\n  return str;\n#elif defined(BENCHMARK_OS_QURT)\n  std::string str = \"Hexagon DSP\";\n  qurt_arch_version_t arch_version_struct;\n  if (qurt_sysenv_get_arch_version(&arch_version_struct) == QURT_EOK) {\n    str += \" v\";\n    str += std::to_string(arch_version_struct.arch_version);\n  }\n  return str;\n#else\n#ifndef HOST_NAME_MAX\n#ifdef BENCHMARK_HAS_SYSCTL  // BSD/Mac doesn't have HOST_NAME_MAX defined\n#define HOST_NAME_MAX 64\n#elif defined(BENCHMARK_OS_NACL)\n#define HOST_NAME_MAX 64\n#elif defined(BENCHMARK_OS_QNX)\n#define HOST_NAME_MAX 154\n#elif defined(BENCHMARK_OS_RTEMS)\n#define HOST_NAME_MAX 256\n#elif defined(BENCHMARK_OS_SOLARIS)\n#define HOST_NAME_MAX MAXHOSTNAMELEN\n#else\n#pragma message(\"HOST_NAME_MAX not defined. using 64\")\n#define HOST_NAME_MAX 64\n#endif\n#endif  // def HOST_NAME_MAX\n  char hostname[HOST_NAME_MAX];\n  int retVal = gethostname(hostname, HOST_NAME_MAX);\n  if (retVal != 0) return std::string(\"\");\n  return std::string(hostname);\n#endif  // Catch-all POSIX block.\n}\n\nint GetNumCPUs() {\n#ifdef BENCHMARK_HAS_SYSCTL\n  int num_cpu = -1;\n  if (GetSysctl(\"hw.ncpu\", &num_cpu)) return num_cpu;\n  fprintf(stderr, \"Err: %s\\n\", strerror(errno));\n  std::exit(EXIT_FAILURE);\n#elif defined(BENCHMARK_OS_WINDOWS)\n  SYSTEM_INFO sysinfo;\n  // Use memset as opposed to = {} to avoid GCC missing initializer false\n  // positives.\n  std::memset(&sysinfo, 0, sizeof(SYSTEM_INFO));\n  GetSystemInfo(&sysinfo);\n  return sysinfo.dwNumberOfProcessors;  // number of logical\n                                        // processors in the current\n                                        // group\n#elif defined(BENCHMARK_OS_SOLARIS)\n  // Returns -1 in case of a failure.\n  long num_cpu = sysconf(_SC_NPROCESSORS_ONLN);\n  if (num_cpu < 0) {\n    fprintf(stderr, \"sysconf(_SC_NPROCESSORS_ONLN) failed with error: %s\\n\",\n            strerror(errno));\n  }\n  return (int)num_cpu;\n#elif defined(BENCHMARK_OS_QNX)\n  return static_cast<int>(_syspage_ptr->num_cpu);\n#elif defined(BENCHMARK_OS_QURT)\n  qurt_sysenv_max_hthreads_t hardware_threads;\n  if (qurt_sysenv_get_max_hw_threads(&hardware_threads) != QURT_EOK) {\n    hardware_threads.max_hthreads = 1;\n  }\n  return hardware_threads.max_hthreads;\n#else\n  int num_cpus = 0;\n  int max_id = -1;\n  std::ifstream f(\"/proc/cpuinfo\");\n  if (!f.is_open()) {\n    std::cerr << \"failed to open /proc/cpuinfo\\n\";\n    return -1;\n  }\n  const std::string Key = \"processor\";\n  std::string ln;\n  while (std::getline(f, ln)) {\n    if (ln.empty()) continue;\n    std::size_t split_idx = ln.find(':');\n    std::string value;\n#if defined(__s390__)\n    // s390 has another format in /proc/cpuinfo\n    // it needs to be parsed differently\n    if (split_idx != std::string::npos)\n      value = ln.substr(Key.size() + 1, split_idx - Key.size() - 1);\n#else\n    if (split_idx != std::string::npos) value = ln.substr(split_idx + 1);\n#endif\n    if (ln.size() >= Key.size() && ln.compare(0, Key.size(), Key) == 0) {\n      num_cpus++;\n      if (!value.empty()) {\n        const int cur_id = benchmark::stoi(value);\n        max_id = std::max(cur_id, max_id);\n      }\n    }\n  }\n  if (f.bad()) {\n    std::cerr << \"Failure reading /proc/cpuinfo\\n\";\n    return -1;\n  }\n  if (!f.eof()) {\n    std::cerr << \"Failed to read to end of /proc/cpuinfo\\n\";\n    return -1;\n  }\n  f.close();\n\n  if ((max_id + 1) != num_cpus) {\n    fprintf(stderr,\n            \"CPU ID assignments in /proc/cpuinfo seem messed up.\"\n            \" This is usually caused by a bad BIOS.\\n\");\n  }\n  return num_cpus;\n#endif\n  BENCHMARK_UNREACHABLE();\n}\n\nclass ThreadAffinityGuard final {\n public:\n  ThreadAffinityGuard() : reset_affinity(SetAffinity()) {\n    if (!reset_affinity)\n      std::cerr << \"***WARNING*** Failed to set thread affinity. Estimated CPU \"\n                   \"frequency may be incorrect.\"\n                << std::endl;\n  }\n\n  ~ThreadAffinityGuard() {\n    if (!reset_affinity) return;\n\n#if defined(BENCHMARK_HAS_PTHREAD_AFFINITY)\n    int ret = pthread_setaffinity_np(self, sizeof(previous_affinity),\n                                     &previous_affinity);\n    if (ret == 0) return;\n#elif defined(BENCHMARK_OS_WINDOWS_WIN32)\n    DWORD_PTR ret = SetThreadAffinityMask(self, previous_affinity);\n    if (ret != 0) return;\n#endif  // def BENCHMARK_HAS_PTHREAD_AFFINITY\n    PrintErrorAndDie(\"Failed to reset thread affinity\");\n  }\n\n  ThreadAffinityGuard(ThreadAffinityGuard&&) = delete;\n  ThreadAffinityGuard(const ThreadAffinityGuard&) = delete;\n  ThreadAffinityGuard& operator=(ThreadAffinityGuard&&) = delete;\n  ThreadAffinityGuard& operator=(const ThreadAffinityGuard&) = delete;\n\n private:\n  bool SetAffinity() {\n#if defined(BENCHMARK_HAS_PTHREAD_AFFINITY)\n    int ret;\n    self = pthread_self();\n    ret = pthread_getaffinity_np(self, sizeof(previous_affinity),\n                                 &previous_affinity);\n    if (ret != 0) return false;\n\n    cpu_set_t affinity;\n    memcpy(&affinity, &previous_affinity, sizeof(affinity));\n\n    bool is_first_cpu = true;\n\n    for (int i = 0; i < CPU_SETSIZE; ++i)\n      if (CPU_ISSET(i, &affinity)) {\n        if (is_first_cpu)\n          is_first_cpu = false;\n        else\n          CPU_CLR(i, &affinity);\n      }\n\n    if (is_first_cpu) return false;\n\n    ret = pthread_setaffinity_np(self, sizeof(affinity), &affinity);\n    return ret == 0;\n#elif defined(BENCHMARK_OS_WINDOWS_WIN32)\n    self = GetCurrentThread();\n    DWORD_PTR mask = static_cast<DWORD_PTR>(1) << GetCurrentProcessorNumber();\n    previous_affinity = SetThreadAffinityMask(self, mask);\n    return previous_affinity != 0;\n#else\n    return false;\n#endif  // def BENCHMARK_HAS_PTHREAD_AFFINITY\n  }\n\n#if defined(BENCHMARK_HAS_PTHREAD_AFFINITY)\n  pthread_t self;\n  cpu_set_t previous_affinity;\n#elif defined(BENCHMARK_OS_WINDOWS_WIN32)\n  HANDLE self;\n  DWORD_PTR previous_affinity;\n#endif  // def BENCHMARK_HAS_PTHREAD_AFFINITY\n  bool reset_affinity;\n};\n\ndouble GetCPUCyclesPerSecond(CPUInfo::Scaling scaling) {\n  // Currently, scaling is only used on linux path here,\n  // suppress diagnostics about it being unused on other paths.\n  (void)scaling;\n\n#if defined BENCHMARK_OS_LINUX || defined BENCHMARK_OS_CYGWIN\n  long freq;\n\n  // If the kernel is exporting the tsc frequency use that. There are issues\n  // where cpuinfo_max_freq cannot be relied on because the BIOS may be\n  // exporintg an invalid p-state (on x86) or p-states may be used to put the\n  // processor in a new mode (turbo mode). Essentially, those frequencies\n  // cannot always be relied upon. The same reasons apply to /proc/cpuinfo as\n  // well.\n  if (ReadFromFile(\"/sys/devices/system/cpu/cpu0/tsc_freq_khz\", &freq)\n      // If CPU scaling is disabled, use the *current* frequency.\n      // Note that we specifically don't want to read cpuinfo_cur_freq,\n      // because it is only readable by root.\n      || (scaling == CPUInfo::Scaling::DISABLED &&\n          ReadFromFile(\"/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq\",\n                       &freq))\n      // Otherwise, if CPU scaling may be in effect, we want to use\n      // the *maximum* frequency, not whatever CPU speed some random processor\n      // happens to be using now.\n      || ReadFromFile(\"/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq\",\n                      &freq)) {\n    // The value is in kHz (as the file name suggests).  For example, on a\n    // 2GHz warpstation, the file contains the value \"2000000\".\n    return freq * 1000.0;\n  }\n\n  const double error_value = -1;\n  double bogo_clock = error_value;\n\n  std::ifstream f(\"/proc/cpuinfo\");\n  if (!f.is_open()) {\n    std::cerr << \"failed to open /proc/cpuinfo\\n\";\n    return error_value;\n  }\n\n  auto StartsWithKey = [](std::string const& Value, std::string const& Key) {\n    if (Key.size() > Value.size()) return false;\n    auto Cmp = [&](char X, char Y) {\n      return std::tolower(X) == std::tolower(Y);\n    };\n    return std::equal(Key.begin(), Key.end(), Value.begin(), Cmp);\n  };\n\n  std::string ln;\n  while (std::getline(f, ln)) {\n    if (ln.empty()) continue;\n    std::size_t split_idx = ln.find(':');\n    std::string value;\n    if (split_idx != std::string::npos) value = ln.substr(split_idx + 1);\n    // When parsing the \"cpu MHz\" and \"bogomips\" (fallback) entries, we only\n    // accept positive values. Some environments (virtual machines) report zero,\n    // which would cause infinite looping in WallTime_Init.\n    if (StartsWithKey(ln, \"cpu MHz\")) {\n      if (!value.empty()) {\n        double cycles_per_second = benchmark::stod(value) * 1000000.0;\n        if (cycles_per_second > 0) return cycles_per_second;\n      }\n    } else if (StartsWithKey(ln, \"bogomips\")) {\n      if (!value.empty()) {\n        bogo_clock = benchmark::stod(value) * 1000000.0;\n        if (bogo_clock < 0.0) bogo_clock = error_value;\n      }\n    }\n  }\n  if (f.bad()) {\n    std::cerr << \"Failure reading /proc/cpuinfo\\n\";\n    return error_value;\n  }\n  if (!f.eof()) {\n    std::cerr << \"Failed to read to end of /proc/cpuinfo\\n\";\n    return error_value;\n  }\n  f.close();\n  // If we found the bogomips clock, but nothing better, we'll use it (but\n  // we're not happy about it); otherwise, fallback to the rough estimation\n  // below.\n  if (bogo_clock >= 0.0) return bogo_clock;\n\n#elif defined BENCHMARK_HAS_SYSCTL\n  constexpr auto* freqStr =\n#if defined(BENCHMARK_OS_FREEBSD) || defined(BENCHMARK_OS_NETBSD)\n      \"machdep.tsc_freq\";\n#elif defined BENCHMARK_OS_OPENBSD\n      \"hw.cpuspeed\";\n#elif defined BENCHMARK_OS_DRAGONFLY\n      \"hw.tsc_frequency\";\n#else\n      \"hw.cpufrequency\";\n#endif\n  unsigned long long hz = 0;\n#if defined BENCHMARK_OS_OPENBSD\n  if (GetSysctl(freqStr, &hz)) return hz * 1000000;\n#else\n  if (GetSysctl(freqStr, &hz)) return hz;\n#endif\n  fprintf(stderr, \"Unable to determine clock rate from sysctl: %s: %s\\n\",\n          freqStr, strerror(errno));\n  fprintf(stderr,\n          \"This does not affect benchmark measurements, only the \"\n          \"metadata output.\\n\");\n\n#elif defined BENCHMARK_OS_WINDOWS_WIN32\n  // In NT, read MHz from the registry. If we fail to do so or we're in win9x\n  // then make a crude estimate.\n  DWORD data, data_size = sizeof(data);\n  if (IsWindowsXPOrGreater() &&\n      SUCCEEDED(\n          SHGetValueA(HKEY_LOCAL_MACHINE,\n                      \"HARDWARE\\\\DESCRIPTION\\\\System\\\\CentralProcessor\\\\0\",\n                      \"~MHz\", nullptr, &data, &data_size)))\n    return static_cast<double>((int64_t)data *\n                               (int64_t)(1000 * 1000));  // was mhz\n#elif defined(BENCHMARK_OS_SOLARIS)\n  kstat_ctl_t* kc = kstat_open();\n  if (!kc) {\n    std::cerr << \"failed to open /dev/kstat\\n\";\n    return -1;\n  }\n  kstat_t* ksp = kstat_lookup(kc, const_cast<char*>(\"cpu_info\"), -1,\n                              const_cast<char*>(\"cpu_info0\"));\n  if (!ksp) {\n    std::cerr << \"failed to lookup in /dev/kstat\\n\";\n    return -1;\n  }\n  if (kstat_read(kc, ksp, NULL) < 0) {\n    std::cerr << \"failed to read from /dev/kstat\\n\";\n    return -1;\n  }\n  kstat_named_t* knp = (kstat_named_t*)kstat_data_lookup(\n      ksp, const_cast<char*>(\"current_clock_Hz\"));\n  if (!knp) {\n    std::cerr << \"failed to lookup data in /dev/kstat\\n\";\n    return -1;\n  }\n  if (knp->data_type != KSTAT_DATA_UINT64) {\n    std::cerr << \"current_clock_Hz is of unexpected data type: \"\n              << knp->data_type << \"\\n\";\n    return -1;\n  }\n  double clock_hz = knp->value.ui64;\n  kstat_close(kc);\n  return clock_hz;\n#elif defined(BENCHMARK_OS_QNX)\n  return static_cast<double>((int64_t)(SYSPAGE_ENTRY(cpuinfo)->speed) *\n                             (int64_t)(1000 * 1000));\n#elif defined(BENCHMARK_OS_QURT)\n  // QuRT doesn't provide any API to query Hexagon frequency.\n  return 1000000000;\n#endif\n  // If we've fallen through, attempt to roughly estimate the CPU clock rate.\n\n  // Make sure to use the same cycle counter when starting and stopping the\n  // cycle timer. We just pin the current thread to a cpu in the previous\n  // affinity set.\n  ThreadAffinityGuard affinity_guard;\n\n  static constexpr double estimate_time_s = 1.0;\n  const double start_time = ChronoClockNow();\n  const auto start_ticks = cycleclock::Now();\n\n  // Impose load instead of calling sleep() to make sure the cycle counter\n  // works.\n  using PRNG = std::minstd_rand;\n  using Result = PRNG::result_type;\n  PRNG rng(static_cast<Result>(start_ticks));\n\n  Result state = 0;\n\n  do {\n    static constexpr size_t batch_size = 10000;\n    rng.discard(batch_size);\n    state += rng();\n\n  } while (ChronoClockNow() - start_time < estimate_time_s);\n\n  DoNotOptimize(state);\n\n  const auto end_ticks = cycleclock::Now();\n  const double end_time = ChronoClockNow();\n\n  return static_cast<double>(end_ticks - start_ticks) / (end_time - start_time);\n  // Reset the affinity of current thread when the lifetime of affinity_guard\n  // ends.\n}\n\nstd::vector<double> GetLoadAvg() {\n#if (defined BENCHMARK_OS_FREEBSD || defined(BENCHMARK_OS_LINUX) ||     \\\n     defined BENCHMARK_OS_MACOSX || defined BENCHMARK_OS_NETBSD ||      \\\n     defined BENCHMARK_OS_OPENBSD || defined BENCHMARK_OS_DRAGONFLY) && \\\n    !defined(__ANDROID__)\n  static constexpr int kMaxSamples = 3;\n  std::vector<double> res(kMaxSamples, 0.0);\n  const int nelem = getloadavg(res.data(), kMaxSamples);\n  if (nelem < 1) {\n    res.clear();\n  } else {\n    res.resize(nelem);\n  }\n  return res;\n#else\n  return {};\n#endif\n}\n\n}  // end namespace\n\nconst CPUInfo& CPUInfo::Get() {\n  static const CPUInfo* info = new CPUInfo();\n  return *info;\n}\n\nCPUInfo::CPUInfo()\n    : num_cpus(GetNumCPUs()),\n      scaling(CpuScaling(num_cpus)),\n      cycles_per_second(GetCPUCyclesPerSecond(scaling)),\n      caches(GetCacheSizes()),\n      load_avg(GetLoadAvg()) {}\n\nconst SystemInfo& SystemInfo::Get() {\n  static const SystemInfo* info = new SystemInfo();\n  return *info;\n}\n\nSystemInfo::SystemInfo() : name(GetSystemName()) {}\n}  // end namespace benchmark\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/thread_manager.h",
    "content": "#ifndef BENCHMARK_THREAD_MANAGER_H\n#define BENCHMARK_THREAD_MANAGER_H\n\n#include <atomic>\n\n#include \"benchmark/benchmark.h\"\n#include \"mutex.h\"\n\nnamespace benchmark {\nnamespace internal {\n\nclass ThreadManager {\n public:\n  explicit ThreadManager(int num_threads)\n      : alive_threads_(num_threads), start_stop_barrier_(num_threads) {}\n\n  Mutex& GetBenchmarkMutex() const RETURN_CAPABILITY(benchmark_mutex_) {\n    return benchmark_mutex_;\n  }\n\n  bool StartStopBarrier() EXCLUDES(end_cond_mutex_) {\n    return start_stop_barrier_.wait();\n  }\n\n  void NotifyThreadComplete() EXCLUDES(end_cond_mutex_) {\n    start_stop_barrier_.removeThread();\n    if (--alive_threads_ == 0) {\n      MutexLock lock(end_cond_mutex_);\n      end_condition_.notify_all();\n    }\n  }\n\n  void WaitForAllThreads() EXCLUDES(end_cond_mutex_) {\n    MutexLock lock(end_cond_mutex_);\n    end_condition_.wait(lock.native_handle(),\n                        [this]() { return alive_threads_ == 0; });\n  }\n\n  struct Result {\n    IterationCount iterations = 0;\n    double real_time_used = 0;\n    double cpu_time_used = 0;\n    double manual_time_used = 0;\n    int64_t complexity_n = 0;\n    std::string report_label_;\n    std::string skip_message_;\n    internal::Skipped skipped_ = internal::NotSkipped;\n    UserCounters counters;\n  };\n  GUARDED_BY(GetBenchmarkMutex()) Result results;\n\n private:\n  mutable Mutex benchmark_mutex_;\n  std::atomic<int> alive_threads_;\n  Barrier start_stop_barrier_;\n  Mutex end_cond_mutex_;\n  Condition end_condition_;\n};\n\n}  // namespace internal\n}  // namespace benchmark\n\n#endif  // BENCHMARK_THREAD_MANAGER_H\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/thread_timer.h",
    "content": "#ifndef BENCHMARK_THREAD_TIMER_H\n#define BENCHMARK_THREAD_TIMER_H\n\n#include \"check.h\"\n#include \"timers.h\"\n\nnamespace benchmark {\nnamespace internal {\n\nclass ThreadTimer {\n  explicit ThreadTimer(bool measure_process_cpu_time_)\n      : measure_process_cpu_time(measure_process_cpu_time_) {}\n\n public:\n  static ThreadTimer Create() {\n    return ThreadTimer(/*measure_process_cpu_time_=*/false);\n  }\n  static ThreadTimer CreateProcessCpuTime() {\n    return ThreadTimer(/*measure_process_cpu_time_=*/true);\n  }\n\n  // Called by each thread\n  void StartTimer() {\n    running_ = true;\n    start_real_time_ = ChronoClockNow();\n    start_cpu_time_ = ReadCpuTimerOfChoice();\n  }\n\n  // Called by each thread\n  void StopTimer() {\n    BM_CHECK(running_);\n    running_ = false;\n    real_time_used_ += ChronoClockNow() - start_real_time_;\n    // Floating point error can result in the subtraction producing a negative\n    // time. Guard against that.\n    cpu_time_used_ +=\n        std::max<double>(ReadCpuTimerOfChoice() - start_cpu_time_, 0);\n  }\n\n  // Called by each thread\n  void SetIterationTime(double seconds) { manual_time_used_ += seconds; }\n\n  bool running() const { return running_; }\n\n  // REQUIRES: timer is not running\n  double real_time_used() const {\n    BM_CHECK(!running_);\n    return real_time_used_;\n  }\n\n  // REQUIRES: timer is not running\n  double cpu_time_used() const {\n    BM_CHECK(!running_);\n    return cpu_time_used_;\n  }\n\n  // REQUIRES: timer is not running\n  double manual_time_used() const {\n    BM_CHECK(!running_);\n    return manual_time_used_;\n  }\n\n private:\n  double ReadCpuTimerOfChoice() const {\n    if (measure_process_cpu_time) return ProcessCPUUsage();\n    return ThreadCPUUsage();\n  }\n\n  // should the thread, or the process, time be measured?\n  const bool measure_process_cpu_time;\n\n  bool running_ = false;        // Is the timer running\n  double start_real_time_ = 0;  // If running_\n  double start_cpu_time_ = 0;   // If running_\n\n  // Accumulated time so far (does not contain current slice if running_)\n  double real_time_used_ = 0;\n  double cpu_time_used_ = 0;\n  // Manually set iteration time. User sets this with SetIterationTime(seconds).\n  double manual_time_used_ = 0;\n};\n\n}  // namespace internal\n}  // namespace benchmark\n\n#endif  // BENCHMARK_THREAD_TIMER_H\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/timers.cc",
    "content": "// Copyright 2015 Google Inc. All rights reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n//     http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#include \"timers.h\"\n\n#include \"internal_macros.h\"\n\n#ifdef BENCHMARK_OS_WINDOWS\n#include <shlwapi.h>\n#undef StrCat  // Don't let StrCat in string_util.h be renamed to lstrcatA\n#include <versionhelpers.h>\n#include <windows.h>\n#else\n#include <fcntl.h>\n#if !defined(BENCHMARK_OS_FUCHSIA) && !defined(BENCHMARK_OS_QURT)\n#include <sys/resource.h>\n#endif\n#include <sys/time.h>\n#include <sys/types.h>  // this header must be included before 'sys/sysctl.h' to avoid compilation error on FreeBSD\n#include <unistd.h>\n#if defined BENCHMARK_OS_FREEBSD || defined BENCHMARK_OS_DRAGONFLY || \\\n    defined BENCHMARK_OS_MACOSX\n#include <sys/sysctl.h>\n#endif\n#if defined(BENCHMARK_OS_MACOSX)\n#include <mach/mach_init.h>\n#include <mach/mach_port.h>\n#include <mach/thread_act.h>\n#endif\n#if defined(BENCHMARK_OS_QURT)\n#include <qurt.h>\n#endif\n#endif\n\n#ifdef BENCHMARK_OS_EMSCRIPTEN\n#include <emscripten.h>\n#endif\n\n#include <cerrno>\n#include <cstdint>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <ctime>\n#include <iostream>\n#include <limits>\n#include <mutex>\n\n#include \"check.h\"\n#include \"log.h\"\n#include \"string_util.h\"\n\nnamespace benchmark {\n\n// Suppress unused warnings on helper functions.\n#if defined(__GNUC__)\n#pragma GCC diagnostic ignored \"-Wunused-function\"\n#endif\n#if defined(__NVCOMPILER)\n#pragma diag_suppress declared_but_not_referenced\n#endif\n\nnamespace {\n#if defined(BENCHMARK_OS_WINDOWS)\ndouble MakeTime(FILETIME const& kernel_time, FILETIME const& user_time) {\n  ULARGE_INTEGER kernel;\n  ULARGE_INTEGER user;\n  kernel.HighPart = kernel_time.dwHighDateTime;\n  kernel.LowPart = kernel_time.dwLowDateTime;\n  user.HighPart = user_time.dwHighDateTime;\n  user.LowPart = user_time.dwLowDateTime;\n  return (static_cast<double>(kernel.QuadPart) +\n          static_cast<double>(user.QuadPart)) *\n         1e-7;\n}\n#elif !defined(BENCHMARK_OS_FUCHSIA) && !defined(BENCHMARK_OS_QURT)\ndouble MakeTime(struct rusage const& ru) {\n  return (static_cast<double>(ru.ru_utime.tv_sec) +\n          static_cast<double>(ru.ru_utime.tv_usec) * 1e-6 +\n          static_cast<double>(ru.ru_stime.tv_sec) +\n          static_cast<double>(ru.ru_stime.tv_usec) * 1e-6);\n}\n#endif\n#if defined(BENCHMARK_OS_MACOSX)\ndouble MakeTime(thread_basic_info_data_t const& info) {\n  return (static_cast<double>(info.user_time.seconds) +\n          static_cast<double>(info.user_time.microseconds) * 1e-6 +\n          static_cast<double>(info.system_time.seconds) +\n          static_cast<double>(info.system_time.microseconds) * 1e-6);\n}\n#endif\n#if defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_THREAD_CPUTIME_ID)\ndouble MakeTime(struct timespec const& ts) {\n  return ts.tv_sec + (static_cast<double>(ts.tv_nsec) * 1e-9);\n}\n#endif\n\nBENCHMARK_NORETURN static void DiagnoseAndExit(const char* msg) {\n  std::cerr << \"ERROR: \" << msg << std::endl;\n  std::exit(EXIT_FAILURE);\n}\n\n}  // end namespace\n\ndouble ProcessCPUUsage() {\n#if defined(BENCHMARK_OS_WINDOWS)\n  HANDLE proc = GetCurrentProcess();\n  FILETIME creation_time;\n  FILETIME exit_time;\n  FILETIME kernel_time;\n  FILETIME user_time;\n  if (GetProcessTimes(proc, &creation_time, &exit_time, &kernel_time,\n                      &user_time))\n    return MakeTime(kernel_time, user_time);\n  DiagnoseAndExit(\"GetProccessTimes() failed\");\n#elif defined(BENCHMARK_OS_QURT)\n  return static_cast<double>(\n             qurt_timer_timetick_to_us(qurt_timer_get_ticks())) *\n         1.0e-6;\n#elif defined(BENCHMARK_OS_EMSCRIPTEN)\n  // clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ...) returns 0 on Emscripten.\n  // Use Emscripten-specific API. Reported CPU time would be exactly the\n  // same as total time, but this is ok because there aren't long-latency\n  // synchronous system calls in Emscripten.\n  return emscripten_get_now() * 1e-3;\n#elif defined(CLOCK_PROCESS_CPUTIME_ID) && !defined(BENCHMARK_OS_MACOSX)\n  // FIXME We want to use clock_gettime, but its not available in MacOS 10.11.\n  // See https://github.com/google/benchmark/pull/292\n  struct timespec spec;\n  if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &spec) == 0)\n    return MakeTime(spec);\n  DiagnoseAndExit(\"clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ...) failed\");\n#else\n  struct rusage ru;\n  if (getrusage(RUSAGE_SELF, &ru) == 0) return MakeTime(ru);\n  DiagnoseAndExit(\"getrusage(RUSAGE_SELF, ...) failed\");\n#endif\n}\n\ndouble ThreadCPUUsage() {\n#if defined(BENCHMARK_OS_WINDOWS)\n  HANDLE this_thread = GetCurrentThread();\n  FILETIME creation_time;\n  FILETIME exit_time;\n  FILETIME kernel_time;\n  FILETIME user_time;\n  GetThreadTimes(this_thread, &creation_time, &exit_time, &kernel_time,\n                 &user_time);\n  return MakeTime(kernel_time, user_time);\n#elif defined(BENCHMARK_OS_QURT)\n  return static_cast<double>(\n             qurt_timer_timetick_to_us(qurt_timer_get_ticks())) *\n         1.0e-6;\n#elif defined(BENCHMARK_OS_MACOSX)\n  // FIXME We want to use clock_gettime, but its not available in MacOS 10.11.\n  // See https://github.com/google/benchmark/pull/292\n  mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT;\n  thread_basic_info_data_t info;\n  mach_port_t thread = pthread_mach_thread_np(pthread_self());\n  if (thread_info(thread, THREAD_BASIC_INFO,\n                  reinterpret_cast<thread_info_t>(&info),\n                  &count) == KERN_SUCCESS) {\n    return MakeTime(info);\n  }\n  DiagnoseAndExit(\"ThreadCPUUsage() failed when evaluating thread_info\");\n#elif defined(BENCHMARK_OS_EMSCRIPTEN)\n  // Emscripten doesn't support traditional threads\n  return ProcessCPUUsage();\n#elif defined(BENCHMARK_OS_RTEMS)\n  // RTEMS doesn't support CLOCK_THREAD_CPUTIME_ID. See\n  // https://github.com/RTEMS/rtems/blob/master/cpukit/posix/src/clockgettime.c\n  return ProcessCPUUsage();\n#elif defined(BENCHMARK_OS_SOLARIS)\n  struct rusage ru;\n  if (getrusage(RUSAGE_LWP, &ru) == 0) return MakeTime(ru);\n  DiagnoseAndExit(\"getrusage(RUSAGE_LWP, ...) failed\");\n#elif defined(CLOCK_THREAD_CPUTIME_ID)\n  struct timespec ts;\n  if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts) == 0) return MakeTime(ts);\n  DiagnoseAndExit(\"clock_gettime(CLOCK_THREAD_CPUTIME_ID, ...) failed\");\n#else\n#error Per-thread timing is not available on your system.\n#endif\n}\n\nstd::string LocalDateTimeString() {\n  // Write the local time in RFC3339 format yyyy-mm-ddTHH:MM:SS+/-HH:MM.\n  typedef std::chrono::system_clock Clock;\n  std::time_t now = Clock::to_time_t(Clock::now());\n  const std::size_t kTzOffsetLen = 6;\n  const std::size_t kTimestampLen = 19;\n\n  std::size_t tz_len;\n  std::size_t timestamp_len;\n  long int offset_minutes;\n  char tz_offset_sign = '+';\n  // tz_offset is set in one of three ways:\n  // * strftime with %z - This either returns empty or the ISO 8601 time.  The\n  // maximum length an\n  //   ISO 8601 string can be is 7 (e.g. -03:30, plus trailing zero).\n  // * snprintf with %c%02li:%02li - The maximum length is 41 (one for %c, up to\n  // 19 for %02li,\n  //   one for :, up to 19 %02li, plus trailing zero).\n  // * A fixed string of \"-00:00\".  The maximum length is 7 (-00:00, plus\n  // trailing zero).\n  //\n  // Thus, the maximum size this needs to be is 41.\n  char tz_offset[41];\n  // Long enough buffer to avoid format-overflow warnings\n  char storage[128];\n\n#if defined(BENCHMARK_OS_WINDOWS)\n  std::tm* timeinfo_p = ::localtime(&now);\n#else\n  std::tm timeinfo;\n  std::tm* timeinfo_p = &timeinfo;\n  ::localtime_r(&now, &timeinfo);\n#endif\n\n  tz_len = std::strftime(tz_offset, sizeof(tz_offset), \"%z\", timeinfo_p);\n\n  if (tz_len < kTzOffsetLen && tz_len > 1) {\n    // Timezone offset was written. strftime writes offset as +HHMM or -HHMM,\n    // RFC3339 specifies an offset as +HH:MM or -HH:MM. To convert, we parse\n    // the offset as an integer, then reprint it to a string.\n\n    offset_minutes = ::strtol(tz_offset, NULL, 10);\n    if (offset_minutes < 0) {\n      offset_minutes *= -1;\n      tz_offset_sign = '-';\n    }\n\n    tz_len =\n        ::snprintf(tz_offset, sizeof(tz_offset), \"%c%02li:%02li\",\n                   tz_offset_sign, offset_minutes / 100, offset_minutes % 100);\n    BM_CHECK(tz_len == kTzOffsetLen);\n    ((void)tz_len);  // Prevent unused variable warning in optimized build.\n  } else {\n    // Unknown offset. RFC3339 specifies that unknown local offsets should be\n    // written as UTC time with -00:00 timezone.\n#if defined(BENCHMARK_OS_WINDOWS)\n    // Potential race condition if another thread calls localtime or gmtime.\n    timeinfo_p = ::gmtime(&now);\n#else\n    ::gmtime_r(&now, &timeinfo);\n#endif\n\n    strncpy(tz_offset, \"-00:00\", kTzOffsetLen + 1);\n  }\n\n  timestamp_len =\n      std::strftime(storage, sizeof(storage), \"%Y-%m-%dT%H:%M:%S\", timeinfo_p);\n  BM_CHECK(timestamp_len == kTimestampLen);\n  // Prevent unused variable warning in optimized build.\n  ((void)kTimestampLen);\n\n  std::strncat(storage, tz_offset, sizeof(storage) - timestamp_len - 1);\n  return std::string(storage);\n}\n\n}  // end namespace benchmark\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/src/timers.h",
    "content": "#ifndef BENCHMARK_TIMERS_H\n#define BENCHMARK_TIMERS_H\n\n#include <chrono>\n#include <string>\n\nnamespace benchmark {\n\n// Return the CPU usage of the current process\ndouble ProcessCPUUsage();\n\n// Return the CPU usage of the children of the current process\ndouble ChildrenCPUUsage();\n\n// Return the CPU usage of the current thread\ndouble ThreadCPUUsage();\n\n#if defined(HAVE_STEADY_CLOCK)\ntemplate <bool HighResIsSteady = std::chrono::high_resolution_clock::is_steady>\nstruct ChooseSteadyClock {\n  typedef std::chrono::high_resolution_clock type;\n};\n\ntemplate <>\nstruct ChooseSteadyClock<false> {\n  typedef std::chrono::steady_clock type;\n};\n#endif\n\nstruct ChooseClockType {\n#if defined(HAVE_STEADY_CLOCK)\n  typedef ChooseSteadyClock<>::type type;\n#else\n  typedef std::chrono::high_resolution_clock type;\n#endif\n};\n\ninline double ChronoClockNow() {\n  typedef ChooseClockType::type ClockType;\n  using FpSeconds = std::chrono::duration<double, std::chrono::seconds::period>;\n  return FpSeconds(ClockType::now().time_since_epoch()).count();\n}\n\nstd::string LocalDateTimeString();\n\n}  // end namespace benchmark\n\n#endif  // BENCHMARK_TIMERS_H\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/BUILD",
    "content": "load(\"@rules_cc//cc:defs.bzl\", \"cc_library\", \"cc_test\")\n\nplatform(\n    name = \"windows\",\n    constraint_values = [\n        \"@platforms//os:windows\",\n    ],\n)\n\nTEST_COPTS = [\n    \"-pedantic\",\n    \"-pedantic-errors\",\n    \"-std=c++11\",\n    \"-Wall\",\n    \"-Wconversion\",\n    \"-Wextra\",\n    \"-Wshadow\",\n    #    \"-Wshorten-64-to-32\",\n    \"-Wfloat-equal\",\n    \"-fstrict-aliasing\",\n]\n\n# Some of the issues with DoNotOptimize only occur when optimization is enabled\nPER_SRC_COPTS = {\n    \"donotoptimize_test.cc\": [\"-O3\"],\n}\n\nTEST_ARGS = [\"--benchmark_min_time=0.01s\"]\n\nPER_SRC_TEST_ARGS = {\n    \"user_counters_tabular_test.cc\": [\"--benchmark_counters_tabular=true\"],\n    \"repetitions_test.cc\": [\" --benchmark_repetitions=3\"],\n    \"spec_arg_test.cc\": [\"--benchmark_filter=BM_NotChosen\"],\n    \"spec_arg_verbosity_test.cc\": [\"--v=42\"],\n}\n\ncc_library(\n    name = \"output_test_helper\",\n    testonly = 1,\n    srcs = [\"output_test_helper.cc\"],\n    hdrs = [\"output_test.h\"],\n    copts = select({\n        \"//:windows\": [],\n        \"//conditions:default\": TEST_COPTS,\n    }),\n    deps = [\n        \"//:benchmark\",\n        \"//:benchmark_internal_headers\",\n    ],\n)\n\n[\n    cc_test(\n        name = test_src[:-len(\".cc\")],\n        size = \"small\",\n        srcs = [test_src],\n        args = TEST_ARGS + PER_SRC_TEST_ARGS.get(test_src, []),\n        copts = select({\n            \"//:windows\": [],\n            \"//conditions:default\": TEST_COPTS,\n        }) + PER_SRC_COPTS.get(test_src, []),\n        deps = [\n            \":output_test_helper\",\n            \"//:benchmark\",\n            \"//:benchmark_internal_headers\",\n            \"@com_google_googletest//:gtest\",\n            \"@com_google_googletest//:gtest_main\",\n        ],\n        # FIXME: Add support for assembly tests to bazel.\n        # See Issue #556\n        # https://github.com/google/benchmark/issues/556\n    )\n    for test_src in glob(\n        [\"*test.cc\"],\n        exclude = [\n            \"*_assembly_test.cc\",\n            \"cxx03_test.cc\",\n            \"link_main_test.cc\",\n        ],\n    )\n]\n\ncc_test(\n    name = \"cxx03_test\",\n    size = \"small\",\n    srcs = [\"cxx03_test.cc\"],\n    copts = TEST_COPTS + [\"-std=c++03\"],\n    target_compatible_with = select({\n        \"//:windows\": [\"@platforms//:incompatible\"],\n        \"//conditions:default\": [],\n    }),\n    deps = [\n        \":output_test_helper\",\n        \"//:benchmark\",\n        \"//:benchmark_internal_headers\",\n        \"@com_google_googletest//:gtest\",\n        \"@com_google_googletest//:gtest_main\",\n    ],\n)\n\ncc_test(\n    name = \"link_main_test\",\n    size = \"small\",\n    srcs = [\"link_main_test.cc\"],\n    copts = select({\n        \"//:windows\": [],\n        \"//conditions:default\": TEST_COPTS,\n    }),\n    deps = [\"//:benchmark_main\"],\n)\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/CMakeLists.txt",
    "content": "# Enable the tests\n\nset(THREADS_PREFER_PTHREAD_FLAG ON)\n\nfind_package(Threads REQUIRED)\ninclude(CheckCXXCompilerFlag)\n\n# NOTE: Some tests use `<cassert>` to perform the test. Therefore we must\n# strip -DNDEBUG from the default CMake flags in DEBUG mode.\nstring(TOUPPER \"${CMAKE_BUILD_TYPE}\" uppercase_CMAKE_BUILD_TYPE)\nif( NOT uppercase_CMAKE_BUILD_TYPE STREQUAL \"DEBUG\" )\n  add_definitions( -UNDEBUG )\n  add_definitions(-DTEST_BENCHMARK_LIBRARY_HAS_NO_ASSERTIONS)\n  # Also remove /D NDEBUG to avoid MSVC warnings about conflicting defines.\n  foreach (flags_var_to_scrub\n      CMAKE_CXX_FLAGS_RELEASE\n      CMAKE_CXX_FLAGS_RELWITHDEBINFO\n      CMAKE_CXX_FLAGS_MINSIZEREL\n      CMAKE_C_FLAGS_RELEASE\n      CMAKE_C_FLAGS_RELWITHDEBINFO\n      CMAKE_C_FLAGS_MINSIZEREL)\n    string (REGEX REPLACE \"(^| )[/-]D *NDEBUG($| )\" \" \"\n      \"${flags_var_to_scrub}\" \"${${flags_var_to_scrub}}\")\n  endforeach()\nendif()\n\nif (NOT BUILD_SHARED_LIBS)\n  add_definitions(-DBENCHMARK_STATIC_DEFINE)\nendif()\n\ncheck_cxx_compiler_flag(-O3 BENCHMARK_HAS_O3_FLAG)\nset(BENCHMARK_O3_FLAG \"\")\nif (BENCHMARK_HAS_O3_FLAG)\n  set(BENCHMARK_O3_FLAG \"-O3\")\nendif()\n\n# NOTE: These flags must be added after find_package(Threads REQUIRED) otherwise\n# they will break the configuration check.\nif (DEFINED BENCHMARK_CXX_LINKER_FLAGS)\n  list(APPEND CMAKE_EXE_LINKER_FLAGS ${BENCHMARK_CXX_LINKER_FLAGS})\nendif()\n\nadd_library(output_test_helper STATIC output_test_helper.cc output_test.h)\ntarget_link_libraries(output_test_helper PRIVATE benchmark::benchmark)\n\nmacro(compile_benchmark_test name)\n  add_executable(${name} \"${name}.cc\")\n  target_link_libraries(${name} benchmark::benchmark ${CMAKE_THREAD_LIBS_INIT})\n  if(\"${CMAKE_CXX_COMPILER_ID}\" STREQUAL \"NVHPC\")\n  target_compile_options( ${name} PRIVATE --diag_suppress partial_override )\n  endif()\nendmacro(compile_benchmark_test)\n\nmacro(compile_benchmark_test_with_main name)\n  add_executable(${name} \"${name}.cc\")\n  target_link_libraries(${name} benchmark::benchmark_main)\nendmacro(compile_benchmark_test_with_main)\n\nmacro(compile_output_test name)\n  add_executable(${name} \"${name}.cc\" output_test.h)\n  target_link_libraries(${name} output_test_helper benchmark::benchmark_main\n          ${BENCHMARK_CXX_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT})\nendmacro(compile_output_test)\n\n# Demonstration executable\ncompile_benchmark_test(benchmark_test)\nadd_test(NAME benchmark COMMAND benchmark_test --benchmark_min_time=0.01s)\n\ncompile_benchmark_test(spec_arg_test)\nadd_test(NAME spec_arg COMMAND spec_arg_test --benchmark_filter=BM_NotChosen)\n\ncompile_benchmark_test(spec_arg_verbosity_test)\nadd_test(NAME spec_arg_verbosity COMMAND spec_arg_verbosity_test --v=42)\n\ncompile_benchmark_test(benchmark_setup_teardown_test)\nadd_test(NAME benchmark_setup_teardown COMMAND benchmark_setup_teardown_test)\n\ncompile_benchmark_test(filter_test)\nmacro(add_filter_test name filter expect)\n  add_test(NAME ${name} COMMAND filter_test --benchmark_min_time=0.01s --benchmark_filter=${filter} ${expect})\n  add_test(NAME ${name}_list_only COMMAND filter_test --benchmark_list_tests --benchmark_filter=${filter} ${expect})\nendmacro(add_filter_test)\n\ncompile_benchmark_test(benchmark_min_time_flag_time_test)\nadd_test(NAME min_time_flag_time COMMAND benchmark_min_time_flag_time_test)\n\ncompile_benchmark_test(benchmark_min_time_flag_iters_test)\nadd_test(NAME min_time_flag_iters COMMAND benchmark_min_time_flag_iters_test)\n\nadd_filter_test(filter_simple \"Foo\" 3)\nadd_filter_test(filter_simple_negative \"-Foo\" 2)\nadd_filter_test(filter_suffix \"BM_.*\" 4)\nadd_filter_test(filter_suffix_negative \"-BM_.*\" 1)\nadd_filter_test(filter_regex_all \".*\" 5)\nadd_filter_test(filter_regex_all_negative \"-.*\" 0)\nadd_filter_test(filter_regex_blank \"\" 5)\nadd_filter_test(filter_regex_blank_negative \"-\" 0)\nadd_filter_test(filter_regex_none \"monkey\" 0)\nadd_filter_test(filter_regex_none_negative \"-monkey\" 5)\nadd_filter_test(filter_regex_wildcard \".*Foo.*\" 3)\nadd_filter_test(filter_regex_wildcard_negative \"-.*Foo.*\" 2)\nadd_filter_test(filter_regex_begin \"^BM_.*\" 4)\nadd_filter_test(filter_regex_begin_negative \"-^BM_.*\" 1)\nadd_filter_test(filter_regex_begin2 \"^N\" 1)\nadd_filter_test(filter_regex_begin2_negative \"-^N\" 4)\nadd_filter_test(filter_regex_end \".*Ba$\" 1)\nadd_filter_test(filter_regex_end_negative \"-.*Ba$\" 4)\n\ncompile_benchmark_test(options_test)\nadd_test(NAME options_benchmarks COMMAND options_test --benchmark_min_time=0.01s)\n\ncompile_benchmark_test(basic_test)\nadd_test(NAME basic_benchmark COMMAND basic_test --benchmark_min_time=0.01s)\n\ncompile_output_test(repetitions_test)\nadd_test(NAME repetitions_benchmark COMMAND repetitions_test --benchmark_min_time=0.01s --benchmark_repetitions=3)\n\ncompile_benchmark_test(diagnostics_test)\nadd_test(NAME diagnostics_test COMMAND diagnostics_test --benchmark_min_time=0.01s)\n\ncompile_benchmark_test(skip_with_error_test)\nadd_test(NAME skip_with_error_test COMMAND skip_with_error_test --benchmark_min_time=0.01s)\n\ncompile_benchmark_test(donotoptimize_test)\n# Enable errors for deprecated deprecations (DoNotOptimize(Tp const& value)).\ncheck_cxx_compiler_flag(-Werror=deprecated-declarations BENCHMARK_HAS_DEPRECATED_DECLARATIONS_FLAG)\nif (BENCHMARK_HAS_DEPRECATED_DECLARATIONS_FLAG)\n  target_compile_options (donotoptimize_test PRIVATE \"-Werror=deprecated-declarations\")\nendif()\n# Some of the issues with DoNotOptimize only occur when optimization is enabled\ncheck_cxx_compiler_flag(-O3 BENCHMARK_HAS_O3_FLAG)\nif (BENCHMARK_HAS_O3_FLAG)\n  set_target_properties(donotoptimize_test PROPERTIES COMPILE_FLAGS \"-O3\")\nendif()\nadd_test(NAME donotoptimize_test COMMAND donotoptimize_test --benchmark_min_time=0.01s)\n\ncompile_benchmark_test(fixture_test)\nadd_test(NAME fixture_test COMMAND fixture_test --benchmark_min_time=0.01s)\n\ncompile_benchmark_test(register_benchmark_test)\nadd_test(NAME register_benchmark_test COMMAND register_benchmark_test --benchmark_min_time=0.01s)\n\ncompile_benchmark_test(map_test)\nadd_test(NAME map_test COMMAND map_test --benchmark_min_time=0.01s)\n\ncompile_benchmark_test(multiple_ranges_test)\nadd_test(NAME multiple_ranges_test COMMAND multiple_ranges_test --benchmark_min_time=0.01s)\n\ncompile_benchmark_test(args_product_test)\nadd_test(NAME args_product_test COMMAND args_product_test --benchmark_min_time=0.01s)\n\ncompile_benchmark_test_with_main(link_main_test)\nadd_test(NAME link_main_test COMMAND link_main_test --benchmark_min_time=0.01s)\n\ncompile_output_test(reporter_output_test)\nadd_test(NAME reporter_output_test COMMAND reporter_output_test --benchmark_min_time=0.01s)\n\ncompile_output_test(templated_fixture_test)\nadd_test(NAME templated_fixture_test COMMAND templated_fixture_test --benchmark_min_time=0.01s)\n\ncompile_output_test(user_counters_test)\nadd_test(NAME user_counters_test COMMAND user_counters_test --benchmark_min_time=0.01s)\n\ncompile_output_test(perf_counters_test)\nadd_test(NAME perf_counters_test COMMAND perf_counters_test --benchmark_min_time=0.01s --benchmark_perf_counters=CYCLES,BRANCHES)\n\ncompile_output_test(internal_threading_test)\nadd_test(NAME internal_threading_test COMMAND internal_threading_test --benchmark_min_time=0.01s)\n\ncompile_output_test(report_aggregates_only_test)\nadd_test(NAME report_aggregates_only_test COMMAND report_aggregates_only_test --benchmark_min_time=0.01s)\n\ncompile_output_test(display_aggregates_only_test)\nadd_test(NAME display_aggregates_only_test COMMAND display_aggregates_only_test --benchmark_min_time=0.01s)\n\ncompile_output_test(user_counters_tabular_test)\nadd_test(NAME user_counters_tabular_test COMMAND user_counters_tabular_test --benchmark_counters_tabular=true --benchmark_min_time=0.01s)\n\ncompile_output_test(user_counters_thousands_test)\nadd_test(NAME user_counters_thousands_test COMMAND user_counters_thousands_test --benchmark_min_time=0.01s)\n\ncompile_output_test(memory_manager_test)\nadd_test(NAME memory_manager_test COMMAND memory_manager_test --benchmark_min_time=0.01s)\n\n# MSVC does not allow to set the language standard to C++98/03.\nif(NOT CMAKE_CXX_COMPILER_ID STREQUAL \"MSVC\")\n  compile_benchmark_test(cxx03_test)\n  set_target_properties(cxx03_test\n      PROPERTIES\n      CXX_STANDARD 98\n      CXX_STANDARD_REQUIRED YES)\n  # libstdc++ provides different definitions within <map> between dialects. When\n  # LTO is enabled and -Werror is specified GCC diagnoses this ODR violation\n  # causing the test to fail to compile. To prevent this we explicitly disable\n  # the warning.\n  check_cxx_compiler_flag(-Wno-odr BENCHMARK_HAS_WNO_ODR)\n  check_cxx_compiler_flag(-Wno-lto-type-mismatch BENCHMARK_HAS_WNO_LTO_TYPE_MISMATCH)\n  # Cannot set_target_properties multiple times here because the warnings will\n  # be overwritten on each call\n  set (DISABLE_LTO_WARNINGS \"\")\n  if (BENCHMARK_HAS_WNO_ODR)\n    set(DISABLE_LTO_WARNINGS \"${DISABLE_LTO_WARNINGS} -Wno-odr\")\n  endif()\n  if (BENCHMARK_HAS_WNO_LTO_TYPE_MISMATCH)\n    set(DISABLE_LTO_WARNINGS \"${DISABLE_LTO_WARNINGS} -Wno-lto-type-mismatch\")\n  endif()\n  set_target_properties(cxx03_test PROPERTIES LINK_FLAGS \"${DISABLE_LTO_WARNINGS}\")\n  add_test(NAME cxx03 COMMAND cxx03_test --benchmark_min_time=0.01s)\nendif()\n\n# Attempt to work around flaky test failures when running on Appveyor servers.\nif (DEFINED ENV{APPVEYOR})\n  set(COMPLEXITY_MIN_TIME \"0.5s\")\nelse()\n  set(COMPLEXITY_MIN_TIME \"0.01s\")\nendif()\ncompile_output_test(complexity_test)\nadd_test(NAME complexity_benchmark COMMAND complexity_test --benchmark_min_time=${COMPLEXITY_MIN_TIME})\n\n###############################################################################\n# GoogleTest Unit Tests\n###############################################################################\n\nif (BENCHMARK_ENABLE_GTEST_TESTS)\n  macro(compile_gtest name)\n    add_executable(${name} \"${name}.cc\")\n    target_link_libraries(${name} benchmark::benchmark\n        gmock_main ${CMAKE_THREAD_LIBS_INIT})\n  endmacro(compile_gtest)\n\n  macro(add_gtest name)\n    compile_gtest(${name})\n    add_test(NAME ${name} COMMAND ${name})\n  endmacro()\n\n  add_gtest(benchmark_gtest)\n  add_gtest(benchmark_name_gtest)\n  add_gtest(benchmark_random_interleaving_gtest)\n  add_gtest(commandlineflags_gtest)\n  add_gtest(statistics_gtest)\n  add_gtest(string_util_gtest)\n  add_gtest(perf_counters_gtest)\n  add_gtest(time_unit_gtest)\n  add_gtest(min_time_parse_gtest)\nendif(BENCHMARK_ENABLE_GTEST_TESTS)\n\n###############################################################################\n# Assembly Unit Tests\n###############################################################################\n\nif (BENCHMARK_ENABLE_ASSEMBLY_TESTS)\n  if (NOT LLVM_FILECHECK_EXE)\n    message(FATAL_ERROR \"LLVM FileCheck is required when including this file\")\n  endif()\n  include(AssemblyTests.cmake)\n  add_filecheck_test(donotoptimize_assembly_test)\n  add_filecheck_test(state_assembly_test)\n  add_filecheck_test(clobber_memory_assembly_test)\nendif()\n\n\n\n###############################################################################\n# Code Coverage Configuration\n###############################################################################\n\n# Add the coverage command(s)\nif(CMAKE_BUILD_TYPE)\n  string(TOLOWER ${CMAKE_BUILD_TYPE} CMAKE_BUILD_TYPE_LOWER)\nendif()\nif (${CMAKE_BUILD_TYPE_LOWER} MATCHES \"coverage\")\n  find_program(GCOV gcov)\n  find_program(LCOV lcov)\n  find_program(GENHTML genhtml)\n  find_program(CTEST ctest)\n  if (GCOV AND LCOV AND GENHTML AND CTEST AND HAVE_CXX_FLAG_COVERAGE)\n    add_custom_command(\n      OUTPUT ${CMAKE_BINARY_DIR}/lcov/index.html\n      COMMAND ${LCOV} -q -z -d .\n      COMMAND ${LCOV} -q --no-external -c -b \"${CMAKE_SOURCE_DIR}\" -d . -o before.lcov -i\n      COMMAND ${CTEST} --force-new-ctest-process\n      COMMAND ${LCOV} -q --no-external -c -b \"${CMAKE_SOURCE_DIR}\" -d . -o after.lcov\n      COMMAND ${LCOV} -q -a before.lcov -a after.lcov --output-file final.lcov\n      COMMAND ${LCOV} -q -r final.lcov \"'${CMAKE_SOURCE_DIR}/test/*'\" -o final.lcov\n      COMMAND ${GENHTML} final.lcov -o lcov --demangle-cpp --sort -p \"${CMAKE_BINARY_DIR}\" -t benchmark\n      DEPENDS filter_test benchmark_test options_test basic_test fixture_test cxx03_test complexity_test\n      WORKING_DIRECTORY ${CMAKE_BINARY_DIR}\n      COMMENT \"Running LCOV\"\n    )\n    add_custom_target(coverage\n      DEPENDS ${CMAKE_BINARY_DIR}/lcov/index.html\n      COMMENT \"LCOV report at lcov/index.html\"\n    )\n    message(STATUS \"Coverage command added\")\n  else()\n    if (HAVE_CXX_FLAG_COVERAGE)\n      set(CXX_FLAG_COVERAGE_MESSAGE supported)\n    else()\n      set(CXX_FLAG_COVERAGE_MESSAGE unavailable)\n    endif()\n    message(WARNING\n      \"Coverage not available:\\n\"\n      \"  gcov: ${GCOV}\\n\"\n      \"  lcov: ${LCOV}\\n\"\n      \"  genhtml: ${GENHTML}\\n\"\n      \"  ctest: ${CTEST}\\n\"\n      \"  --coverage flag: ${CXX_FLAG_COVERAGE_MESSAGE}\")\n  endif()\nendif()\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/args_product_test.cc",
    "content": "#include <cassert>\n#include <iostream>\n#include <set>\n#include <vector>\n\n#include \"benchmark/benchmark.h\"\n\nclass ArgsProductFixture : public ::benchmark::Fixture {\n public:\n  ArgsProductFixture()\n      : expectedValues({{0, 100, 2000, 30000},\n                        {1, 15, 3, 8},\n                        {1, 15, 3, 9},\n                        {1, 15, 7, 8},\n                        {1, 15, 7, 9},\n                        {1, 15, 10, 8},\n                        {1, 15, 10, 9},\n                        {2, 15, 3, 8},\n                        {2, 15, 3, 9},\n                        {2, 15, 7, 8},\n                        {2, 15, 7, 9},\n                        {2, 15, 10, 8},\n                        {2, 15, 10, 9},\n                        {4, 5, 6, 11}}) {}\n\n  void SetUp(const ::benchmark::State& state) override {\n    std::vector<int64_t> ranges = {state.range(0), state.range(1),\n                                   state.range(2), state.range(3)};\n\n    assert(expectedValues.find(ranges) != expectedValues.end());\n\n    actualValues.insert(ranges);\n  }\n\n  // NOTE: This is not TearDown as we want to check after _all_ runs are\n  // complete.\n  ~ArgsProductFixture() override {\n    if (actualValues != expectedValues) {\n      std::cout << \"EXPECTED\\n\";\n      for (const auto& v : expectedValues) {\n        std::cout << \"{\";\n        for (int64_t iv : v) {\n          std::cout << iv << \", \";\n        }\n        std::cout << \"}\\n\";\n      }\n      std::cout << \"ACTUAL\\n\";\n      for (const auto& v : actualValues) {\n        std::cout << \"{\";\n        for (int64_t iv : v) {\n          std::cout << iv << \", \";\n        }\n        std::cout << \"}\\n\";\n      }\n    }\n  }\n\n  std::set<std::vector<int64_t>> expectedValues;\n  std::set<std::vector<int64_t>> actualValues;\n};\n\nBENCHMARK_DEFINE_F(ArgsProductFixture, Empty)(benchmark::State& state) {\n  for (auto _ : state) {\n    int64_t product =\n        state.range(0) * state.range(1) * state.range(2) * state.range(3);\n    for (int64_t x = 0; x < product; x++) {\n      benchmark::DoNotOptimize(x);\n    }\n  }\n}\n\nBENCHMARK_REGISTER_F(ArgsProductFixture, Empty)\n    ->Args({0, 100, 2000, 30000})\n    ->ArgsProduct({{1, 2}, {15}, {3, 7, 10}, {8, 9}})\n    ->Args({4, 5, 6, 11});\n\nBENCHMARK_MAIN();\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/basic_test.cc",
    "content": "\n#include \"benchmark/benchmark.h\"\n\n#define BASIC_BENCHMARK_TEST(x) BENCHMARK(x)->Arg(8)->Arg(512)->Arg(8192)\n\nvoid BM_empty(benchmark::State& state) {\n  for (auto _ : state) {\n    auto iterations = state.iterations();\n    benchmark::DoNotOptimize(iterations);\n  }\n}\nBENCHMARK(BM_empty);\nBENCHMARK(BM_empty)->ThreadPerCpu();\n\nvoid BM_spin_empty(benchmark::State& state) {\n  for (auto _ : state) {\n    for (auto x = 0; x < state.range(0); ++x) {\n      benchmark::DoNotOptimize(x);\n    }\n  }\n}\nBASIC_BENCHMARK_TEST(BM_spin_empty);\nBASIC_BENCHMARK_TEST(BM_spin_empty)->ThreadPerCpu();\n\nvoid BM_spin_pause_before(benchmark::State& state) {\n  for (auto i = 0; i < state.range(0); ++i) {\n    benchmark::DoNotOptimize(i);\n  }\n  for (auto _ : state) {\n    for (auto i = 0; i < state.range(0); ++i) {\n      benchmark::DoNotOptimize(i);\n    }\n  }\n}\nBASIC_BENCHMARK_TEST(BM_spin_pause_before);\nBASIC_BENCHMARK_TEST(BM_spin_pause_before)->ThreadPerCpu();\n\nvoid BM_spin_pause_during(benchmark::State& state) {\n  for (auto _ : state) {\n    state.PauseTiming();\n    for (auto i = 0; i < state.range(0); ++i) {\n      benchmark::DoNotOptimize(i);\n    }\n    state.ResumeTiming();\n    for (auto i = 0; i < state.range(0); ++i) {\n      benchmark::DoNotOptimize(i);\n    }\n  }\n}\nBASIC_BENCHMARK_TEST(BM_spin_pause_during);\nBASIC_BENCHMARK_TEST(BM_spin_pause_during)->ThreadPerCpu();\n\nvoid BM_pause_during(benchmark::State& state) {\n  for (auto _ : state) {\n    state.PauseTiming();\n    state.ResumeTiming();\n  }\n}\nBENCHMARK(BM_pause_during);\nBENCHMARK(BM_pause_during)->ThreadPerCpu();\nBENCHMARK(BM_pause_during)->UseRealTime();\nBENCHMARK(BM_pause_during)->UseRealTime()->ThreadPerCpu();\n\nvoid BM_spin_pause_after(benchmark::State& state) {\n  for (auto _ : state) {\n    for (auto i = 0; i < state.range(0); ++i) {\n      benchmark::DoNotOptimize(i);\n    }\n  }\n  for (auto i = 0; i < state.range(0); ++i) {\n    benchmark::DoNotOptimize(i);\n  }\n}\nBASIC_BENCHMARK_TEST(BM_spin_pause_after);\nBASIC_BENCHMARK_TEST(BM_spin_pause_after)->ThreadPerCpu();\n\nvoid BM_spin_pause_before_and_after(benchmark::State& state) {\n  for (auto i = 0; i < state.range(0); ++i) {\n    benchmark::DoNotOptimize(i);\n  }\n  for (auto _ : state) {\n    for (auto i = 0; i < state.range(0); ++i) {\n      benchmark::DoNotOptimize(i);\n    }\n  }\n  for (auto i = 0; i < state.range(0); ++i) {\n    benchmark::DoNotOptimize(i);\n  }\n}\nBASIC_BENCHMARK_TEST(BM_spin_pause_before_and_after);\nBASIC_BENCHMARK_TEST(BM_spin_pause_before_and_after)->ThreadPerCpu();\n\nvoid BM_empty_stop_start(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_empty_stop_start);\nBENCHMARK(BM_empty_stop_start)->ThreadPerCpu();\n\nvoid BM_KeepRunning(benchmark::State& state) {\n  benchmark::IterationCount iter_count = 0;\n  assert(iter_count == state.iterations());\n  while (state.KeepRunning()) {\n    ++iter_count;\n  }\n  assert(iter_count == state.iterations());\n}\nBENCHMARK(BM_KeepRunning);\n\nvoid BM_KeepRunningBatch(benchmark::State& state) {\n  // Choose a batch size >1000 to skip the typical runs with iteration\n  // targets of 10, 100 and 1000.  If these are not actually skipped the\n  // bug would be detectable as consecutive runs with the same iteration\n  // count.  Below we assert that this does not happen.\n  const benchmark::IterationCount batch_size = 1009;\n\n  static benchmark::IterationCount prior_iter_count = 0;\n  benchmark::IterationCount iter_count = 0;\n  while (state.KeepRunningBatch(batch_size)) {\n    iter_count += batch_size;\n  }\n  assert(state.iterations() == iter_count);\n\n  // Verify that the iteration count always increases across runs (see\n  // comment above).\n  assert(iter_count == batch_size            // max_iterations == 1\n         || iter_count > prior_iter_count);  // max_iterations > batch_size\n  prior_iter_count = iter_count;\n}\n// Register with a fixed repetition count to establish the invariant that\n// the iteration count should always change across runs.  This overrides\n// the --benchmark_repetitions command line flag, which would otherwise\n// cause this test to fail if set > 1.\nBENCHMARK(BM_KeepRunningBatch)->Repetitions(1);\n\nvoid BM_RangedFor(benchmark::State& state) {\n  benchmark::IterationCount iter_count = 0;\n  for (auto _ : state) {\n    ++iter_count;\n  }\n  assert(iter_count == state.max_iterations);\n}\nBENCHMARK(BM_RangedFor);\n\n#ifdef BENCHMARK_HAS_CXX11\ntemplate <typename T>\nvoid BM_OneTemplateFunc(benchmark::State& state) {\n  auto arg = state.range(0);\n  T sum = 0;\n  for (auto _ : state) {\n    sum += static_cast<T>(arg);\n  }\n}\nBENCHMARK(BM_OneTemplateFunc<int>)->Arg(1);\nBENCHMARK(BM_OneTemplateFunc<double>)->Arg(1);\n\ntemplate <typename A, typename B>\nvoid BM_TwoTemplateFunc(benchmark::State& state) {\n  auto arg = state.range(0);\n  A sum = 0;\n  B prod = 1;\n  for (auto _ : state) {\n    sum += static_cast<A>(arg);\n    prod *= static_cast<B>(arg);\n  }\n}\nBENCHMARK(BM_TwoTemplateFunc<int, double>)->Arg(1);\nBENCHMARK(BM_TwoTemplateFunc<double, int>)->Arg(1);\n\n#endif  // BENCHMARK_HAS_CXX11\n\n// Ensure that StateIterator provides all the necessary typedefs required to\n// instantiate std::iterator_traits.\nstatic_assert(\n    std::is_same<typename std::iterator_traits<\n                     benchmark::State::StateIterator>::value_type,\n                 typename benchmark::State::StateIterator::value_type>::value,\n    \"\");\n\nBENCHMARK_MAIN();\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/benchmark_gtest.cc",
    "content": "#include <map>\n#include <string>\n#include <vector>\n\n#include \"../src/benchmark_register.h\"\n#include \"benchmark/benchmark.h\"\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n\nnamespace benchmark {\nnamespace internal {\n\nnamespace {\n\nTEST(AddRangeTest, Simple) {\n  std::vector<int> dst;\n  AddRange(&dst, 1, 2, 2);\n  EXPECT_THAT(dst, testing::ElementsAre(1, 2));\n}\n\nTEST(AddRangeTest, Simple64) {\n  std::vector<int64_t> dst;\n  AddRange(&dst, static_cast<int64_t>(1), static_cast<int64_t>(2), 2);\n  EXPECT_THAT(dst, testing::ElementsAre(1, 2));\n}\n\nTEST(AddRangeTest, Advanced) {\n  std::vector<int> dst;\n  AddRange(&dst, 5, 15, 2);\n  EXPECT_THAT(dst, testing::ElementsAre(5, 8, 15));\n}\n\nTEST(AddRangeTest, Advanced64) {\n  std::vector<int64_t> dst;\n  AddRange(&dst, static_cast<int64_t>(5), static_cast<int64_t>(15), 2);\n  EXPECT_THAT(dst, testing::ElementsAre(5, 8, 15));\n}\n\nTEST(AddRangeTest, FullRange8) {\n  std::vector<int8_t> dst;\n  AddRange(&dst, int8_t{1}, std::numeric_limits<int8_t>::max(), int8_t{8});\n  EXPECT_THAT(\n      dst, testing::ElementsAre(int8_t{1}, int8_t{8}, int8_t{64}, int8_t{127}));\n}\n\nTEST(AddRangeTest, FullRange64) {\n  std::vector<int64_t> dst;\n  AddRange(&dst, int64_t{1}, std::numeric_limits<int64_t>::max(), 1024);\n  EXPECT_THAT(\n      dst, testing::ElementsAre(1LL, 1024LL, 1048576LL, 1073741824LL,\n                                1099511627776LL, 1125899906842624LL,\n                                1152921504606846976LL, 9223372036854775807LL));\n}\n\nTEST(AddRangeTest, NegativeRanges) {\n  std::vector<int> dst;\n  AddRange(&dst, -8, 0, 2);\n  EXPECT_THAT(dst, testing::ElementsAre(-8, -4, -2, -1, 0));\n}\n\nTEST(AddRangeTest, StrictlyNegative) {\n  std::vector<int> dst;\n  AddRange(&dst, -8, -1, 2);\n  EXPECT_THAT(dst, testing::ElementsAre(-8, -4, -2, -1));\n}\n\nTEST(AddRangeTest, SymmetricNegativeRanges) {\n  std::vector<int> dst;\n  AddRange(&dst, -8, 8, 2);\n  EXPECT_THAT(dst, testing::ElementsAre(-8, -4, -2, -1, 0, 1, 2, 4, 8));\n}\n\nTEST(AddRangeTest, SymmetricNegativeRangesOddMult) {\n  std::vector<int> dst;\n  AddRange(&dst, -30, 32, 5);\n  EXPECT_THAT(dst, testing::ElementsAre(-30, -25, -5, -1, 0, 1, 5, 25, 32));\n}\n\nTEST(AddRangeTest, NegativeRangesAsymmetric) {\n  std::vector<int> dst;\n  AddRange(&dst, -3, 5, 2);\n  EXPECT_THAT(dst, testing::ElementsAre(-3, -2, -1, 0, 1, 2, 4, 5));\n}\n\nTEST(AddRangeTest, NegativeRangesLargeStep) {\n  // Always include -1, 0, 1 when crossing zero.\n  std::vector<int> dst;\n  AddRange(&dst, -8, 8, 10);\n  EXPECT_THAT(dst, testing::ElementsAre(-8, -1, 0, 1, 8));\n}\n\nTEST(AddRangeTest, ZeroOnlyRange) {\n  std::vector<int> dst;\n  AddRange(&dst, 0, 0, 2);\n  EXPECT_THAT(dst, testing::ElementsAre(0));\n}\n\nTEST(AddRangeTest, ZeroStartingRange) {\n  std::vector<int> dst;\n  AddRange(&dst, 0, 2, 2);\n  EXPECT_THAT(dst, testing::ElementsAre(0, 1, 2));\n}\n\nTEST(AddRangeTest, NegativeRange64) {\n  std::vector<int64_t> dst;\n  AddRange<int64_t>(&dst, -4, 4, 2);\n  EXPECT_THAT(dst, testing::ElementsAre(-4, -2, -1, 0, 1, 2, 4));\n}\n\nTEST(AddRangeTest, NegativeRangePreservesExistingOrder) {\n  // If elements already exist in the range, ensure we don't change\n  // their ordering by adding negative values.\n  std::vector<int64_t> dst = {1, 2, 3};\n  AddRange<int64_t>(&dst, -2, 2, 2);\n  EXPECT_THAT(dst, testing::ElementsAre(1, 2, 3, -2, -1, 0, 1, 2));\n}\n\nTEST(AddRangeTest, FullNegativeRange64) {\n  std::vector<int64_t> dst;\n  const auto min = std::numeric_limits<int64_t>::min();\n  const auto max = std::numeric_limits<int64_t>::max();\n  AddRange(&dst, min, max, 1024);\n  EXPECT_THAT(\n      dst, testing::ElementsAreArray(std::vector<int64_t>{\n               min, -1152921504606846976LL, -1125899906842624LL,\n               -1099511627776LL, -1073741824LL, -1048576LL, -1024LL, -1LL, 0LL,\n               1LL, 1024LL, 1048576LL, 1073741824LL, 1099511627776LL,\n               1125899906842624LL, 1152921504606846976LL, max}));\n}\n\nTEST(AddRangeTest, Simple8) {\n  std::vector<int8_t> dst;\n  AddRange<int8_t>(&dst, int8_t{1}, int8_t{8}, int8_t{2});\n  EXPECT_THAT(dst,\n              testing::ElementsAre(int8_t{1}, int8_t{2}, int8_t{4}, int8_t{8}));\n}\n\nTEST(AddCustomContext, Simple) {\n  std::map<std::string, std::string> *&global_context = GetGlobalContext();\n  EXPECT_THAT(global_context, nullptr);\n\n  AddCustomContext(\"foo\", \"bar\");\n  AddCustomContext(\"baz\", \"qux\");\n\n  EXPECT_THAT(*global_context,\n              testing::UnorderedElementsAre(testing::Pair(\"foo\", \"bar\"),\n                                            testing::Pair(\"baz\", \"qux\")));\n\n  delete global_context;\n  global_context = nullptr;\n}\n\nTEST(AddCustomContext, DuplicateKey) {\n  std::map<std::string, std::string> *&global_context = GetGlobalContext();\n  EXPECT_THAT(global_context, nullptr);\n\n  AddCustomContext(\"foo\", \"bar\");\n  AddCustomContext(\"foo\", \"qux\");\n\n  EXPECT_THAT(*global_context,\n              testing::UnorderedElementsAre(testing::Pair(\"foo\", \"bar\")));\n\n  delete global_context;\n  global_context = nullptr;\n}\n\n}  // namespace\n}  // namespace internal\n}  // namespace benchmark\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/benchmark_min_time_flag_iters_test.cc",
    "content": "#include <cassert>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include \"benchmark/benchmark.h\"\n\n// Tests that we can specify the number of iterations with\n// --benchmark_min_time=<NUM>x.\nnamespace {\n\nclass TestReporter : public benchmark::ConsoleReporter {\n public:\n  virtual bool ReportContext(const Context& context) BENCHMARK_OVERRIDE {\n    return ConsoleReporter::ReportContext(context);\n  };\n\n  virtual void ReportRuns(const std::vector<Run>& report) BENCHMARK_OVERRIDE {\n    assert(report.size() == 1);\n    iter_nums_.push_back(report[0].iterations);\n    ConsoleReporter::ReportRuns(report);\n  };\n\n  TestReporter() {}\n\n  virtual ~TestReporter() {}\n\n  const std::vector<benchmark::IterationCount>& GetIters() const {\n    return iter_nums_;\n  }\n\n private:\n  std::vector<benchmark::IterationCount> iter_nums_;\n};\n\n}  // end namespace\n\nstatic void BM_MyBench(benchmark::State& state) {\n  for (auto s : state) {\n  }\n}\nBENCHMARK(BM_MyBench);\n\nint main(int argc, char** argv) {\n  // Make a fake argv and append the new --benchmark_min_time=<foo> to it.\n  int fake_argc = argc + 1;\n  const char** fake_argv = new const char*[static_cast<size_t>(fake_argc)];\n  for (int i = 0; i < argc; ++i) fake_argv[i] = argv[i];\n  fake_argv[argc] = \"--benchmark_min_time=4x\";\n\n  benchmark::Initialize(&fake_argc, const_cast<char**>(fake_argv));\n\n  TestReporter test_reporter;\n  const size_t returned_count =\n      benchmark::RunSpecifiedBenchmarks(&test_reporter, \"BM_MyBench\");\n  assert(returned_count == 1);\n\n  // Check the executed iters.\n  const std::vector<benchmark::IterationCount> iters = test_reporter.GetIters();\n  assert(!iters.empty() && iters[0] == 4);\n\n  delete[] fake_argv;\n  return 0;\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/benchmark_min_time_flag_time_test.cc",
    "content": "#include <cassert>\n#include <climits>\n#include <cmath>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <string>\n#include <vector>\n\n#include \"benchmark/benchmark.h\"\n\n// Tests that we can specify the min time with\n// --benchmark_min_time=<NUM> (no suffix needed) OR\n// --benchmark_min_time=<NUM>s\nnamespace {\n\n// This is from benchmark.h\ntypedef int64_t IterationCount;\n\nclass TestReporter : public benchmark::ConsoleReporter {\n public:\n  virtual bool ReportContext(const Context& context) BENCHMARK_OVERRIDE {\n    return ConsoleReporter::ReportContext(context);\n  };\n\n  virtual void ReportRuns(const std::vector<Run>& report) BENCHMARK_OVERRIDE {\n    assert(report.size() == 1);\n    ConsoleReporter::ReportRuns(report);\n  };\n\n  virtual void ReportRunsConfig(double min_time, bool /* has_explicit_iters */,\n                                IterationCount /* iters */) BENCHMARK_OVERRIDE {\n    min_times_.push_back(min_time);\n  }\n\n  TestReporter() {}\n\n  virtual ~TestReporter() {}\n\n  const std::vector<double>& GetMinTimes() const { return min_times_; }\n\n private:\n  std::vector<double> min_times_;\n};\n\nbool AlmostEqual(double a, double b) {\n  return std::fabs(a - b) < std::numeric_limits<double>::epsilon();\n}\n\nvoid DoTestHelper(int* argc, const char** argv, double expected) {\n  benchmark::Initialize(argc, const_cast<char**>(argv));\n\n  TestReporter test_reporter;\n  const size_t returned_count =\n      benchmark::RunSpecifiedBenchmarks(&test_reporter, \"BM_MyBench\");\n  assert(returned_count == 1);\n\n  // Check the min_time\n  const std::vector<double>& min_times = test_reporter.GetMinTimes();\n  assert(!min_times.empty() && AlmostEqual(min_times[0], expected));\n}\n\n}  // end namespace\n\nstatic void BM_MyBench(benchmark::State& state) {\n  for (auto s : state) {\n  }\n}\nBENCHMARK(BM_MyBench);\n\nint main(int argc, char** argv) {\n  // Make a fake argv and append the new --benchmark_min_time=<foo> to it.\n  int fake_argc = argc + 1;\n  const char** fake_argv = new const char*[static_cast<size_t>(fake_argc)];\n\n  for (int i = 0; i < argc; ++i) fake_argv[i] = argv[i];\n\n  const char* no_suffix = \"--benchmark_min_time=4\";\n  const char* with_suffix = \"--benchmark_min_time=4.0s\";\n  double expected = 4.0;\n\n  fake_argv[argc] = no_suffix;\n  DoTestHelper(&fake_argc, fake_argv, expected);\n\n  fake_argv[argc] = with_suffix;\n  DoTestHelper(&fake_argc, fake_argv, expected);\n\n  delete[] fake_argv;\n  return 0;\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/benchmark_name_gtest.cc",
    "content": "#include \"benchmark/benchmark.h\"\n#include \"gtest/gtest.h\"\n\nnamespace {\n\nusing namespace benchmark;\nusing namespace benchmark::internal;\n\nTEST(BenchmarkNameTest, Empty) {\n  const auto name = BenchmarkName();\n  EXPECT_EQ(name.str(), std::string());\n}\n\nTEST(BenchmarkNameTest, FunctionName) {\n  auto name = BenchmarkName();\n  name.function_name = \"function_name\";\n  EXPECT_EQ(name.str(), \"function_name\");\n}\n\nTEST(BenchmarkNameTest, FunctionNameAndArgs) {\n  auto name = BenchmarkName();\n  name.function_name = \"function_name\";\n  name.args = \"some_args:3/4/5\";\n  EXPECT_EQ(name.str(), \"function_name/some_args:3/4/5\");\n}\n\nTEST(BenchmarkNameTest, MinTime) {\n  auto name = BenchmarkName();\n  name.function_name = \"function_name\";\n  name.args = \"some_args:3/4\";\n  name.min_time = \"min_time:3.4s\";\n  EXPECT_EQ(name.str(), \"function_name/some_args:3/4/min_time:3.4s\");\n}\n\nTEST(BenchmarkNameTest, MinWarmUpTime) {\n  auto name = BenchmarkName();\n  name.function_name = \"function_name\";\n  name.args = \"some_args:3/4\";\n  name.min_warmup_time = \"min_warmup_time:3.5s\";\n  EXPECT_EQ(name.str(), \"function_name/some_args:3/4/min_warmup_time:3.5s\");\n}\n\nTEST(BenchmarkNameTest, Iterations) {\n  auto name = BenchmarkName();\n  name.function_name = \"function_name\";\n  name.min_time = \"min_time:3.4s\";\n  name.iterations = \"iterations:42\";\n  EXPECT_EQ(name.str(), \"function_name/min_time:3.4s/iterations:42\");\n}\n\nTEST(BenchmarkNameTest, Repetitions) {\n  auto name = BenchmarkName();\n  name.function_name = \"function_name\";\n  name.min_time = \"min_time:3.4s\";\n  name.repetitions = \"repetitions:24\";\n  EXPECT_EQ(name.str(), \"function_name/min_time:3.4s/repetitions:24\");\n}\n\nTEST(BenchmarkNameTest, TimeType) {\n  auto name = BenchmarkName();\n  name.function_name = \"function_name\";\n  name.min_time = \"min_time:3.4s\";\n  name.time_type = \"hammer_time\";\n  EXPECT_EQ(name.str(), \"function_name/min_time:3.4s/hammer_time\");\n}\n\nTEST(BenchmarkNameTest, Threads) {\n  auto name = BenchmarkName();\n  name.function_name = \"function_name\";\n  name.min_time = \"min_time:3.4s\";\n  name.threads = \"threads:256\";\n  EXPECT_EQ(name.str(), \"function_name/min_time:3.4s/threads:256\");\n}\n\nTEST(BenchmarkNameTest, TestEmptyFunctionName) {\n  auto name = BenchmarkName();\n  name.args = \"first:3/second:4\";\n  name.threads = \"threads:22\";\n  EXPECT_EQ(name.str(), \"first:3/second:4/threads:22\");\n}\n\n}  // end namespace\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/benchmark_random_interleaving_gtest.cc",
    "content": "#include <queue>\n#include <string>\n#include <vector>\n\n#include \"../src/commandlineflags.h\"\n#include \"../src/string_util.h\"\n#include \"benchmark/benchmark.h\"\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n\nnamespace benchmark {\n\nBM_DECLARE_bool(benchmark_enable_random_interleaving);\nBM_DECLARE_string(benchmark_filter);\nBM_DECLARE_int32(benchmark_repetitions);\n\nnamespace internal {\nnamespace {\n\nclass EventQueue : public std::queue<std::string> {\n public:\n  void Put(const std::string& event) { push(event); }\n\n  void Clear() {\n    while (!empty()) {\n      pop();\n    }\n  }\n\n  std::string Get() {\n    std::string event = front();\n    pop();\n    return event;\n  }\n};\n\nEventQueue* queue = new EventQueue();\n\nclass NullReporter : public BenchmarkReporter {\n public:\n  bool ReportContext(const Context& /*context*/) override { return true; }\n  void ReportRuns(const std::vector<Run>& /* report */) override {}\n};\n\nclass BenchmarkTest : public testing::Test {\n public:\n  static void SetupHook(int /* num_threads */) { queue->push(\"Setup\"); }\n\n  static void TeardownHook(int /* num_threads */) { queue->push(\"Teardown\"); }\n\n  void Execute(const std::string& pattern) {\n    queue->Clear();\n\n    std::unique_ptr<BenchmarkReporter> reporter(new NullReporter());\n    FLAGS_benchmark_filter = pattern;\n    RunSpecifiedBenchmarks(reporter.get());\n\n    queue->Put(\"DONE\");  // End marker\n  }\n};\n\nvoid BM_Match1(benchmark::State& state) {\n  const int64_t arg = state.range(0);\n\n  for (auto _ : state) {\n  }\n  queue->Put(StrFormat(\"BM_Match1/%d\", static_cast<int>(arg)));\n}\nBENCHMARK(BM_Match1)\n    ->Iterations(100)\n    ->Arg(1)\n    ->Arg(2)\n    ->Arg(3)\n    ->Range(10, 80)\n    ->Args({90})\n    ->Args({100});\n\nTEST_F(BenchmarkTest, Match1) {\n  Execute(\"BM_Match1\");\n  ASSERT_EQ(\"BM_Match1/1\", queue->Get());\n  ASSERT_EQ(\"BM_Match1/2\", queue->Get());\n  ASSERT_EQ(\"BM_Match1/3\", queue->Get());\n  ASSERT_EQ(\"BM_Match1/10\", queue->Get());\n  ASSERT_EQ(\"BM_Match1/64\", queue->Get());\n  ASSERT_EQ(\"BM_Match1/80\", queue->Get());\n  ASSERT_EQ(\"BM_Match1/90\", queue->Get());\n  ASSERT_EQ(\"BM_Match1/100\", queue->Get());\n  ASSERT_EQ(\"DONE\", queue->Get());\n}\n\nTEST_F(BenchmarkTest, Match1WithRepetition) {\n  FLAGS_benchmark_repetitions = 2;\n\n  Execute(\"BM_Match1/(64|80)\");\n  ASSERT_EQ(\"BM_Match1/64\", queue->Get());\n  ASSERT_EQ(\"BM_Match1/64\", queue->Get());\n  ASSERT_EQ(\"BM_Match1/80\", queue->Get());\n  ASSERT_EQ(\"BM_Match1/80\", queue->Get());\n  ASSERT_EQ(\"DONE\", queue->Get());\n}\n\nTEST_F(BenchmarkTest, Match1WithRandomInterleaving) {\n  FLAGS_benchmark_enable_random_interleaving = true;\n  FLAGS_benchmark_repetitions = 100;\n\n  std::map<std::string, int> element_count;\n  std::map<std::string, int> interleaving_count;\n  Execute(\"BM_Match1/(64|80)\");\n  for (int i = 0; i < 100; ++i) {\n    std::vector<std::string> interleaving;\n    interleaving.push_back(queue->Get());\n    interleaving.push_back(queue->Get());\n    element_count[interleaving[0]]++;\n    element_count[interleaving[1]]++;\n    interleaving_count[StrFormat(\"%s,%s\", interleaving[0].c_str(),\n                                 interleaving[1].c_str())]++;\n  }\n  EXPECT_EQ(element_count[\"BM_Match1/64\"], 100) << \"Unexpected repetitions.\";\n  EXPECT_EQ(element_count[\"BM_Match1/80\"], 100) << \"Unexpected repetitions.\";\n  EXPECT_GE(interleaving_count.size(), 2) << \"Interleaving was not randomized.\";\n  ASSERT_EQ(\"DONE\", queue->Get());\n}\n\n}  // namespace\n}  // namespace internal\n}  // namespace benchmark\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/benchmark_setup_teardown_test.cc",
    "content": "#include <atomic>\n#include <cassert>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <limits>\n#include <string>\n\n#include \"benchmark/benchmark.h\"\n\n// Test that Setup() and Teardown() are called exactly once\n// for each benchmark run (single-threaded).\nnamespace singlethreaded {\nstatic int setup_call = 0;\nstatic int teardown_call = 0;\n}  // namespace singlethreaded\nstatic void DoSetup1(const benchmark::State& state) {\n  ++singlethreaded::setup_call;\n\n  // Setup/Teardown should never be called with any thread_idx != 0.\n  assert(state.thread_index() == 0);\n}\n\nstatic void DoTeardown1(const benchmark::State& state) {\n  ++singlethreaded::teardown_call;\n  assert(state.thread_index() == 0);\n}\n\nstatic void BM_with_setup(benchmark::State& state) {\n  for (auto s : state) {\n  }\n}\nBENCHMARK(BM_with_setup)\n    ->Arg(1)\n    ->Arg(3)\n    ->Arg(5)\n    ->Arg(7)\n    ->Iterations(100)\n    ->Setup(DoSetup1)\n    ->Teardown(DoTeardown1);\n\n// Test that Setup() and Teardown() are called once for each group of threads.\nnamespace concurrent {\nstatic std::atomic<int> setup_call(0);\nstatic std::atomic<int> teardown_call(0);\nstatic std::atomic<int> func_call(0);\n}  // namespace concurrent\n\nstatic void DoSetup2(const benchmark::State& state) {\n  concurrent::setup_call.fetch_add(1, std::memory_order_acquire);\n  assert(state.thread_index() == 0);\n}\n\nstatic void DoTeardown2(const benchmark::State& state) {\n  concurrent::teardown_call.fetch_add(1, std::memory_order_acquire);\n  assert(state.thread_index() == 0);\n}\n\nstatic void BM_concurrent(benchmark::State& state) {\n  for (auto s : state) {\n  }\n  concurrent::func_call.fetch_add(1, std::memory_order_acquire);\n}\n\nBENCHMARK(BM_concurrent)\n    ->Setup(DoSetup2)\n    ->Teardown(DoTeardown2)\n    ->Iterations(100)\n    ->Threads(5)\n    ->Threads(10)\n    ->Threads(15);\n\n// Testing interaction with Fixture::Setup/Teardown\nnamespace fixture_interaction {\nint setup = 0;\nint fixture_setup = 0;\n}  // namespace fixture_interaction\n\n#define FIXTURE_BECHMARK_NAME MyFixture\n\nclass FIXTURE_BECHMARK_NAME : public ::benchmark::Fixture {\n public:\n  void SetUp(const ::benchmark::State&) override {\n    fixture_interaction::fixture_setup++;\n  }\n\n  ~FIXTURE_BECHMARK_NAME() override {}\n};\n\nBENCHMARK_F(FIXTURE_BECHMARK_NAME, BM_WithFixture)(benchmark::State& st) {\n  for (auto _ : st) {\n  }\n}\n\nstatic void DoSetupWithFixture(const benchmark::State&) {\n  fixture_interaction::setup++;\n}\n\nBENCHMARK_REGISTER_F(FIXTURE_BECHMARK_NAME, BM_WithFixture)\n    ->Arg(1)\n    ->Arg(3)\n    ->Arg(5)\n    ->Arg(7)\n    ->Setup(DoSetupWithFixture)\n    ->Repetitions(1)\n    ->Iterations(100);\n\n// Testing repetitions.\nnamespace repetitions {\nint setup = 0;\n}\n\nstatic void DoSetupWithRepetitions(const benchmark::State&) {\n  repetitions::setup++;\n}\nstatic void BM_WithRep(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\n\nBENCHMARK(BM_WithRep)\n    ->Arg(1)\n    ->Arg(3)\n    ->Arg(5)\n    ->Arg(7)\n    ->Setup(DoSetupWithRepetitions)\n    ->Iterations(100)\n    ->Repetitions(4);\n\nint main(int argc, char** argv) {\n  benchmark::Initialize(&argc, argv);\n\n  size_t ret = benchmark::RunSpecifiedBenchmarks(\".\");\n  assert(ret > 0);\n\n  // Setup/Teardown is called once for each arg group (1,3,5,7).\n  assert(singlethreaded::setup_call == 4);\n  assert(singlethreaded::teardown_call == 4);\n\n  // 3 group of threads calling this function (3,5,10).\n  assert(concurrent::setup_call.load(std::memory_order_relaxed) == 3);\n  assert(concurrent::teardown_call.load(std::memory_order_relaxed) == 3);\n  assert((5 + 10 + 15) ==\n         concurrent::func_call.load(std::memory_order_relaxed));\n\n  // Setup is called 4 times, once for each arg group (1,3,5,7)\n  assert(fixture_interaction::setup == 4);\n  // Fixture::Setup is called every time the bm routine is run.\n  // The exact number is indeterministic, so we just assert that\n  // it's more than setup.\n  assert(fixture_interaction::fixture_setup > fixture_interaction::setup);\n\n  // Setup is call once for each repetition * num_arg =  4 * 4 = 16.\n  assert(repetitions::setup == 16);\n\n  return 0;\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/benchmark_test.cc",
    "content": "#include \"benchmark/benchmark.h\"\n\n#include <assert.h>\n#include <math.h>\n#include <stdint.h>\n\n#include <chrono>\n#include <complex>\n#include <cstdlib>\n#include <iostream>\n#include <limits>\n#include <list>\n#include <map>\n#include <mutex>\n#include <set>\n#include <sstream>\n#include <string>\n#include <thread>\n#include <utility>\n#include <vector>\n\n#if defined(__GNUC__)\n#define BENCHMARK_NOINLINE __attribute__((noinline))\n#else\n#define BENCHMARK_NOINLINE\n#endif\n\nnamespace {\n\nint BENCHMARK_NOINLINE Factorial(int n) {\n  return (n == 1) ? 1 : n * Factorial(n - 1);\n}\n\ndouble CalculatePi(int depth) {\n  double pi = 0.0;\n  for (int i = 0; i < depth; ++i) {\n    double numerator = static_cast<double>(((i % 2) * 2) - 1);\n    double denominator = static_cast<double>((2 * i) - 1);\n    pi += numerator / denominator;\n  }\n  return (pi - 1.0) * 4;\n}\n\nstd::set<int64_t> ConstructRandomSet(int64_t size) {\n  std::set<int64_t> s;\n  for (int i = 0; i < size; ++i) s.insert(s.end(), i);\n  return s;\n}\n\nstd::mutex test_vector_mu;\nstd::vector<int>* test_vector = nullptr;\n\n}  // end namespace\n\nstatic void BM_Factorial(benchmark::State& state) {\n  int fac_42 = 0;\n  for (auto _ : state) fac_42 = Factorial(8);\n  // Prevent compiler optimizations\n  std::stringstream ss;\n  ss << fac_42;\n  state.SetLabel(ss.str());\n}\nBENCHMARK(BM_Factorial);\nBENCHMARK(BM_Factorial)->UseRealTime();\n\nstatic void BM_CalculatePiRange(benchmark::State& state) {\n  double pi = 0.0;\n  for (auto _ : state) pi = CalculatePi(static_cast<int>(state.range(0)));\n  std::stringstream ss;\n  ss << pi;\n  state.SetLabel(ss.str());\n}\nBENCHMARK_RANGE(BM_CalculatePiRange, 1, 1024 * 1024);\n\nstatic void BM_CalculatePi(benchmark::State& state) {\n  static const int depth = 1024;\n  for (auto _ : state) {\n    double pi = CalculatePi(static_cast<int>(depth));\n    benchmark::DoNotOptimize(pi);\n  }\n}\nBENCHMARK(BM_CalculatePi)->Threads(8);\nBENCHMARK(BM_CalculatePi)->ThreadRange(1, 32);\nBENCHMARK(BM_CalculatePi)->ThreadPerCpu();\n\nstatic void BM_SetInsert(benchmark::State& state) {\n  std::set<int64_t> data;\n  for (auto _ : state) {\n    state.PauseTiming();\n    data = ConstructRandomSet(state.range(0));\n    state.ResumeTiming();\n    for (int j = 0; j < state.range(1); ++j) data.insert(rand());\n  }\n  state.SetItemsProcessed(state.iterations() * state.range(1));\n  state.SetBytesProcessed(state.iterations() * state.range(1) *\n                          static_cast<int64_t>(sizeof(int)));\n}\n\n// Test many inserts at once to reduce the total iterations needed. Otherwise,\n// the slower, non-timed part of each iteration will make the benchmark take\n// forever.\nBENCHMARK(BM_SetInsert)->Ranges({{1 << 10, 8 << 10}, {128, 512}});\n\ntemplate <typename Container,\n          typename ValueType = typename Container::value_type>\nstatic void BM_Sequential(benchmark::State& state) {\n  ValueType v = 42;\n  for (auto _ : state) {\n    Container c;\n    for (int64_t i = state.range(0); --i;) c.push_back(v);\n  }\n  const int64_t items_processed = state.iterations() * state.range(0);\n  state.SetItemsProcessed(items_processed);\n  state.SetBytesProcessed(items_processed * static_cast<int64_t>(sizeof(v)));\n}\nBENCHMARK_TEMPLATE2(BM_Sequential, std::vector<int>, int)\n    ->Range(1 << 0, 1 << 10);\nBENCHMARK_TEMPLATE(BM_Sequential, std::list<int>)->Range(1 << 0, 1 << 10);\n// Test the variadic version of BENCHMARK_TEMPLATE in C++11 and beyond.\n#ifdef BENCHMARK_HAS_CXX11\nBENCHMARK_TEMPLATE(BM_Sequential, std::vector<int>, int)->Arg(512);\n#endif\n\nstatic void BM_StringCompare(benchmark::State& state) {\n  size_t len = static_cast<size_t>(state.range(0));\n  std::string s1(len, '-');\n  std::string s2(len, '-');\n  for (auto _ : state) {\n    auto comp = s1.compare(s2);\n    benchmark::DoNotOptimize(comp);\n  }\n}\nBENCHMARK(BM_StringCompare)->Range(1, 1 << 20);\n\nstatic void BM_SetupTeardown(benchmark::State& state) {\n  if (state.thread_index() == 0) {\n    // No need to lock test_vector_mu here as this is running single-threaded.\n    test_vector = new std::vector<int>();\n  }\n  int i = 0;\n  for (auto _ : state) {\n    std::lock_guard<std::mutex> l(test_vector_mu);\n    if (i % 2 == 0)\n      test_vector->push_back(i);\n    else\n      test_vector->pop_back();\n    ++i;\n  }\n  if (state.thread_index() == 0) {\n    delete test_vector;\n  }\n}\nBENCHMARK(BM_SetupTeardown)->ThreadPerCpu();\n\nstatic void BM_LongTest(benchmark::State& state) {\n  double tracker = 0.0;\n  for (auto _ : state) {\n    for (int i = 0; i < state.range(0); ++i)\n      benchmark::DoNotOptimize(tracker += i);\n  }\n}\nBENCHMARK(BM_LongTest)->Range(1 << 16, 1 << 28);\n\nstatic void BM_ParallelMemset(benchmark::State& state) {\n  int64_t size = state.range(0) / static_cast<int64_t>(sizeof(int));\n  int thread_size = static_cast<int>(size) / state.threads();\n  int from = thread_size * state.thread_index();\n  int to = from + thread_size;\n\n  if (state.thread_index() == 0) {\n    test_vector = new std::vector<int>(static_cast<size_t>(size));\n  }\n\n  for (auto _ : state) {\n    for (int i = from; i < to; i++) {\n      // No need to lock test_vector_mu as ranges\n      // do not overlap between threads.\n      benchmark::DoNotOptimize(test_vector->at(static_cast<size_t>(i)) = 1);\n    }\n  }\n\n  if (state.thread_index() == 0) {\n    delete test_vector;\n  }\n}\nBENCHMARK(BM_ParallelMemset)->Arg(10 << 20)->ThreadRange(1, 4);\n\nstatic void BM_ManualTiming(benchmark::State& state) {\n  int64_t slept_for = 0;\n  int64_t microseconds = state.range(0);\n  std::chrono::duration<double, std::micro> sleep_duration{\n      static_cast<double>(microseconds)};\n\n  for (auto _ : state) {\n    auto start = std::chrono::high_resolution_clock::now();\n    // Simulate some useful workload with a sleep\n    std::this_thread::sleep_for(\n        std::chrono::duration_cast<std::chrono::nanoseconds>(sleep_duration));\n    auto end = std::chrono::high_resolution_clock::now();\n\n    auto elapsed =\n        std::chrono::duration_cast<std::chrono::duration<double>>(end - start);\n\n    state.SetIterationTime(elapsed.count());\n    slept_for += microseconds;\n  }\n  state.SetItemsProcessed(slept_for);\n}\nBENCHMARK(BM_ManualTiming)->Range(1, 1 << 14)->UseRealTime();\nBENCHMARK(BM_ManualTiming)->Range(1, 1 << 14)->UseManualTime();\n\n#ifdef BENCHMARK_HAS_CXX11\n\ntemplate <class... Args>\nvoid BM_with_args(benchmark::State& state, Args&&...) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK_CAPTURE(BM_with_args, int_test, 42, 43, 44);\nBENCHMARK_CAPTURE(BM_with_args, string_and_pair_test, std::string(\"abc\"),\n                  std::pair<int, double>(42, 3.8));\n\nvoid BM_non_template_args(benchmark::State& state, int, double) {\n  while (state.KeepRunning()) {\n  }\n}\nBENCHMARK_CAPTURE(BM_non_template_args, basic_test, 0, 0);\n\n#endif  // BENCHMARK_HAS_CXX11\n\nstatic void BM_DenseThreadRanges(benchmark::State& st) {\n  switch (st.range(0)) {\n    case 1:\n      assert(st.threads() == 1 || st.threads() == 2 || st.threads() == 3);\n      break;\n    case 2:\n      assert(st.threads() == 1 || st.threads() == 3 || st.threads() == 4);\n      break;\n    case 3:\n      assert(st.threads() == 5 || st.threads() == 8 || st.threads() == 11 ||\n             st.threads() == 14);\n      break;\n    default:\n      assert(false && \"Invalid test case number\");\n  }\n  while (st.KeepRunning()) {\n  }\n}\nBENCHMARK(BM_DenseThreadRanges)->Arg(1)->DenseThreadRange(1, 3);\nBENCHMARK(BM_DenseThreadRanges)->Arg(2)->DenseThreadRange(1, 4, 2);\nBENCHMARK(BM_DenseThreadRanges)->Arg(3)->DenseThreadRange(5, 14, 3);\n\nstatic void BM_BenchmarkName(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n\n  // Check that the benchmark name is passed correctly to `state`.\n  assert(\"BM_BenchmarkName\" == state.name());\n}\nBENCHMARK(BM_BenchmarkName);\n\n// regression test for #1446\ntemplate <typename type>\nstatic void BM_templated_test(benchmark::State& state) {\n  for (auto _ : state) {\n    type created_string;\n    benchmark::DoNotOptimize(created_string);\n  }\n}\n\nstatic auto BM_templated_test_double = BM_templated_test<std::complex<double>>;\nBENCHMARK(BM_templated_test_double);\n\nBENCHMARK_MAIN();\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/clobber_memory_assembly_test.cc",
    "content": "#include <benchmark/benchmark.h>\n\n#ifdef __clang__\n#pragma clang diagnostic ignored \"-Wreturn-type\"\n#endif\nBENCHMARK_DISABLE_DEPRECATED_WARNING\n\nextern \"C\" {\n\nextern int ExternInt;\nextern int ExternInt2;\nextern int ExternInt3;\n}\n\n// CHECK-LABEL: test_basic:\nextern \"C\" void test_basic() {\n  int x;\n  benchmark::DoNotOptimize(&x);\n  x = 101;\n  benchmark::ClobberMemory();\n  // CHECK: leaq [[DEST:[^,]+]], %rax\n  // CHECK: movl $101, [[DEST]]\n  // CHECK: ret\n}\n\n// CHECK-LABEL: test_redundant_store:\nextern \"C\" void test_redundant_store() {\n  ExternInt = 3;\n  benchmark::ClobberMemory();\n  ExternInt = 51;\n  // CHECK-DAG: ExternInt\n  // CHECK-DAG: movl $3\n  // CHECK: movl $51\n}\n\n// CHECK-LABEL: test_redundant_read:\nextern \"C\" void test_redundant_read() {\n  int x;\n  benchmark::DoNotOptimize(&x);\n  x = ExternInt;\n  benchmark::ClobberMemory();\n  x = ExternInt2;\n  // CHECK: leaq [[DEST:[^,]+]], %rax\n  // CHECK: ExternInt(%rip)\n  // CHECK: movl %eax, [[DEST]]\n  // CHECK-NOT: ExternInt2\n  // CHECK: ret\n}\n\n// CHECK-LABEL: test_redundant_read2:\nextern \"C\" void test_redundant_read2() {\n  int x;\n  benchmark::DoNotOptimize(&x);\n  x = ExternInt;\n  benchmark::ClobberMemory();\n  x = ExternInt2;\n  benchmark::ClobberMemory();\n  // CHECK: leaq [[DEST:[^,]+]], %rax\n  // CHECK: ExternInt(%rip)\n  // CHECK: movl %eax, [[DEST]]\n  // CHECK: ExternInt2(%rip)\n  // CHECK: movl %eax, [[DEST]]\n  // CHECK: ret\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/commandlineflags_gtest.cc",
    "content": "#include <cstdlib>\n\n#include \"../src/commandlineflags.h\"\n#include \"../src/internal_macros.h\"\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n\nnamespace benchmark {\nnamespace {\n\n#if defined(BENCHMARK_OS_WINDOWS)\nint setenv(const char* name, const char* value, int overwrite) {\n  if (!overwrite) {\n    // NOTE: getenv_s is far superior but not available under mingw.\n    char* env_value = getenv(name);\n    if (env_value == nullptr) {\n      return -1;\n    }\n  }\n  return _putenv_s(name, value);\n}\n\nint unsetenv(const char* name) { return _putenv_s(name, \"\"); }\n\n#endif  // BENCHMARK_OS_WINDOWS\n\nTEST(BoolFromEnv, Default) {\n  ASSERT_EQ(unsetenv(\"NOT_IN_ENV\"), 0);\n  EXPECT_EQ(BoolFromEnv(\"not_in_env\", true), true);\n}\n\nTEST(BoolFromEnv, False) {\n  ASSERT_EQ(setenv(\"IN_ENV\", \"0\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", true), false);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"N\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", true), false);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"n\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", true), false);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"NO\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", true), false);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"No\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", true), false);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"no\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", true), false);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"F\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", true), false);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"f\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", true), false);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"FALSE\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", true), false);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"False\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", true), false);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"false\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", true), false);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"OFF\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", true), false);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"Off\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", true), false);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"off\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", true), false);\n  unsetenv(\"IN_ENV\");\n}\n\nTEST(BoolFromEnv, True) {\n  ASSERT_EQ(setenv(\"IN_ENV\", \"1\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", false), true);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"Y\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", false), true);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"y\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", false), true);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"YES\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", false), true);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"Yes\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", false), true);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"yes\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", false), true);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"T\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", false), true);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"t\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", false), true);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"TRUE\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", false), true);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"True\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", false), true);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"true\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", false), true);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"ON\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", false), true);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"On\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", false), true);\n  unsetenv(\"IN_ENV\");\n\n  ASSERT_EQ(setenv(\"IN_ENV\", \"on\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", false), true);\n  unsetenv(\"IN_ENV\");\n\n#ifndef BENCHMARK_OS_WINDOWS\n  ASSERT_EQ(setenv(\"IN_ENV\", \"\", 1), 0);\n  EXPECT_EQ(BoolFromEnv(\"in_env\", false), true);\n  unsetenv(\"IN_ENV\");\n#endif\n}\n\nTEST(Int32FromEnv, NotInEnv) {\n  ASSERT_EQ(unsetenv(\"NOT_IN_ENV\"), 0);\n  EXPECT_EQ(Int32FromEnv(\"not_in_env\", 42), 42);\n}\n\nTEST(Int32FromEnv, InvalidInteger) {\n  ASSERT_EQ(setenv(\"IN_ENV\", \"foo\", 1), 0);\n  EXPECT_EQ(Int32FromEnv(\"in_env\", 42), 42);\n  unsetenv(\"IN_ENV\");\n}\n\nTEST(Int32FromEnv, ValidInteger) {\n  ASSERT_EQ(setenv(\"IN_ENV\", \"42\", 1), 0);\n  EXPECT_EQ(Int32FromEnv(\"in_env\", 64), 42);\n  unsetenv(\"IN_ENV\");\n}\n\nTEST(DoubleFromEnv, NotInEnv) {\n  ASSERT_EQ(unsetenv(\"NOT_IN_ENV\"), 0);\n  EXPECT_EQ(DoubleFromEnv(\"not_in_env\", 0.51), 0.51);\n}\n\nTEST(DoubleFromEnv, InvalidReal) {\n  ASSERT_EQ(setenv(\"IN_ENV\", \"foo\", 1), 0);\n  EXPECT_EQ(DoubleFromEnv(\"in_env\", 0.51), 0.51);\n  unsetenv(\"IN_ENV\");\n}\n\nTEST(DoubleFromEnv, ValidReal) {\n  ASSERT_EQ(setenv(\"IN_ENV\", \"0.51\", 1), 0);\n  EXPECT_EQ(DoubleFromEnv(\"in_env\", 0.71), 0.51);\n  unsetenv(\"IN_ENV\");\n}\n\nTEST(StringFromEnv, Default) {\n  ASSERT_EQ(unsetenv(\"NOT_IN_ENV\"), 0);\n  EXPECT_STREQ(StringFromEnv(\"not_in_env\", \"foo\"), \"foo\");\n}\n\nTEST(StringFromEnv, Valid) {\n  ASSERT_EQ(setenv(\"IN_ENV\", \"foo\", 1), 0);\n  EXPECT_STREQ(StringFromEnv(\"in_env\", \"bar\"), \"foo\");\n  unsetenv(\"IN_ENV\");\n}\n\nTEST(KvPairsFromEnv, Default) {\n  ASSERT_EQ(unsetenv(\"NOT_IN_ENV\"), 0);\n  EXPECT_THAT(KvPairsFromEnv(\"not_in_env\", {{\"foo\", \"bar\"}}),\n              testing::ElementsAre(testing::Pair(\"foo\", \"bar\")));\n}\n\nTEST(KvPairsFromEnv, MalformedReturnsDefault) {\n  ASSERT_EQ(setenv(\"IN_ENV\", \"foo\", 1), 0);\n  EXPECT_THAT(KvPairsFromEnv(\"in_env\", {{\"foo\", \"bar\"}}),\n              testing::ElementsAre(testing::Pair(\"foo\", \"bar\")));\n  unsetenv(\"IN_ENV\");\n}\n\nTEST(KvPairsFromEnv, Single) {\n  ASSERT_EQ(setenv(\"IN_ENV\", \"foo=bar\", 1), 0);\n  EXPECT_THAT(KvPairsFromEnv(\"in_env\", {}),\n              testing::ElementsAre(testing::Pair(\"foo\", \"bar\")));\n  unsetenv(\"IN_ENV\");\n}\n\nTEST(KvPairsFromEnv, Multiple) {\n  ASSERT_EQ(setenv(\"IN_ENV\", \"foo=bar,baz=qux\", 1), 0);\n  EXPECT_THAT(KvPairsFromEnv(\"in_env\", {}),\n              testing::UnorderedElementsAre(testing::Pair(\"foo\", \"bar\"),\n                                            testing::Pair(\"baz\", \"qux\")));\n  unsetenv(\"IN_ENV\");\n}\n\n}  // namespace\n}  // namespace benchmark\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/complexity_test.cc",
    "content": "#undef NDEBUG\n#include <algorithm>\n#include <cassert>\n#include <cmath>\n#include <cstdlib>\n#include <vector>\n\n#include \"benchmark/benchmark.h\"\n#include \"output_test.h\"\n\nnamespace {\n\n#define ADD_COMPLEXITY_CASES(...) \\\n  int CONCAT(dummy, __LINE__) = AddComplexityTest(__VA_ARGS__)\n\nint AddComplexityTest(const std::string &test_name,\n                      const std::string &big_o_test_name,\n                      const std::string &rms_test_name,\n                      const std::string &big_o, int family_index) {\n  SetSubstitutions({{\"%name\", test_name},\n                    {\"%bigo_name\", big_o_test_name},\n                    {\"%rms_name\", rms_test_name},\n                    {\"%bigo_str\", \"[ ]* %float \" + big_o},\n                    {\"%bigo\", big_o},\n                    {\"%rms\", \"[ ]*[0-9]+ %\"}});\n  AddCases(\n      TC_ConsoleOut,\n      {{\"^%bigo_name %bigo_str %bigo_str[ ]*$\"},\n       {\"^%bigo_name\", MR_Not},  // Assert we we didn't only matched a name.\n       {\"^%rms_name %rms %rms[ ]*$\", MR_Next}});\n  AddCases(\n      TC_JSONOut,\n      {{\"\\\"name\\\": \\\"%bigo_name\\\",$\"},\n       {\"\\\"family_index\\\": \" + std::to_string(family_index) + \",$\", MR_Next},\n       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n       {\"\\\"run_name\\\": \\\"%name\\\",$\", MR_Next},\n       {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n       {\"\\\"repetitions\\\": %int,$\", MR_Next},\n       {\"\\\"threads\\\": 1,$\", MR_Next},\n       {\"\\\"aggregate_name\\\": \\\"BigO\\\",$\", MR_Next},\n       {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n       {\"\\\"cpu_coefficient\\\": %float,$\", MR_Next},\n       {\"\\\"real_coefficient\\\": %float,$\", MR_Next},\n       {\"\\\"big_o\\\": \\\"%bigo\\\",$\", MR_Next},\n       {\"\\\"time_unit\\\": \\\"ns\\\"$\", MR_Next},\n       {\"}\", MR_Next},\n       {\"\\\"name\\\": \\\"%rms_name\\\",$\"},\n       {\"\\\"family_index\\\": \" + std::to_string(family_index) + \",$\", MR_Next},\n       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n       {\"\\\"run_name\\\": \\\"%name\\\",$\", MR_Next},\n       {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n       {\"\\\"repetitions\\\": %int,$\", MR_Next},\n       {\"\\\"threads\\\": 1,$\", MR_Next},\n       {\"\\\"aggregate_name\\\": \\\"RMS\\\",$\", MR_Next},\n       {\"\\\"aggregate_unit\\\": \\\"percentage\\\",$\", MR_Next},\n       {\"\\\"rms\\\": %float$\", MR_Next},\n       {\"}\", MR_Next}});\n  AddCases(TC_CSVOut, {{\"^\\\"%bigo_name\\\",,%float,%float,%bigo,,,,,$\"},\n                       {\"^\\\"%bigo_name\\\"\", MR_Not},\n                       {\"^\\\"%rms_name\\\",,%float,%float,,,,,,$\", MR_Next}});\n  return 0;\n}\n\n}  // end namespace\n\n// ========================================================================= //\n// --------------------------- Testing BigO O(1) --------------------------- //\n// ========================================================================= //\n\nvoid BM_Complexity_O1(benchmark::State &state) {\n  for (auto _ : state) {\n    for (int i = 0; i < 1024; ++i) {\n      benchmark::DoNotOptimize(i);\n    }\n  }\n  state.SetComplexityN(state.range(0));\n}\nBENCHMARK(BM_Complexity_O1)->Range(1, 1 << 18)->Complexity(benchmark::o1);\nBENCHMARK(BM_Complexity_O1)->Range(1, 1 << 18)->Complexity();\nBENCHMARK(BM_Complexity_O1)\n    ->Range(1, 1 << 18)\n    ->Complexity([](benchmark::IterationCount) { return 1.0; });\n\nconst char *one_test_name = \"BM_Complexity_O1\";\nconst char *big_o_1_test_name = \"BM_Complexity_O1_BigO\";\nconst char *rms_o_1_test_name = \"BM_Complexity_O1_RMS\";\nconst char *enum_big_o_1 = \"\\\\([0-9]+\\\\)\";\n// FIXME: Tolerate both '(1)' and 'lgN' as output when the complexity is auto\n// deduced.\n// See https://github.com/google/benchmark/issues/272\nconst char *auto_big_o_1 = \"(\\\\([0-9]+\\\\))|(lgN)\";\nconst char *lambda_big_o_1 = \"f\\\\(N\\\\)\";\n\n// Add enum tests\nADD_COMPLEXITY_CASES(one_test_name, big_o_1_test_name, rms_o_1_test_name,\n                     enum_big_o_1, /*family_index=*/0);\n\n// Add auto enum tests\nADD_COMPLEXITY_CASES(one_test_name, big_o_1_test_name, rms_o_1_test_name,\n                     auto_big_o_1, /*family_index=*/1);\n\n// Add lambda tests\nADD_COMPLEXITY_CASES(one_test_name, big_o_1_test_name, rms_o_1_test_name,\n                     lambda_big_o_1, /*family_index=*/2);\n\n// ========================================================================= //\n// --------------------------- Testing BigO O(N) --------------------------- //\n// ========================================================================= //\n\nstd::vector<int> ConstructRandomVector(int64_t size) {\n  std::vector<int> v;\n  v.reserve(static_cast<size_t>(size));\n  for (int i = 0; i < size; ++i) {\n    v.push_back(static_cast<int>(std::rand() % size));\n  }\n  return v;\n}\n\nvoid BM_Complexity_O_N(benchmark::State &state) {\n  auto v = ConstructRandomVector(state.range(0));\n  // Test worst case scenario (item not in vector)\n  const int64_t item_not_in_vector = state.range(0) * 2;\n  for (auto _ : state) {\n    auto it = std::find(v.begin(), v.end(), item_not_in_vector);\n    benchmark::DoNotOptimize(it);\n  }\n  state.SetComplexityN(state.range(0));\n}\nBENCHMARK(BM_Complexity_O_N)\n    ->RangeMultiplier(2)\n    ->Range(1 << 10, 1 << 16)\n    ->Complexity(benchmark::oN);\nBENCHMARK(BM_Complexity_O_N)\n    ->RangeMultiplier(2)\n    ->Range(1 << 10, 1 << 16)\n    ->Complexity([](benchmark::IterationCount n) -> double {\n      return static_cast<double>(n);\n    });\nBENCHMARK(BM_Complexity_O_N)\n    ->RangeMultiplier(2)\n    ->Range(1 << 10, 1 << 16)\n    ->Complexity();\n\nconst char *n_test_name = \"BM_Complexity_O_N\";\nconst char *big_o_n_test_name = \"BM_Complexity_O_N_BigO\";\nconst char *rms_o_n_test_name = \"BM_Complexity_O_N_RMS\";\nconst char *enum_auto_big_o_n = \"N\";\nconst char *lambda_big_o_n = \"f\\\\(N\\\\)\";\n\n// Add enum tests\nADD_COMPLEXITY_CASES(n_test_name, big_o_n_test_name, rms_o_n_test_name,\n                     enum_auto_big_o_n, /*family_index=*/3);\n\n// Add lambda tests\nADD_COMPLEXITY_CASES(n_test_name, big_o_n_test_name, rms_o_n_test_name,\n                     lambda_big_o_n, /*family_index=*/4);\n\n// ========================================================================= //\n// ------------------------- Testing BigO O(N*lgN) ------------------------- //\n// ========================================================================= //\n\nstatic void BM_Complexity_O_N_log_N(benchmark::State &state) {\n  auto v = ConstructRandomVector(state.range(0));\n  for (auto _ : state) {\n    std::sort(v.begin(), v.end());\n  }\n  state.SetComplexityN(state.range(0));\n}\nstatic const double kLog2E = 1.44269504088896340736;\nBENCHMARK(BM_Complexity_O_N_log_N)\n    ->RangeMultiplier(2)\n    ->Range(1 << 10, 1 << 16)\n    ->Complexity(benchmark::oNLogN);\nBENCHMARK(BM_Complexity_O_N_log_N)\n    ->RangeMultiplier(2)\n    ->Range(1 << 10, 1 << 16)\n    ->Complexity([](benchmark::IterationCount n) {\n      return kLog2E * static_cast<double>(n) * log(static_cast<double>(n));\n    });\nBENCHMARK(BM_Complexity_O_N_log_N)\n    ->RangeMultiplier(2)\n    ->Range(1 << 10, 1 << 16)\n    ->Complexity();\n\nconst char *n_lg_n_test_name = \"BM_Complexity_O_N_log_N\";\nconst char *big_o_n_lg_n_test_name = \"BM_Complexity_O_N_log_N_BigO\";\nconst char *rms_o_n_lg_n_test_name = \"BM_Complexity_O_N_log_N_RMS\";\nconst char *enum_auto_big_o_n_lg_n = \"NlgN\";\nconst char *lambda_big_o_n_lg_n = \"f\\\\(N\\\\)\";\n\n// Add enum tests\nADD_COMPLEXITY_CASES(n_lg_n_test_name, big_o_n_lg_n_test_name,\n                     rms_o_n_lg_n_test_name, enum_auto_big_o_n_lg_n,\n                     /*family_index=*/6);\n\n// Add lambda tests\nADD_COMPLEXITY_CASES(n_lg_n_test_name, big_o_n_lg_n_test_name,\n                     rms_o_n_lg_n_test_name, lambda_big_o_n_lg_n,\n                     /*family_index=*/7);\n\n// ========================================================================= //\n// -------- Testing formatting of Complexity with captured args ------------ //\n// ========================================================================= //\n\nvoid BM_ComplexityCaptureArgs(benchmark::State &state, int n) {\n  for (auto _ : state) {\n    // This test requires a non-zero CPU time to avoid divide-by-zero\n    auto iterations = state.iterations();\n    benchmark::DoNotOptimize(iterations);\n  }\n  state.SetComplexityN(n);\n}\n\nBENCHMARK_CAPTURE(BM_ComplexityCaptureArgs, capture_test, 100)\n    ->Complexity(benchmark::oN)\n    ->Ranges({{1, 2}, {3, 4}});\n\nconst std::string complexity_capture_name =\n    \"BM_ComplexityCaptureArgs/capture_test\";\n\nADD_COMPLEXITY_CASES(complexity_capture_name, complexity_capture_name + \"_BigO\",\n                     complexity_capture_name + \"_RMS\", \"N\", /*family_index=*/9);\n\n// ========================================================================= //\n// --------------------------- TEST CASES END ------------------------------ //\n// ========================================================================= //\n\nint main(int argc, char *argv[]) { RunOutputTests(argc, argv); }\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/cxx03_test.cc",
    "content": "#undef NDEBUG\n#include <cassert>\n#include <cstddef>\n\n#include \"benchmark/benchmark.h\"\n\n#if __cplusplus >= 201103L\n#error C++11 or greater detected. Should be C++03.\n#endif\n\n#ifdef BENCHMARK_HAS_CXX11\n#error C++11 or greater detected by the library. BENCHMARK_HAS_CXX11 is defined.\n#endif\n\nvoid BM_empty(benchmark::State& state) {\n  while (state.KeepRunning()) {\n    volatile benchmark::IterationCount x = state.iterations();\n    ((void)x);\n  }\n}\nBENCHMARK(BM_empty);\n\n// The new C++11 interface for args/ranges requires initializer list support.\n// Therefore we provide the old interface to support C++03.\nvoid BM_old_arg_range_interface(benchmark::State& state) {\n  assert((state.range(0) == 1 && state.range(1) == 2) ||\n         (state.range(0) == 5 && state.range(1) == 6));\n  while (state.KeepRunning()) {\n  }\n}\nBENCHMARK(BM_old_arg_range_interface)->ArgPair(1, 2)->RangePair(5, 5, 6, 6);\n\ntemplate <class T, class U>\nvoid BM_template2(benchmark::State& state) {\n  BM_empty(state);\n}\nBENCHMARK_TEMPLATE2(BM_template2, int, long);\n\ntemplate <class T>\nvoid BM_template1(benchmark::State& state) {\n  BM_empty(state);\n}\nBENCHMARK_TEMPLATE(BM_template1, long);\nBENCHMARK_TEMPLATE1(BM_template1, int);\n\ntemplate <class T>\nstruct BM_Fixture : public ::benchmark::Fixture {};\n\nBENCHMARK_TEMPLATE_F(BM_Fixture, BM_template1, long)(benchmark::State& state) {\n  BM_empty(state);\n}\nBENCHMARK_TEMPLATE1_F(BM_Fixture, BM_template2, int)(benchmark::State& state) {\n  BM_empty(state);\n}\n\nvoid BM_counters(benchmark::State& state) {\n  BM_empty(state);\n  state.counters[\"Foo\"] = 2;\n}\nBENCHMARK(BM_counters);\n\nBENCHMARK_MAIN();\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/diagnostics_test.cc",
    "content": "// Testing:\n//   State::PauseTiming()\n//   State::ResumeTiming()\n// Test that CHECK's within these function diagnose when they are called\n// outside of the KeepRunning() loop.\n//\n// NOTE: Users should NOT include or use src/check.h. This is only done in\n// order to test library internals.\n\n#include <cstdlib>\n#include <stdexcept>\n\n#include \"../src/check.h\"\n#include \"benchmark/benchmark.h\"\n\n#if defined(__GNUC__) && !defined(__EXCEPTIONS)\n#define TEST_HAS_NO_EXCEPTIONS\n#endif\n\nvoid TestHandler() {\n#ifndef TEST_HAS_NO_EXCEPTIONS\n  throw std::logic_error(\"\");\n#else\n  std::abort();\n#endif\n}\n\nvoid try_invalid_pause_resume(benchmark::State& state) {\n#if !defined(TEST_BENCHMARK_LIBRARY_HAS_NO_ASSERTIONS) && \\\n    !defined(TEST_HAS_NO_EXCEPTIONS)\n  try {\n    state.PauseTiming();\n    std::abort();\n  } catch (std::logic_error const&) {\n  }\n  try {\n    state.ResumeTiming();\n    std::abort();\n  } catch (std::logic_error const&) {\n  }\n#else\n  (void)state;  // avoid unused warning\n#endif\n}\n\nvoid BM_diagnostic_test(benchmark::State& state) {\n  static bool called_once = false;\n\n  if (called_once == false) try_invalid_pause_resume(state);\n\n  for (auto _ : state) {\n    auto iterations = state.iterations();\n    benchmark::DoNotOptimize(iterations);\n  }\n\n  if (called_once == false) try_invalid_pause_resume(state);\n\n  called_once = true;\n}\nBENCHMARK(BM_diagnostic_test);\n\nvoid BM_diagnostic_test_keep_running(benchmark::State& state) {\n  static bool called_once = false;\n\n  if (called_once == false) try_invalid_pause_resume(state);\n\n  while (state.KeepRunning()) {\n    auto iterations = state.iterations();\n    benchmark::DoNotOptimize(iterations);\n  }\n\n  if (called_once == false) try_invalid_pause_resume(state);\n\n  called_once = true;\n}\nBENCHMARK(BM_diagnostic_test_keep_running);\n\nint main(int argc, char* argv[]) {\n#ifdef NDEBUG\n  // This test is exercising functionality for debug builds, which are not\n  // available in release builds. Skip the test if we are in that environment\n  // to avoid a test failure.\n  std::cout << \"Diagnostic test disabled in release build\" << std::endl;\n  (void)argc;\n  (void)argv;\n#else\n  benchmark::internal::GetAbortHandler() = &TestHandler;\n  benchmark::Initialize(&argc, argv);\n  benchmark::RunSpecifiedBenchmarks();\n#endif\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/display_aggregates_only_test.cc",
    "content": "\n#undef NDEBUG\n#include <cstdio>\n#include <string>\n\n#include \"benchmark/benchmark.h\"\n#include \"output_test.h\"\n\n// Ok this test is super ugly. We want to check what happens with the file\n// reporter in the presence of DisplayAggregatesOnly().\n// We do not care about console output, the normal tests check that already.\n\nvoid BM_SummaryRepeat(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_SummaryRepeat)->Repetitions(3)->DisplayAggregatesOnly();\n\nint main(int argc, char* argv[]) {\n  const std::string output = GetFileReporterOutput(argc, argv);\n\n  if (SubstrCnt(output, \"\\\"name\\\": \\\"BM_SummaryRepeat/repeats:3\") != 7 ||\n      SubstrCnt(output, \"\\\"name\\\": \\\"BM_SummaryRepeat/repeats:3\\\"\") != 3 ||\n      SubstrCnt(output, \"\\\"name\\\": \\\"BM_SummaryRepeat/repeats:3_mean\\\"\") != 1 ||\n      SubstrCnt(output, \"\\\"name\\\": \\\"BM_SummaryRepeat/repeats:3_median\\\"\") !=\n          1 ||\n      SubstrCnt(output, \"\\\"name\\\": \\\"BM_SummaryRepeat/repeats:3_stddev\\\"\") !=\n          1 ||\n      SubstrCnt(output, \"\\\"name\\\": \\\"BM_SummaryRepeat/repeats:3_cv\\\"\") != 1) {\n    std::cout << \"Precondition mismatch. Expected to only find 8 \"\n                 \"occurrences of \\\"BM_SummaryRepeat/repeats:3\\\" substring:\\n\"\n                 \"\\\"name\\\": \\\"BM_SummaryRepeat/repeats:3\\\", \"\n                 \"\\\"name\\\": \\\"BM_SummaryRepeat/repeats:3\\\", \"\n                 \"\\\"name\\\": \\\"BM_SummaryRepeat/repeats:3\\\", \"\n                 \"\\\"name\\\": \\\"BM_SummaryRepeat/repeats:3_mean\\\", \"\n                 \"\\\"name\\\": \\\"BM_SummaryRepeat/repeats:3_median\\\", \"\n                 \"\\\"name\\\": \\\"BM_SummaryRepeat/repeats:3_stddev\\\", \"\n                 \"\\\"name\\\": \\\"BM_SummaryRepeat/repeats:3_cv\\\"\\nThe entire \"\n                 \"output:\\n\";\n    std::cout << output;\n    return 1;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/donotoptimize_assembly_test.cc",
    "content": "#include <benchmark/benchmark.h>\n\n#ifdef __clang__\n#pragma clang diagnostic ignored \"-Wreturn-type\"\n#endif\nBENCHMARK_DISABLE_DEPRECATED_WARNING\n\nextern \"C\" {\n\nextern int ExternInt;\nextern int ExternInt2;\nextern int ExternInt3;\nextern int BigArray[2049];\n\nconst int ConstBigArray[2049]{};\n\ninline int Add42(int x) { return x + 42; }\n\nstruct NotTriviallyCopyable {\n  NotTriviallyCopyable();\n  explicit NotTriviallyCopyable(int x) : value(x) {}\n  NotTriviallyCopyable(NotTriviallyCopyable const &);\n  int value;\n};\n\nstruct Large {\n  int value;\n  int data[2];\n};\n\nstruct ExtraLarge {\n  int arr[2049];\n};\n}\n\nextern ExtraLarge ExtraLargeObj;\nconst ExtraLarge ConstExtraLargeObj{};\n\n// CHECK-LABEL: test_with_rvalue:\nextern \"C\" void test_with_rvalue() {\n  benchmark::DoNotOptimize(Add42(0));\n  // CHECK: movl $42, %eax\n  // CHECK: ret\n}\n\n// CHECK-LABEL: test_with_large_rvalue:\nextern \"C\" void test_with_large_rvalue() {\n  benchmark::DoNotOptimize(Large{ExternInt, {ExternInt, ExternInt}});\n  // CHECK: ExternInt(%rip)\n  // CHECK: movl %eax, -{{[0-9]+}}(%[[REG:[a-z]+]]\n  // CHECK: movl %eax, -{{[0-9]+}}(%[[REG]])\n  // CHECK: movl %eax, -{{[0-9]+}}(%[[REG]])\n  // CHECK: ret\n}\n\n// CHECK-LABEL: test_with_non_trivial_rvalue:\nextern \"C\" void test_with_non_trivial_rvalue() {\n  benchmark::DoNotOptimize(NotTriviallyCopyable(ExternInt));\n  // CHECK: mov{{l|q}} ExternInt(%rip)\n  // CHECK: ret\n}\n\n// CHECK-LABEL: test_with_lvalue:\nextern \"C\" void test_with_lvalue() {\n  int x = 101;\n  benchmark::DoNotOptimize(x);\n  // CHECK-GNU: movl $101, %eax\n  // CHECK-CLANG: movl $101, -{{[0-9]+}}(%[[REG:[a-z]+]])\n  // CHECK: ret\n}\n\n// CHECK-LABEL: test_with_large_lvalue:\nextern \"C\" void test_with_large_lvalue() {\n  Large L{ExternInt, {ExternInt, ExternInt}};\n  benchmark::DoNotOptimize(L);\n  // CHECK: ExternInt(%rip)\n  // CHECK: movl %eax, -{{[0-9]+}}(%[[REG:[a-z]+]])\n  // CHECK: movl %eax, -{{[0-9]+}}(%[[REG]])\n  // CHECK: movl %eax, -{{[0-9]+}}(%[[REG]])\n  // CHECK: ret\n}\n\n// CHECK-LABEL: test_with_extra_large_lvalue_with_op:\nextern \"C\" void test_with_extra_large_lvalue_with_op() {\n  ExtraLargeObj.arr[16] = 42;\n  benchmark::DoNotOptimize(ExtraLargeObj);\n  // CHECK: movl $42, ExtraLargeObj+64(%rip)\n  // CHECK: ret\n}\n\n// CHECK-LABEL: test_with_big_array_with_op\nextern \"C\" void test_with_big_array_with_op() {\n  BigArray[16] = 42;\n  benchmark::DoNotOptimize(BigArray);\n  // CHECK: movl $42, BigArray+64(%rip)\n  // CHECK: ret\n}\n\n// CHECK-LABEL: test_with_non_trivial_lvalue:\nextern \"C\" void test_with_non_trivial_lvalue() {\n  NotTriviallyCopyable NTC(ExternInt);\n  benchmark::DoNotOptimize(NTC);\n  // CHECK: ExternInt(%rip)\n  // CHECK: movl %eax, -{{[0-9]+}}(%[[REG:[a-z]+]])\n  // CHECK: ret\n}\n\n// CHECK-LABEL: test_with_const_lvalue:\nextern \"C\" void test_with_const_lvalue() {\n  const int x = 123;\n  benchmark::DoNotOptimize(x);\n  // CHECK: movl $123, %eax\n  // CHECK: ret\n}\n\n// CHECK-LABEL: test_with_large_const_lvalue:\nextern \"C\" void test_with_large_const_lvalue() {\n  const Large L{ExternInt, {ExternInt, ExternInt}};\n  benchmark::DoNotOptimize(L);\n  // CHECK: ExternInt(%rip)\n  // CHECK: movl %eax, -{{[0-9]+}}(%[[REG:[a-z]+]])\n  // CHECK: movl %eax, -{{[0-9]+}}(%[[REG]])\n  // CHECK: movl %eax, -{{[0-9]+}}(%[[REG]])\n  // CHECK: ret\n}\n\n// CHECK-LABEL: test_with_const_extra_large_obj:\nextern \"C\" void test_with_const_extra_large_obj() {\n  benchmark::DoNotOptimize(ConstExtraLargeObj);\n  // CHECK: ret\n}\n\n// CHECK-LABEL: test_with_const_big_array\nextern \"C\" void test_with_const_big_array() {\n  benchmark::DoNotOptimize(ConstBigArray);\n  // CHECK: ret\n}\n\n// CHECK-LABEL: test_with_non_trivial_const_lvalue:\nextern \"C\" void test_with_non_trivial_const_lvalue() {\n  const NotTriviallyCopyable Obj(ExternInt);\n  benchmark::DoNotOptimize(Obj);\n  // CHECK: mov{{q|l}} ExternInt(%rip)\n  // CHECK: ret\n}\n\n// CHECK-LABEL: test_div_by_two:\nextern \"C\" int test_div_by_two(int input) {\n  int divisor = 2;\n  benchmark::DoNotOptimize(divisor);\n  return input / divisor;\n  // CHECK: movl $2, [[DEST:.*]]\n  // CHECK: idivl [[DEST]]\n  // CHECK: ret\n}\n\n// CHECK-LABEL: test_inc_integer:\nextern \"C\" int test_inc_integer() {\n  int x = 0;\n  for (int i = 0; i < 5; ++i) benchmark::DoNotOptimize(++x);\n  // CHECK: movl $1, [[DEST:.*]]\n  // CHECK: {{(addl \\$1,|incl)}} [[DEST]]\n  // CHECK: {{(addl \\$1,|incl)}} [[DEST]]\n  // CHECK: {{(addl \\$1,|incl)}} [[DEST]]\n  // CHECK: {{(addl \\$1,|incl)}} [[DEST]]\n  // CHECK-CLANG: movl [[DEST]], %eax\n  // CHECK: ret\n  return x;\n}\n\n// CHECK-LABEL: test_pointer_rvalue\nextern \"C\" void test_pointer_rvalue() {\n  // CHECK: movl $42, [[DEST:.*]]\n  // CHECK: leaq [[DEST]], %rax\n  // CHECK-CLANG: movq %rax, -{{[0-9]+}}(%[[REG:[a-z]+]])\n  // CHECK: ret\n  int x = 42;\n  benchmark::DoNotOptimize(&x);\n}\n\n// CHECK-LABEL: test_pointer_const_lvalue:\nextern \"C\" void test_pointer_const_lvalue() {\n  // CHECK: movl $42, [[DEST:.*]]\n  // CHECK: leaq [[DEST]], %rax\n  // CHECK-CLANG: movq %rax, -{{[0-9]+}}(%[[REG:[a-z]+]])\n  // CHECK: ret\n  int x = 42;\n  int *const xp = &x;\n  benchmark::DoNotOptimize(xp);\n}\n\n// CHECK-LABEL: test_pointer_lvalue:\nextern \"C\" void test_pointer_lvalue() {\n  // CHECK: movl $42, [[DEST:.*]]\n  // CHECK: leaq [[DEST]], %rax\n  // CHECK-CLANG: movq %rax, -{{[0-9]+}}(%[[REG:[a-z+]+]])\n  // CHECK: ret\n  int x = 42;\n  int *xp = &x;\n  benchmark::DoNotOptimize(xp);\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/donotoptimize_test.cc",
    "content": "#include <cstdint>\n\n#include \"benchmark/benchmark.h\"\n\nnamespace {\n#if defined(__GNUC__)\nstd::int64_t double_up(const std::int64_t x) __attribute__((const));\n#endif\nstd::int64_t double_up(const std::int64_t x) { return x * 2; }\n}  // namespace\n\n// Using DoNotOptimize on types like BitRef seem to cause a lot of problems\n// with the inline assembly on both GCC and Clang.\nstruct BitRef {\n  int index;\n  unsigned char& byte;\n\n public:\n  static BitRef Make() {\n    static unsigned char arr[2] = {};\n    BitRef b(1, arr[0]);\n    return b;\n  }\n\n private:\n  BitRef(int i, unsigned char& b) : index(i), byte(b) {}\n};\n\nint main(int, char*[]) {\n  // this test verifies compilation of DoNotOptimize() for some types\n\n  char buffer1[1] = \"\";\n  benchmark::DoNotOptimize(buffer1);\n\n  char buffer2[2] = \"\";\n  benchmark::DoNotOptimize(buffer2);\n\n  char buffer3[3] = \"\";\n  benchmark::DoNotOptimize(buffer3);\n\n  char buffer8[8] = \"\";\n  benchmark::DoNotOptimize(buffer8);\n\n  char buffer20[20] = \"\";\n  benchmark::DoNotOptimize(buffer20);\n\n  char buffer1024[1024] = \"\";\n  benchmark::DoNotOptimize(buffer1024);\n  char* bptr = &buffer1024[0];\n  benchmark::DoNotOptimize(bptr);\n\n  int x = 123;\n  benchmark::DoNotOptimize(x);\n  int* xp = &x;\n  benchmark::DoNotOptimize(xp);\n  benchmark::DoNotOptimize(x += 42);\n\n  std::int64_t y = double_up(x);\n  benchmark::DoNotOptimize(y);\n\n  // These tests are to e\n  BitRef lval = BitRef::Make();\n  benchmark::DoNotOptimize(lval);\n\n#ifdef BENCHMARK_HAS_CXX11\n  // Check that accept rvalue.\n  benchmark::DoNotOptimize(BitRef::Make());\n#endif\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/filter_test.cc",
    "content": "#include <algorithm>\n#include <cassert>\n#include <cmath>\n#include <cstdint>\n#include <cstdlib>\n#include <iostream>\n#include <limits>\n#include <sstream>\n#include <string>\n\n#include \"benchmark/benchmark.h\"\n\nnamespace {\n\nclass TestReporter : public benchmark::ConsoleReporter {\n public:\n  bool ReportContext(const Context& context) override {\n    return ConsoleReporter::ReportContext(context);\n  };\n\n  void ReportRuns(const std::vector<Run>& report) override {\n    ++count_;\n    max_family_index_ = std::max(max_family_index_, report[0].family_index);\n    ConsoleReporter::ReportRuns(report);\n  };\n\n  TestReporter() : count_(0), max_family_index_(0) {}\n\n  ~TestReporter() override {}\n\n  int GetCount() const { return count_; }\n\n  int64_t GetMaxFamilyIndex() const { return max_family_index_; }\n\n private:\n  mutable int count_;\n  mutable int64_t max_family_index_;\n};\n\n}  // end namespace\n\nstatic void NoPrefix(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(NoPrefix);\n\nstatic void BM_Foo(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_Foo);\n\nstatic void BM_Bar(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_Bar);\n\nstatic void BM_FooBar(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_FooBar);\n\nstatic void BM_FooBa(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_FooBa);\n\nint main(int argc, char** argv) {\n  bool list_only = false;\n  for (int i = 0; i < argc; ++i)\n    list_only |= std::string(argv[i]).find(\"--benchmark_list_tests\") !=\n                 std::string::npos;\n\n  benchmark::Initialize(&argc, argv);\n\n  TestReporter test_reporter;\n  const int64_t returned_count =\n      static_cast<int64_t>(benchmark::RunSpecifiedBenchmarks(&test_reporter));\n\n  if (argc == 2) {\n    // Make sure we ran all of the tests\n    std::stringstream ss(argv[1]);\n    int64_t expected_return;\n    ss >> expected_return;\n\n    if (returned_count != expected_return) {\n      std::cerr << \"ERROR: Expected \" << expected_return\n                << \" tests to match the filter but returned_count = \"\n                << returned_count << std::endl;\n      return -1;\n    }\n\n    const int64_t expected_reports = list_only ? 0 : expected_return;\n    const int64_t reports_count = test_reporter.GetCount();\n    if (reports_count != expected_reports) {\n      std::cerr << \"ERROR: Expected \" << expected_reports\n                << \" tests to be run but reported_count = \" << reports_count\n                << std::endl;\n      return -1;\n    }\n\n    const int64_t max_family_index = test_reporter.GetMaxFamilyIndex();\n    const int64_t num_families = reports_count == 0 ? 0 : 1 + max_family_index;\n    if (num_families != expected_reports) {\n      std::cerr << \"ERROR: Expected \" << expected_reports\n                << \" test families to be run but num_families = \"\n                << num_families << std::endl;\n      return -1;\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/fixture_test.cc",
    "content": "\n#include <cassert>\n#include <memory>\n\n#include \"benchmark/benchmark.h\"\n\n#define FIXTURE_BECHMARK_NAME MyFixture\n\nclass FIXTURE_BECHMARK_NAME : public ::benchmark::Fixture {\n public:\n  void SetUp(const ::benchmark::State& state) override {\n    if (state.thread_index() == 0) {\n      assert(data.get() == nullptr);\n      data.reset(new int(42));\n    }\n  }\n\n  void TearDown(const ::benchmark::State& state) override {\n    if (state.thread_index() == 0) {\n      assert(data.get() != nullptr);\n      data.reset();\n    }\n  }\n\n  ~FIXTURE_BECHMARK_NAME() override { assert(data == nullptr); }\n\n  std::unique_ptr<int> data;\n};\n\nBENCHMARK_F(FIXTURE_BECHMARK_NAME, Foo)(benchmark::State& st) {\n  assert(data.get() != nullptr);\n  assert(*data == 42);\n  for (auto _ : st) {\n  }\n}\n\nBENCHMARK_DEFINE_F(FIXTURE_BECHMARK_NAME, Bar)(benchmark::State& st) {\n  if (st.thread_index() == 0) {\n    assert(data.get() != nullptr);\n    assert(*data == 42);\n  }\n  for (auto _ : st) {\n    assert(data.get() != nullptr);\n    assert(*data == 42);\n  }\n  st.SetItemsProcessed(st.range(0));\n}\nBENCHMARK_REGISTER_F(FIXTURE_BECHMARK_NAME, Bar)->Arg(42);\nBENCHMARK_REGISTER_F(FIXTURE_BECHMARK_NAME, Bar)->Arg(42)->ThreadPerCpu();\n\nBENCHMARK_MAIN();\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/internal_threading_test.cc",
    "content": "\n#undef NDEBUG\n\n#include <chrono>\n#include <thread>\n\n#include \"../src/timers.h\"\n#include \"benchmark/benchmark.h\"\n#include \"output_test.h\"\n\nstatic const std::chrono::duration<double, std::milli> time_frame(50);\nstatic const double time_frame_in_sec(\n    std::chrono::duration_cast<std::chrono::duration<double, std::ratio<1, 1>>>(\n        time_frame)\n        .count());\n\nvoid MyBusySpinwait() {\n  const auto start = benchmark::ChronoClockNow();\n\n  while (true) {\n    const auto now = benchmark::ChronoClockNow();\n    const auto elapsed = now - start;\n\n    if (std::chrono::duration<double, std::chrono::seconds::period>(elapsed) >=\n        time_frame)\n      return;\n  }\n}\n\n// ========================================================================= //\n// --------------------------- TEST CASES BEGIN ---------------------------- //\n// ========================================================================= //\n\n// ========================================================================= //\n// BM_MainThread\n\nvoid BM_MainThread(benchmark::State& state) {\n  for (auto _ : state) {\n    MyBusySpinwait();\n    state.SetIterationTime(time_frame_in_sec);\n  }\n  state.counters[\"invtime\"] =\n      benchmark::Counter{1, benchmark::Counter::kIsRate};\n}\n\nBENCHMARK(BM_MainThread)->Iterations(1)->Threads(1);\nBENCHMARK(BM_MainThread)->Iterations(1)->Threads(1)->UseRealTime();\nBENCHMARK(BM_MainThread)->Iterations(1)->Threads(1)->UseManualTime();\nBENCHMARK(BM_MainThread)->Iterations(1)->Threads(1)->MeasureProcessCPUTime();\nBENCHMARK(BM_MainThread)\n    ->Iterations(1)\n    ->Threads(1)\n    ->MeasureProcessCPUTime()\n    ->UseRealTime();\nBENCHMARK(BM_MainThread)\n    ->Iterations(1)\n    ->Threads(1)\n    ->MeasureProcessCPUTime()\n    ->UseManualTime();\n\nBENCHMARK(BM_MainThread)->Iterations(1)->Threads(2);\nBENCHMARK(BM_MainThread)->Iterations(1)->Threads(2)->UseRealTime();\nBENCHMARK(BM_MainThread)->Iterations(1)->Threads(2)->UseManualTime();\nBENCHMARK(BM_MainThread)->Iterations(1)->Threads(2)->MeasureProcessCPUTime();\nBENCHMARK(BM_MainThread)\n    ->Iterations(1)\n    ->Threads(2)\n    ->MeasureProcessCPUTime()\n    ->UseRealTime();\nBENCHMARK(BM_MainThread)\n    ->Iterations(1)\n    ->Threads(2)\n    ->MeasureProcessCPUTime()\n    ->UseManualTime();\n\n// ========================================================================= //\n// BM_WorkerThread\n\nvoid BM_WorkerThread(benchmark::State& state) {\n  for (auto _ : state) {\n    std::thread Worker(&MyBusySpinwait);\n    Worker.join();\n    state.SetIterationTime(time_frame_in_sec);\n  }\n  state.counters[\"invtime\"] =\n      benchmark::Counter{1, benchmark::Counter::kIsRate};\n}\n\nBENCHMARK(BM_WorkerThread)->Iterations(1)->Threads(1);\nBENCHMARK(BM_WorkerThread)->Iterations(1)->Threads(1)->UseRealTime();\nBENCHMARK(BM_WorkerThread)->Iterations(1)->Threads(1)->UseManualTime();\nBENCHMARK(BM_WorkerThread)->Iterations(1)->Threads(1)->MeasureProcessCPUTime();\nBENCHMARK(BM_WorkerThread)\n    ->Iterations(1)\n    ->Threads(1)\n    ->MeasureProcessCPUTime()\n    ->UseRealTime();\nBENCHMARK(BM_WorkerThread)\n    ->Iterations(1)\n    ->Threads(1)\n    ->MeasureProcessCPUTime()\n    ->UseManualTime();\n\nBENCHMARK(BM_WorkerThread)->Iterations(1)->Threads(2);\nBENCHMARK(BM_WorkerThread)->Iterations(1)->Threads(2)->UseRealTime();\nBENCHMARK(BM_WorkerThread)->Iterations(1)->Threads(2)->UseManualTime();\nBENCHMARK(BM_WorkerThread)->Iterations(1)->Threads(2)->MeasureProcessCPUTime();\nBENCHMARK(BM_WorkerThread)\n    ->Iterations(1)\n    ->Threads(2)\n    ->MeasureProcessCPUTime()\n    ->UseRealTime();\nBENCHMARK(BM_WorkerThread)\n    ->Iterations(1)\n    ->Threads(2)\n    ->MeasureProcessCPUTime()\n    ->UseManualTime();\n\n// ========================================================================= //\n// BM_MainThreadAndWorkerThread\n\nvoid BM_MainThreadAndWorkerThread(benchmark::State& state) {\n  for (auto _ : state) {\n    std::thread Worker(&MyBusySpinwait);\n    MyBusySpinwait();\n    Worker.join();\n    state.SetIterationTime(time_frame_in_sec);\n  }\n  state.counters[\"invtime\"] =\n      benchmark::Counter{1, benchmark::Counter::kIsRate};\n}\n\nBENCHMARK(BM_MainThreadAndWorkerThread)->Iterations(1)->Threads(1);\nBENCHMARK(BM_MainThreadAndWorkerThread)\n    ->Iterations(1)\n    ->Threads(1)\n    ->UseRealTime();\nBENCHMARK(BM_MainThreadAndWorkerThread)\n    ->Iterations(1)\n    ->Threads(1)\n    ->UseManualTime();\nBENCHMARK(BM_MainThreadAndWorkerThread)\n    ->Iterations(1)\n    ->Threads(1)\n    ->MeasureProcessCPUTime();\nBENCHMARK(BM_MainThreadAndWorkerThread)\n    ->Iterations(1)\n    ->Threads(1)\n    ->MeasureProcessCPUTime()\n    ->UseRealTime();\nBENCHMARK(BM_MainThreadAndWorkerThread)\n    ->Iterations(1)\n    ->Threads(1)\n    ->MeasureProcessCPUTime()\n    ->UseManualTime();\n\nBENCHMARK(BM_MainThreadAndWorkerThread)->Iterations(1)->Threads(2);\nBENCHMARK(BM_MainThreadAndWorkerThread)\n    ->Iterations(1)\n    ->Threads(2)\n    ->UseRealTime();\nBENCHMARK(BM_MainThreadAndWorkerThread)\n    ->Iterations(1)\n    ->Threads(2)\n    ->UseManualTime();\nBENCHMARK(BM_MainThreadAndWorkerThread)\n    ->Iterations(1)\n    ->Threads(2)\n    ->MeasureProcessCPUTime();\nBENCHMARK(BM_MainThreadAndWorkerThread)\n    ->Iterations(1)\n    ->Threads(2)\n    ->MeasureProcessCPUTime()\n    ->UseRealTime();\nBENCHMARK(BM_MainThreadAndWorkerThread)\n    ->Iterations(1)\n    ->Threads(2)\n    ->MeasureProcessCPUTime()\n    ->UseManualTime();\n\n// ========================================================================= //\n// ---------------------------- TEST CASES END ----------------------------- //\n// ========================================================================= //\n\nint main(int argc, char* argv[]) { RunOutputTests(argc, argv); }\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/link_main_test.cc",
    "content": "#include \"benchmark/benchmark.h\"\n\nvoid BM_empty(benchmark::State& state) {\n  for (auto _ : state) {\n    auto iterations = state.iterations();\n    benchmark::DoNotOptimize(iterations);\n  }\n}\nBENCHMARK(BM_empty);\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/map_test.cc",
    "content": "#include <cstdlib>\n#include <map>\n\n#include \"benchmark/benchmark.h\"\n\nnamespace {\n\nstd::map<int, int> ConstructRandomMap(int size) {\n  std::map<int, int> m;\n  for (int i = 0; i < size; ++i) {\n    m.insert(std::make_pair(std::rand() % size, std::rand() % size));\n  }\n  return m;\n}\n\n}  // namespace\n\n// Basic version.\nstatic void BM_MapLookup(benchmark::State& state) {\n  const int size = static_cast<int>(state.range(0));\n  std::map<int, int> m;\n  for (auto _ : state) {\n    state.PauseTiming();\n    m = ConstructRandomMap(size);\n    state.ResumeTiming();\n    for (int i = 0; i < size; ++i) {\n      auto it = m.find(std::rand() % size);\n      benchmark::DoNotOptimize(it);\n    }\n  }\n  state.SetItemsProcessed(state.iterations() * size);\n}\nBENCHMARK(BM_MapLookup)->Range(1 << 3, 1 << 12);\n\n// Using fixtures.\nclass MapFixture : public ::benchmark::Fixture {\n public:\n  void SetUp(const ::benchmark::State& st) override {\n    m = ConstructRandomMap(static_cast<int>(st.range(0)));\n  }\n\n  void TearDown(const ::benchmark::State&) override { m.clear(); }\n\n  std::map<int, int> m;\n};\n\nBENCHMARK_DEFINE_F(MapFixture, Lookup)(benchmark::State& state) {\n  const int size = static_cast<int>(state.range(0));\n  for (auto _ : state) {\n    for (int i = 0; i < size; ++i) {\n      auto it = m.find(std::rand() % size);\n      benchmark::DoNotOptimize(it);\n    }\n  }\n  state.SetItemsProcessed(state.iterations() * size);\n}\nBENCHMARK_REGISTER_F(MapFixture, Lookup)->Range(1 << 3, 1 << 12);\n\nBENCHMARK_MAIN();\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/memory_manager_test.cc",
    "content": "#include <memory>\n\n#include \"../src/check.h\"\n#include \"benchmark/benchmark.h\"\n#include \"output_test.h\"\n\nclass TestMemoryManager : public benchmark::MemoryManager {\n  void Start() override {}\n  void Stop(Result& result) override {\n    result.num_allocs = 42;\n    result.max_bytes_used = 42000;\n  }\n};\n\nvoid BM_empty(benchmark::State& state) {\n  for (auto _ : state) {\n    auto iterations = state.iterations();\n    benchmark::DoNotOptimize(iterations);\n  }\n}\nBENCHMARK(BM_empty);\n\nADD_CASES(TC_ConsoleOut, {{\"^BM_empty %console_report$\"}});\nADD_CASES(TC_JSONOut, {{\"\\\"name\\\": \\\"BM_empty\\\",$\"},\n                       {\"\\\"family_index\\\": 0,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_empty\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 1,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"iterations\\\": %int,$\", MR_Next},\n                       {\"\\\"real_time\\\": %float,$\", MR_Next},\n                       {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n                       {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n                       {\"\\\"allocs_per_iter\\\": %float,$\", MR_Next},\n                       {\"\\\"max_bytes_used\\\": 42000$\", MR_Next},\n                       {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_empty\\\",%csv_report$\"}});\n\nint main(int argc, char* argv[]) {\n  std::unique_ptr<benchmark::MemoryManager> mm(new TestMemoryManager());\n\n  benchmark::RegisterMemoryManager(mm.get());\n  RunOutputTests(argc, argv);\n  benchmark::RegisterMemoryManager(nullptr);\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/min_time_parse_gtest.cc",
    "content": "#include \"../src/benchmark_runner.h\"\n#include \"gtest/gtest.h\"\n\nnamespace {\n\nTEST(ParseMinTimeTest, InvalidInput) {\n#if GTEST_HAS_DEATH_TEST\n  // Tests only runnable in debug mode (when BM_CHECK is enabled).\n#ifndef NDEBUG\n#ifndef TEST_BENCHMARK_LIBRARY_HAS_NO_ASSERTIONS\n  ASSERT_DEATH_IF_SUPPORTED(\n      { benchmark::internal::ParseBenchMinTime(\"abc\"); },\n      \"Malformed seconds value passed to --benchmark_min_time: `abc`\");\n\n  ASSERT_DEATH_IF_SUPPORTED(\n      { benchmark::internal::ParseBenchMinTime(\"123ms\"); },\n      \"Malformed seconds value passed to --benchmark_min_time: `123ms`\");\n\n  ASSERT_DEATH_IF_SUPPORTED(\n      { benchmark::internal::ParseBenchMinTime(\"1z\"); },\n      \"Malformed seconds value passed to --benchmark_min_time: `1z`\");\n\n  ASSERT_DEATH_IF_SUPPORTED(\n      { benchmark::internal::ParseBenchMinTime(\"1hs\"); },\n      \"Malformed seconds value passed to --benchmark_min_time: `1hs`\");\n#endif\n#endif\n#endif\n}\n}  // namespace\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/multiple_ranges_test.cc",
    "content": "#include <cassert>\n#include <iostream>\n#include <set>\n#include <vector>\n\n#include \"benchmark/benchmark.h\"\n\nclass MultipleRangesFixture : public ::benchmark::Fixture {\n public:\n  MultipleRangesFixture()\n      : expectedValues({{1, 3, 5},\n                        {1, 3, 8},\n                        {1, 3, 15},\n                        {2, 3, 5},\n                        {2, 3, 8},\n                        {2, 3, 15},\n                        {1, 4, 5},\n                        {1, 4, 8},\n                        {1, 4, 15},\n                        {2, 4, 5},\n                        {2, 4, 8},\n                        {2, 4, 15},\n                        {1, 7, 5},\n                        {1, 7, 8},\n                        {1, 7, 15},\n                        {2, 7, 5},\n                        {2, 7, 8},\n                        {2, 7, 15},\n                        {7, 6, 3}}) {}\n\n  void SetUp(const ::benchmark::State& state) override {\n    std::vector<int64_t> ranges = {state.range(0), state.range(1),\n                                   state.range(2)};\n\n    assert(expectedValues.find(ranges) != expectedValues.end());\n\n    actualValues.insert(ranges);\n  }\n\n  // NOTE: This is not TearDown as we want to check after _all_ runs are\n  // complete.\n  ~MultipleRangesFixture() override {\n    if (actualValues != expectedValues) {\n      std::cout << \"EXPECTED\\n\";\n      for (const auto& v : expectedValues) {\n        std::cout << \"{\";\n        for (int64_t iv : v) {\n          std::cout << iv << \", \";\n        }\n        std::cout << \"}\\n\";\n      }\n      std::cout << \"ACTUAL\\n\";\n      for (const auto& v : actualValues) {\n        std::cout << \"{\";\n        for (int64_t iv : v) {\n          std::cout << iv << \", \";\n        }\n        std::cout << \"}\\n\";\n      }\n    }\n  }\n\n  std::set<std::vector<int64_t>> expectedValues;\n  std::set<std::vector<int64_t>> actualValues;\n};\n\nBENCHMARK_DEFINE_F(MultipleRangesFixture, Empty)(benchmark::State& state) {\n  for (auto _ : state) {\n    int64_t product = state.range(0) * state.range(1) * state.range(2);\n    for (int64_t x = 0; x < product; x++) {\n      benchmark::DoNotOptimize(x);\n    }\n  }\n}\n\nBENCHMARK_REGISTER_F(MultipleRangesFixture, Empty)\n    ->RangeMultiplier(2)\n    ->Ranges({{1, 2}, {3, 7}, {5, 15}})\n    ->Args({7, 6, 3});\n\nvoid BM_CheckDefaultArgument(benchmark::State& state) {\n  // Test that the 'range()' without an argument is the same as 'range(0)'.\n  assert(state.range() == state.range(0));\n  assert(state.range() != state.range(1));\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_CheckDefaultArgument)->Ranges({{1, 5}, {6, 10}});\n\nstatic void BM_MultipleRanges(benchmark::State& st) {\n  for (auto _ : st) {\n  }\n}\nBENCHMARK(BM_MultipleRanges)->Ranges({{5, 5}, {6, 6}});\n\nBENCHMARK_MAIN();\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/options_test.cc",
    "content": "#include <chrono>\n#include <thread>\n\n#include \"benchmark/benchmark.h\"\n\n#if defined(NDEBUG)\n#undef NDEBUG\n#endif\n#include <cassert>\n\nvoid BM_basic(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\n\nvoid BM_basic_slow(benchmark::State& state) {\n  std::chrono::milliseconds sleep_duration(state.range(0));\n  for (auto _ : state) {\n    std::this_thread::sleep_for(\n        std::chrono::duration_cast<std::chrono::nanoseconds>(sleep_duration));\n  }\n}\n\nBENCHMARK(BM_basic);\nBENCHMARK(BM_basic)->Arg(42);\nBENCHMARK(BM_basic_slow)->Arg(10)->Unit(benchmark::kNanosecond);\nBENCHMARK(BM_basic_slow)->Arg(100)->Unit(benchmark::kMicrosecond);\nBENCHMARK(BM_basic_slow)->Arg(1000)->Unit(benchmark::kMillisecond);\nBENCHMARK(BM_basic_slow)->Arg(1000)->Unit(benchmark::kSecond);\nBENCHMARK(BM_basic)->Range(1, 8);\nBENCHMARK(BM_basic)->RangeMultiplier(2)->Range(1, 8);\nBENCHMARK(BM_basic)->DenseRange(10, 15);\nBENCHMARK(BM_basic)->Args({42, 42});\nBENCHMARK(BM_basic)->Ranges({{64, 512}, {64, 512}});\nBENCHMARK(BM_basic)->MinTime(0.7);\nBENCHMARK(BM_basic)->MinWarmUpTime(0.8);\nBENCHMARK(BM_basic)->MinTime(0.1)->MinWarmUpTime(0.2);\nBENCHMARK(BM_basic)->UseRealTime();\nBENCHMARK(BM_basic)->ThreadRange(2, 4);\nBENCHMARK(BM_basic)->ThreadPerCpu();\nBENCHMARK(BM_basic)->Repetitions(3);\nBENCHMARK(BM_basic)\n    ->RangeMultiplier(std::numeric_limits<int>::max())\n    ->Range(std::numeric_limits<int64_t>::min(),\n            std::numeric_limits<int64_t>::max());\n\n// Negative ranges\nBENCHMARK(BM_basic)->Range(-64, -1);\nBENCHMARK(BM_basic)->RangeMultiplier(4)->Range(-8, 8);\nBENCHMARK(BM_basic)->DenseRange(-2, 2, 1);\nBENCHMARK(BM_basic)->Ranges({{-64, 1}, {-8, -1}});\n\nvoid CustomArgs(benchmark::internal::Benchmark* b) {\n  for (int i = 0; i < 10; ++i) {\n    b->Arg(i);\n  }\n}\n\nBENCHMARK(BM_basic)->Apply(CustomArgs);\n\nvoid BM_explicit_iteration_count(benchmark::State& state) {\n  // Test that benchmarks specified with an explicit iteration count are\n  // only run once.\n  static bool invoked_before = false;\n  assert(!invoked_before);\n  invoked_before = true;\n\n  // Test that the requested iteration count is respected.\n  assert(state.max_iterations == 42);\n  for (auto _ : state) {\n  }\n  assert(state.iterations() == state.max_iterations);\n  assert(state.iterations() == 42);\n}\nBENCHMARK(BM_explicit_iteration_count)->Iterations(42);\n\nBENCHMARK_MAIN();\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/output_test.h",
    "content": "#ifndef TEST_OUTPUT_TEST_H\n#define TEST_OUTPUT_TEST_H\n\n#undef NDEBUG\n#include <functional>\n#include <initializer_list>\n#include <memory>\n#include <sstream>\n#include <string>\n#include <utility>\n#include <vector>\n\n#include \"../src/re.h\"\n#include \"benchmark/benchmark.h\"\n\n#define CONCAT2(x, y) x##y\n#define CONCAT(x, y) CONCAT2(x, y)\n\n#define ADD_CASES(...) int CONCAT(dummy, __LINE__) = ::AddCases(__VA_ARGS__)\n\n#define SET_SUBSTITUTIONS(...) \\\n  int CONCAT(dummy, __LINE__) = ::SetSubstitutions(__VA_ARGS__)\n\nenum MatchRules {\n  MR_Default,  // Skip non-matching lines until a match is found.\n  MR_Next,     // Match must occur on the next line.\n  MR_Not  // No line between the current position and the next match matches\n          // the regex\n};\n\nstruct TestCase {\n  TestCase(std::string re, int rule = MR_Default);\n\n  std::string regex_str;\n  int match_rule;\n  std::string substituted_regex;\n  std::shared_ptr<benchmark::Regex> regex;\n};\n\nenum TestCaseID {\n  TC_ConsoleOut,\n  TC_ConsoleErr,\n  TC_JSONOut,\n  TC_JSONErr,\n  TC_CSVOut,\n  TC_CSVErr,\n\n  TC_NumID  // PRIVATE\n};\n\n// Add a list of test cases to be run against the output specified by\n// 'ID'\nint AddCases(TestCaseID ID, std::initializer_list<TestCase> il);\n\n// Add or set a list of substitutions to be performed on constructed regex's\n// See 'output_test_helper.cc' for a list of default substitutions.\nint SetSubstitutions(\n    std::initializer_list<std::pair<std::string, std::string>> il);\n\n// Run all output tests.\nvoid RunOutputTests(int argc, char* argv[]);\n\n// Count the number of 'pat' substrings in the 'haystack' string.\nint SubstrCnt(const std::string& haystack, const std::string& pat);\n\n// Run registered benchmarks with file reporter enabled, and return the content\n// outputted by the file reporter.\nstd::string GetFileReporterOutput(int argc, char* argv[]);\n\n// ========================================================================= //\n// ------------------------- Results checking ------------------------------ //\n// ========================================================================= //\n\n// Call this macro to register a benchmark for checking its results. This\n// should be all that's needed. It subscribes a function to check the (CSV)\n// results of a benchmark. This is done only after verifying that the output\n// strings are really as expected.\n// bm_name_pattern: a name or a regex pattern which will be matched against\n//                  all the benchmark names. Matching benchmarks\n//                  will be the subject of a call to checker_function\n// checker_function: should be of type ResultsCheckFn (see below)\n#define CHECK_BENCHMARK_RESULTS(bm_name_pattern, checker_function) \\\n  size_t CONCAT(dummy, __LINE__) = AddChecker(bm_name_pattern, checker_function)\n\nstruct Results;\ntypedef std::function<void(Results const&)> ResultsCheckFn;\n\nsize_t AddChecker(const std::string& bm_name_pattern, const ResultsCheckFn& fn);\n\n// Class holding the results of a benchmark.\n// It is passed in calls to checker functions.\nstruct Results {\n  // the benchmark name\n  std::string name;\n  // the benchmark fields\n  std::map<std::string, std::string> values;\n\n  Results(const std::string& n) : name(n) {}\n\n  int NumThreads() const;\n\n  double NumIterations() const;\n\n  typedef enum { kCpuTime, kRealTime } BenchmarkTime;\n\n  // get cpu_time or real_time in seconds\n  double GetTime(BenchmarkTime which) const;\n\n  // get the real_time duration of the benchmark in seconds.\n  // it is better to use fuzzy float checks for this, as the float\n  // ASCII formatting is lossy.\n  double DurationRealTime() const {\n    return NumIterations() * GetTime(kRealTime);\n  }\n  // get the cpu_time duration of the benchmark in seconds\n  double DurationCPUTime() const { return NumIterations() * GetTime(kCpuTime); }\n\n  // get the string for a result by name, or nullptr if the name\n  // is not found\n  const std::string* Get(const std::string& entry_name) const {\n    auto it = values.find(entry_name);\n    if (it == values.end()) return nullptr;\n    return &it->second;\n  }\n\n  // get a result by name, parsed as a specific type.\n  // NOTE: for counters, use GetCounterAs instead.\n  template <class T>\n  T GetAs(const std::string& entry_name) const;\n\n  // counters are written as doubles, so they have to be read first\n  // as a double, and only then converted to the asked type.\n  template <class T>\n  T GetCounterAs(const std::string& entry_name) const {\n    double dval = GetAs<double>(entry_name);\n    T tval = static_cast<T>(dval);\n    return tval;\n  }\n};\n\ntemplate <class T>\nT Results::GetAs(const std::string& entry_name) const {\n  auto* sv = Get(entry_name);\n  BM_CHECK(sv != nullptr && !sv->empty());\n  std::stringstream ss;\n  ss << *sv;\n  T out;\n  ss >> out;\n  BM_CHECK(!ss.fail());\n  return out;\n}\n\n//----------------------------------\n// Macros to help in result checking. Do not use them with arguments causing\n// side-effects.\n\n// clang-format off\n\n#define CHECK_RESULT_VALUE_IMPL(entry, getfn, var_type, var_name, relationship, value) \\\n    CONCAT(BM_CHECK_, relationship)                                        \\\n    (entry.getfn< var_type >(var_name), (value)) << \"\\n\"                \\\n    << __FILE__ << \":\" << __LINE__ << \": \" << (entry).name << \":\\n\"     \\\n    << __FILE__ << \":\" << __LINE__ << \": \"                              \\\n    << \"expected (\" << #var_type << \")\" << (var_name)                   \\\n    << \"=\" << (entry).getfn< var_type >(var_name)                       \\\n    << \" to be \" #relationship \" to \" << (value) << \"\\n\"\n\n// check with tolerance. eps_factor is the tolerance window, which is\n// interpreted relative to value (eg, 0.1 means 10% of value).\n#define CHECK_FLOAT_RESULT_VALUE_IMPL(entry, getfn, var_type, var_name, relationship, value, eps_factor) \\\n    CONCAT(BM_CHECK_FLOAT_, relationship)                                  \\\n    (entry.getfn< var_type >(var_name), (value), (eps_factor) * (value)) << \"\\n\" \\\n    << __FILE__ << \":\" << __LINE__ << \": \" << (entry).name << \":\\n\"     \\\n    << __FILE__ << \":\" << __LINE__ << \": \"                              \\\n    << \"expected (\" << #var_type << \")\" << (var_name)                   \\\n    << \"=\" << (entry).getfn< var_type >(var_name)                       \\\n    << \" to be \" #relationship \" to \" << (value) << \"\\n\"                \\\n    << __FILE__ << \":\" << __LINE__ << \": \"                              \\\n    << \"with tolerance of \" << (eps_factor) * (value)                   \\\n    << \" (\" << (eps_factor)*100. << \"%), \"                              \\\n    << \"but delta was \" << ((entry).getfn< var_type >(var_name) - (value)) \\\n    << \" (\" << (((entry).getfn< var_type >(var_name) - (value))         \\\n               /                                                        \\\n               ((value) > 1.e-5 || value < -1.e-5 ? value : 1.e-5)*100.) \\\n    << \"%)\"\n\n#define CHECK_RESULT_VALUE(entry, var_type, var_name, relationship, value) \\\n    CHECK_RESULT_VALUE_IMPL(entry, GetAs, var_type, var_name, relationship, value)\n\n#define CHECK_COUNTER_VALUE(entry, var_type, var_name, relationship, value) \\\n    CHECK_RESULT_VALUE_IMPL(entry, GetCounterAs, var_type, var_name, relationship, value)\n\n#define CHECK_FLOAT_RESULT_VALUE(entry, var_name, relationship, value, eps_factor) \\\n    CHECK_FLOAT_RESULT_VALUE_IMPL(entry, GetAs, double, var_name, relationship, value, eps_factor)\n\n#define CHECK_FLOAT_COUNTER_VALUE(entry, var_name, relationship, value, eps_factor) \\\n    CHECK_FLOAT_RESULT_VALUE_IMPL(entry, GetCounterAs, double, var_name, relationship, value, eps_factor)\n\n// clang-format on\n\n// ========================================================================= //\n// --------------------------- Misc Utilities ------------------------------ //\n// ========================================================================= //\n\nnamespace {\n\nconst char* const dec_re = \"[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?\";\n\n}  //  end namespace\n\n#endif  // TEST_OUTPUT_TEST_H\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/output_test_helper.cc",
    "content": "#include <cstdio>\n#include <cstring>\n#include <fstream>\n#include <iostream>\n#include <map>\n#include <memory>\n#include <random>\n#include <sstream>\n#include <streambuf>\n\n#include \"../src/benchmark_api_internal.h\"\n#include \"../src/check.h\"  // NOTE: check.h is for internal use only!\n#include \"../src/log.h\"    // NOTE: log.h is for internal use only\n#include \"../src/re.h\"     // NOTE: re.h is for internal use only\n#include \"output_test.h\"\n\n// ========================================================================= //\n// ------------------------------ Internals -------------------------------- //\n// ========================================================================= //\nnamespace internal {\nnamespace {\n\nusing TestCaseList = std::vector<TestCase>;\n\n// Use a vector because the order elements are added matters during iteration.\n// std::map/unordered_map don't guarantee that.\n// For example:\n//  SetSubstitutions({{\"%HelloWorld\", \"Hello\"}, {\"%Hello\", \"Hi\"}});\n//     Substitute(\"%HelloWorld\") // Always expands to Hello.\nusing SubMap = std::vector<std::pair<std::string, std::string>>;\n\nTestCaseList& GetTestCaseList(TestCaseID ID) {\n  // Uses function-local statics to ensure initialization occurs\n  // before first use.\n  static TestCaseList lists[TC_NumID];\n  return lists[ID];\n}\n\nSubMap& GetSubstitutions() {\n  // Don't use 'dec_re' from header because it may not yet be initialized.\n  // clang-format off\n  static std::string safe_dec_re = \"[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?\";\n  static std::string time_re = \"([0-9]+[.])?[0-9]+\";\n  static std::string percentage_re = \"[0-9]+[.][0-9]{2}\";\n  static SubMap map = {\n      {\"%float\", \"[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?\"},\n      // human-readable float\n      {\"%hrfloat\", \"[0-9]*[.]?[0-9]+([eE][-+][0-9]+)?[kMGTPEZYmunpfazy]?\"},\n      {\"%percentage\", percentage_re},\n      {\"%int\", \"[ ]*[0-9]+\"},\n      {\" %s \", \"[ ]+\"},\n      {\"%time\", \"[ ]*\" + time_re + \"[ ]+ns\"},\n      {\"%console_report\", \"[ ]*\" + time_re + \"[ ]+ns [ ]*\" + time_re + \"[ ]+ns [ ]*[0-9]+\"},\n      {\"%console_percentage_report\", \"[ ]*\" + percentage_re + \"[ ]+% [ ]*\" + percentage_re + \"[ ]+% [ ]*[0-9]+\"},\n      {\"%console_us_report\", \"[ ]*\" + time_re + \"[ ]+us [ ]*\" + time_re + \"[ ]+us [ ]*[0-9]+\"},\n      {\"%console_ms_report\", \"[ ]*\" + time_re + \"[ ]+ms [ ]*\" + time_re + \"[ ]+ms [ ]*[0-9]+\"},\n      {\"%console_s_report\", \"[ ]*\" + time_re + \"[ ]+s [ ]*\" + time_re + \"[ ]+s [ ]*[0-9]+\"},\n      {\"%console_time_only_report\", \"[ ]*\" + time_re + \"[ ]+ns [ ]*\" + time_re + \"[ ]+ns\"},\n      {\"%console_us_report\", \"[ ]*\" + time_re + \"[ ]+us [ ]*\" + time_re + \"[ ]+us [ ]*[0-9]+\"},\n      {\"%console_us_time_only_report\", \"[ ]*\" + time_re + \"[ ]+us [ ]*\" + time_re + \"[ ]+us\"},\n      {\"%csv_header\",\n       \"name,iterations,real_time,cpu_time,time_unit,bytes_per_second,\"\n       \"items_per_second,label,error_occurred,error_message\"},\n      {\"%csv_report\", \"[0-9]+,\" + safe_dec_re + \",\" + safe_dec_re + \",ns,,,,,\"},\n      {\"%csv_us_report\", \"[0-9]+,\" + safe_dec_re + \",\" + safe_dec_re + \",us,,,,,\"},\n      {\"%csv_ms_report\", \"[0-9]+,\" + safe_dec_re + \",\" + safe_dec_re + \",ms,,,,,\"},\n      {\"%csv_s_report\", \"[0-9]+,\" + safe_dec_re + \",\" + safe_dec_re + \",s,,,,,\"},\n      {\"%csv_bytes_report\",\n       \"[0-9]+,\" + safe_dec_re + \",\" + safe_dec_re + \",ns,\" + safe_dec_re + \",,,,\"},\n      {\"%csv_items_report\",\n       \"[0-9]+,\" + safe_dec_re + \",\" + safe_dec_re + \",ns,,\" + safe_dec_re + \",,,\"},\n      {\"%csv_bytes_items_report\",\n       \"[0-9]+,\" + safe_dec_re + \",\" + safe_dec_re + \",ns,\" + safe_dec_re +\n       \",\" + safe_dec_re + \",,,\"},\n      {\"%csv_label_report_begin\", \"[0-9]+,\" + safe_dec_re + \",\" + safe_dec_re + \",ns,,,\"},\n      {\"%csv_label_report_end\", \",,\"}};\n  // clang-format on\n  return map;\n}\n\nstd::string PerformSubstitutions(std::string source) {\n  SubMap const& subs = GetSubstitutions();\n  using SizeT = std::string::size_type;\n  for (auto const& KV : subs) {\n    SizeT pos;\n    SizeT next_start = 0;\n    while ((pos = source.find(KV.first, next_start)) != std::string::npos) {\n      next_start = pos + KV.second.size();\n      source.replace(pos, KV.first.size(), KV.second);\n    }\n  }\n  return source;\n}\n\nvoid CheckCase(std::stringstream& remaining_output, TestCase const& TC,\n               TestCaseList const& not_checks) {\n  std::string first_line;\n  bool on_first = true;\n  std::string line;\n  while (remaining_output.eof() == false) {\n    BM_CHECK(remaining_output.good());\n    std::getline(remaining_output, line);\n    if (on_first) {\n      first_line = line;\n      on_first = false;\n    }\n    for (const auto& NC : not_checks) {\n      BM_CHECK(!NC.regex->Match(line))\n          << \"Unexpected match for line \\\"\" << line << \"\\\" for MR_Not regex \\\"\"\n          << NC.regex_str << \"\\\"\"\n          << \"\\n    actual regex string \\\"\" << TC.substituted_regex << \"\\\"\"\n          << \"\\n    started matching near: \" << first_line;\n    }\n    if (TC.regex->Match(line)) return;\n    BM_CHECK(TC.match_rule != MR_Next)\n        << \"Expected line \\\"\" << line << \"\\\" to match regex \\\"\" << TC.regex_str\n        << \"\\\"\"\n        << \"\\n    actual regex string \\\"\" << TC.substituted_regex << \"\\\"\"\n        << \"\\n    started matching near: \" << first_line;\n  }\n  BM_CHECK(remaining_output.eof() == false)\n      << \"End of output reached before match for regex \\\"\" << TC.regex_str\n      << \"\\\" was found\"\n      << \"\\n    actual regex string \\\"\" << TC.substituted_regex << \"\\\"\"\n      << \"\\n    started matching near: \" << first_line;\n}\n\nvoid CheckCases(TestCaseList const& checks, std::stringstream& output) {\n  std::vector<TestCase> not_checks;\n  for (size_t i = 0; i < checks.size(); ++i) {\n    const auto& TC = checks[i];\n    if (TC.match_rule == MR_Not) {\n      not_checks.push_back(TC);\n      continue;\n    }\n    CheckCase(output, TC, not_checks);\n    not_checks.clear();\n  }\n}\n\nclass TestReporter : public benchmark::BenchmarkReporter {\n public:\n  TestReporter(std::vector<benchmark::BenchmarkReporter*> reps)\n      : reporters_(std::move(reps)) {}\n\n  bool ReportContext(const Context& context) override {\n    bool last_ret = false;\n    bool first = true;\n    for (auto rep : reporters_) {\n      bool new_ret = rep->ReportContext(context);\n      BM_CHECK(first || new_ret == last_ret)\n          << \"Reports return different values for ReportContext\";\n      first = false;\n      last_ret = new_ret;\n    }\n    (void)first;\n    return last_ret;\n  }\n\n  void ReportRuns(const std::vector<Run>& report) override {\n    for (auto rep : reporters_) rep->ReportRuns(report);\n  }\n  void Finalize() override {\n    for (auto rep : reporters_) rep->Finalize();\n  }\n\n private:\n  std::vector<benchmark::BenchmarkReporter*> reporters_;\n};\n}  // namespace\n\n}  // end namespace internal\n\n// ========================================================================= //\n// -------------------------- Results checking ----------------------------- //\n// ========================================================================= //\n\nnamespace internal {\n\n// Utility class to manage subscribers for checking benchmark results.\n// It works by parsing the CSV output to read the results.\nclass ResultsChecker {\n public:\n  struct PatternAndFn : public TestCase {  // reusing TestCase for its regexes\n    PatternAndFn(const std::string& rx, ResultsCheckFn fn_)\n        : TestCase(rx), fn(std::move(fn_)) {}\n    ResultsCheckFn fn;\n  };\n\n  std::vector<PatternAndFn> check_patterns;\n  std::vector<Results> results;\n  std::vector<std::string> field_names;\n\n  void Add(const std::string& entry_pattern, const ResultsCheckFn& fn);\n\n  void CheckResults(std::stringstream& output);\n\n private:\n  void SetHeader_(const std::string& csv_header);\n  void SetValues_(const std::string& entry_csv_line);\n\n  std::vector<std::string> SplitCsv_(const std::string& line);\n};\n\n// store the static ResultsChecker in a function to prevent initialization\n// order problems\nResultsChecker& GetResultsChecker() {\n  static ResultsChecker rc;\n  return rc;\n}\n\n// add a results checker for a benchmark\nvoid ResultsChecker::Add(const std::string& entry_pattern,\n                         const ResultsCheckFn& fn) {\n  check_patterns.emplace_back(entry_pattern, fn);\n}\n\n// check the results of all subscribed benchmarks\nvoid ResultsChecker::CheckResults(std::stringstream& output) {\n  // first reset the stream to the start\n  {\n    auto start = std::stringstream::pos_type(0);\n    // clear before calling tellg()\n    output.clear();\n    // seek to zero only when needed\n    if (output.tellg() > start) output.seekg(start);\n    // and just in case\n    output.clear();\n  }\n  // now go over every line and publish it to the ResultsChecker\n  std::string line;\n  bool on_first = true;\n  while (output.eof() == false) {\n    BM_CHECK(output.good());\n    std::getline(output, line);\n    if (on_first) {\n      SetHeader_(line);  // this is important\n      on_first = false;\n      continue;\n    }\n    SetValues_(line);\n  }\n  // finally we can call the subscribed check functions\n  for (const auto& p : check_patterns) {\n    BM_VLOG(2) << \"--------------------------------\\n\";\n    BM_VLOG(2) << \"checking for benchmarks matching \" << p.regex_str << \"...\\n\";\n    for (const auto& r : results) {\n      if (!p.regex->Match(r.name)) {\n        BM_VLOG(2) << p.regex_str << \" is not matched by \" << r.name << \"\\n\";\n        continue;\n      }\n      BM_VLOG(2) << p.regex_str << \" is matched by \" << r.name << \"\\n\";\n      BM_VLOG(1) << \"Checking results of \" << r.name << \": ... \\n\";\n      p.fn(r);\n      BM_VLOG(1) << \"Checking results of \" << r.name << \": OK.\\n\";\n    }\n  }\n}\n\n// prepare for the names in this header\nvoid ResultsChecker::SetHeader_(const std::string& csv_header) {\n  field_names = SplitCsv_(csv_header);\n}\n\n// set the values for a benchmark\nvoid ResultsChecker::SetValues_(const std::string& entry_csv_line) {\n  if (entry_csv_line.empty()) return;  // some lines are empty\n  BM_CHECK(!field_names.empty());\n  auto vals = SplitCsv_(entry_csv_line);\n  BM_CHECK_EQ(vals.size(), field_names.size());\n  results.emplace_back(vals[0]);  // vals[0] is the benchmark name\n  auto& entry = results.back();\n  for (size_t i = 1, e = vals.size(); i < e; ++i) {\n    entry.values[field_names[i]] = vals[i];\n  }\n}\n\n// a quick'n'dirty csv splitter (eliminating quotes)\nstd::vector<std::string> ResultsChecker::SplitCsv_(const std::string& line) {\n  std::vector<std::string> out;\n  if (line.empty()) return out;\n  if (!field_names.empty()) out.reserve(field_names.size());\n  size_t prev = 0, pos = line.find_first_of(','), curr = pos;\n  while (pos != line.npos) {\n    BM_CHECK(curr > 0);\n    if (line[prev] == '\"') ++prev;\n    if (line[curr - 1] == '\"') --curr;\n    out.push_back(line.substr(prev, curr - prev));\n    prev = pos + 1;\n    pos = line.find_first_of(',', pos + 1);\n    curr = pos;\n  }\n  curr = line.size();\n  if (line[prev] == '\"') ++prev;\n  if (line[curr - 1] == '\"') --curr;\n  out.push_back(line.substr(prev, curr - prev));\n  return out;\n}\n\n}  // end namespace internal\n\nsize_t AddChecker(const std::string& bm_name, const ResultsCheckFn& fn) {\n  auto& rc = internal::GetResultsChecker();\n  rc.Add(bm_name, fn);\n  return rc.results.size();\n}\n\nint Results::NumThreads() const {\n  auto pos = name.find(\"/threads:\");\n  if (pos == name.npos) return 1;\n  auto end = name.find('/', pos + 9);\n  std::stringstream ss;\n  ss << name.substr(pos + 9, end);\n  int num = 1;\n  ss >> num;\n  BM_CHECK(!ss.fail());\n  return num;\n}\n\ndouble Results::NumIterations() const { return GetAs<double>(\"iterations\"); }\n\ndouble Results::GetTime(BenchmarkTime which) const {\n  BM_CHECK(which == kCpuTime || which == kRealTime);\n  const char* which_str = which == kCpuTime ? \"cpu_time\" : \"real_time\";\n  double val = GetAs<double>(which_str);\n  auto unit = Get(\"time_unit\");\n  BM_CHECK(unit);\n  if (*unit == \"ns\") {\n    return val * 1.e-9;\n  }\n  if (*unit == \"us\") {\n    return val * 1.e-6;\n  }\n  if (*unit == \"ms\") {\n    return val * 1.e-3;\n  }\n  if (*unit == \"s\") {\n    return val;\n  }\n  BM_CHECK(1 == 0) << \"unknown time unit: \" << *unit;\n  return 0;\n}\n\n// ========================================================================= //\n// -------------------------- Public API Definitions------------------------ //\n// ========================================================================= //\n\nTestCase::TestCase(std::string re, int rule)\n    : regex_str(std::move(re)),\n      match_rule(rule),\n      substituted_regex(internal::PerformSubstitutions(regex_str)),\n      regex(std::make_shared<benchmark::Regex>()) {\n  std::string err_str;\n  regex->Init(substituted_regex, &err_str);\n  BM_CHECK(err_str.empty())\n      << \"Could not construct regex \\\"\" << substituted_regex << \"\\\"\"\n      << \"\\n    originally \\\"\" << regex_str << \"\\\"\"\n      << \"\\n    got error: \" << err_str;\n}\n\nint AddCases(TestCaseID ID, std::initializer_list<TestCase> il) {\n  auto& L = internal::GetTestCaseList(ID);\n  L.insert(L.end(), il);\n  return 0;\n}\n\nint SetSubstitutions(\n    std::initializer_list<std::pair<std::string, std::string>> il) {\n  auto& subs = internal::GetSubstitutions();\n  for (auto KV : il) {\n    bool exists = false;\n    KV.second = internal::PerformSubstitutions(KV.second);\n    for (auto& EKV : subs) {\n      if (EKV.first == KV.first) {\n        EKV.second = std::move(KV.second);\n        exists = true;\n        break;\n      }\n    }\n    if (!exists) subs.push_back(std::move(KV));\n  }\n  return 0;\n}\n\n// Disable deprecated warnings temporarily because we need to reference\n// CSVReporter but don't want to trigger -Werror=-Wdeprecated-declarations\nBENCHMARK_DISABLE_DEPRECATED_WARNING\n\nvoid RunOutputTests(int argc, char* argv[]) {\n  using internal::GetTestCaseList;\n  benchmark::Initialize(&argc, argv);\n  auto options = benchmark::internal::GetOutputOptions(/*force_no_color*/ true);\n  benchmark::ConsoleReporter CR(options);\n  benchmark::JSONReporter JR;\n  benchmark::CSVReporter CSVR;\n  struct ReporterTest {\n    std::string name;\n    std::vector<TestCase>& output_cases;\n    std::vector<TestCase>& error_cases;\n    benchmark::BenchmarkReporter& reporter;\n    std::stringstream out_stream;\n    std::stringstream err_stream;\n\n    ReporterTest(const std::string& n, std::vector<TestCase>& out_tc,\n                 std::vector<TestCase>& err_tc,\n                 benchmark::BenchmarkReporter& br)\n        : name(n), output_cases(out_tc), error_cases(err_tc), reporter(br) {\n      reporter.SetOutputStream(&out_stream);\n      reporter.SetErrorStream(&err_stream);\n    }\n  } TestCases[] = {\n      {std::string(\"ConsoleReporter\"), GetTestCaseList(TC_ConsoleOut),\n       GetTestCaseList(TC_ConsoleErr), CR},\n      {std::string(\"JSONReporter\"), GetTestCaseList(TC_JSONOut),\n       GetTestCaseList(TC_JSONErr), JR},\n      {std::string(\"CSVReporter\"), GetTestCaseList(TC_CSVOut),\n       GetTestCaseList(TC_CSVErr), CSVR},\n  };\n\n  // Create the test reporter and run the benchmarks.\n  std::cout << \"Running benchmarks...\\n\";\n  internal::TestReporter test_rep({&CR, &JR, &CSVR});\n  benchmark::RunSpecifiedBenchmarks(&test_rep);\n\n  for (auto& rep_test : TestCases) {\n    std::string msg =\n        std::string(\"\\nTesting \") + rep_test.name + std::string(\" Output\\n\");\n    std::string banner(msg.size() - 1, '-');\n    std::cout << banner << msg << banner << \"\\n\";\n\n    std::cerr << rep_test.err_stream.str();\n    std::cout << rep_test.out_stream.str();\n\n    internal::CheckCases(rep_test.error_cases, rep_test.err_stream);\n    internal::CheckCases(rep_test.output_cases, rep_test.out_stream);\n\n    std::cout << \"\\n\";\n  }\n\n  // now that we know the output is as expected, we can dispatch\n  // the checks to subscribees.\n  auto& csv = TestCases[2];\n  // would use == but gcc spits a warning\n  BM_CHECK(csv.name == std::string(\"CSVReporter\"));\n  internal::GetResultsChecker().CheckResults(csv.out_stream);\n}\n\nBENCHMARK_RESTORE_DEPRECATED_WARNING\n\nint SubstrCnt(const std::string& haystack, const std::string& pat) {\n  if (pat.length() == 0) return 0;\n  int count = 0;\n  for (size_t offset = haystack.find(pat); offset != std::string::npos;\n       offset = haystack.find(pat, offset + pat.length()))\n    ++count;\n  return count;\n}\n\nstatic char ToHex(int ch) {\n  return ch < 10 ? static_cast<char>('0' + ch)\n                 : static_cast<char>('a' + (ch - 10));\n}\n\nstatic char RandomHexChar() {\n  static std::mt19937 rd{std::random_device{}()};\n  static std::uniform_int_distribution<int> mrand{0, 15};\n  return ToHex(mrand(rd));\n}\n\nstatic std::string GetRandomFileName() {\n  std::string model = \"test.%%%%%%\";\n  for (auto& ch : model) {\n    if (ch == '%') ch = RandomHexChar();\n  }\n  return model;\n}\n\nstatic bool FileExists(std::string const& name) {\n  std::ifstream in(name.c_str());\n  return in.good();\n}\n\nstatic std::string GetTempFileName() {\n  // This function attempts to avoid race conditions where two tests\n  // create the same file at the same time. However, it still introduces races\n  // similar to tmpnam.\n  int retries = 3;\n  while (--retries) {\n    std::string name = GetRandomFileName();\n    if (!FileExists(name)) return name;\n  }\n  std::cerr << \"Failed to create unique temporary file name\" << std::endl;\n  std::abort();\n}\n\nstd::string GetFileReporterOutput(int argc, char* argv[]) {\n  std::vector<char*> new_argv(argv, argv + argc);\n  assert(static_cast<decltype(new_argv)::size_type>(argc) == new_argv.size());\n\n  std::string tmp_file_name = GetTempFileName();\n  std::cout << \"Will be using this as the tmp file: \" << tmp_file_name << '\\n';\n\n  std::string tmp = \"--benchmark_out=\";\n  tmp += tmp_file_name;\n  new_argv.emplace_back(const_cast<char*>(tmp.c_str()));\n\n  argc = int(new_argv.size());\n\n  benchmark::Initialize(&argc, new_argv.data());\n  benchmark::RunSpecifiedBenchmarks();\n\n  // Read the output back from the file, and delete the file.\n  std::ifstream tmp_stream(tmp_file_name);\n  std::string output = std::string((std::istreambuf_iterator<char>(tmp_stream)),\n                                   std::istreambuf_iterator<char>());\n  std::remove(tmp_file_name.c_str());\n\n  return output;\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/perf_counters_gtest.cc",
    "content": "#include <random>\n#include <thread>\n\n#include \"../src/perf_counters.h\"\n#include \"gtest/gtest.h\"\n\n#ifndef GTEST_SKIP\nstruct MsgHandler {\n  void operator=(std::ostream&) {}\n};\n#define GTEST_SKIP() return MsgHandler() = std::cout\n#endif\n\nusing benchmark::internal::PerfCounters;\nusing benchmark::internal::PerfCountersMeasurement;\nusing benchmark::internal::PerfCounterValues;\n\nnamespace {\nconst char kGenericPerfEvent1[] = \"CYCLES\";\nconst char kGenericPerfEvent2[] = \"BRANCHES\";\nconst char kGenericPerfEvent3[] = \"INSTRUCTIONS\";\n\nTEST(PerfCountersTest, Init) {\n  EXPECT_EQ(PerfCounters::Initialize(), PerfCounters::kSupported);\n}\n\nTEST(PerfCountersTest, OneCounter) {\n  if (!PerfCounters::kSupported) {\n    GTEST_SKIP() << \"Performance counters not supported.\\n\";\n  }\n  EXPECT_TRUE(PerfCounters::Initialize());\n  EXPECT_EQ(PerfCounters::Create({kGenericPerfEvent1}).num_counters(), 1);\n}\n\nTEST(PerfCountersTest, NegativeTest) {\n  if (!PerfCounters::kSupported) {\n    EXPECT_FALSE(PerfCounters::Initialize());\n    return;\n  }\n  EXPECT_TRUE(PerfCounters::Initialize());\n  // Sanity checks\n  // Create() will always create a valid object, even if passed no or\n  // wrong arguments as the new behavior is to warn and drop unsupported\n  // counters\n  EXPECT_EQ(PerfCounters::Create({}).num_counters(), 0);\n  EXPECT_EQ(PerfCounters::Create({\"\"}).num_counters(), 0);\n  EXPECT_EQ(PerfCounters::Create({\"not a counter name\"}).num_counters(), 0);\n  {\n    // Try sneaking in a bad egg to see if it is filtered out. The\n    // number of counters has to be two, not zero\n    auto counter =\n        PerfCounters::Create({kGenericPerfEvent2, \"\", kGenericPerfEvent1});\n    EXPECT_EQ(counter.num_counters(), 2);\n    EXPECT_EQ(counter.names(), std::vector<std::string>(\n                                   {kGenericPerfEvent2, kGenericPerfEvent1}));\n  }\n  {\n    // Try sneaking in an outrageous counter, like a fat finger mistake\n    auto counter = PerfCounters::Create(\n        {kGenericPerfEvent3, \"not a counter name\", kGenericPerfEvent1});\n    EXPECT_EQ(counter.num_counters(), 2);\n    EXPECT_EQ(counter.names(), std::vector<std::string>(\n                                   {kGenericPerfEvent3, kGenericPerfEvent1}));\n  }\n  {\n    // Finally try a golden input - it should like all them\n    EXPECT_EQ(PerfCounters::Create(\n                  {kGenericPerfEvent1, kGenericPerfEvent2, kGenericPerfEvent3})\n                  .num_counters(),\n              3);\n  }\n  {\n    // Add a bad apple in the end of the chain to check the edges\n    auto counter = PerfCounters::Create({kGenericPerfEvent1, kGenericPerfEvent2,\n                                         kGenericPerfEvent3,\n                                         \"MISPREDICTED_BRANCH_RETIRED\"});\n    EXPECT_EQ(counter.num_counters(), 3);\n    EXPECT_EQ(counter.names(),\n              std::vector<std::string>({kGenericPerfEvent1, kGenericPerfEvent2,\n                                        kGenericPerfEvent3}));\n  }\n}\n\nTEST(PerfCountersTest, Read1Counter) {\n  if (!PerfCounters::kSupported) {\n    GTEST_SKIP() << \"Test skipped because libpfm is not supported.\\n\";\n  }\n  EXPECT_TRUE(PerfCounters::Initialize());\n  auto counters = PerfCounters::Create({kGenericPerfEvent1});\n  EXPECT_EQ(counters.num_counters(), 1);\n  PerfCounterValues values1(1);\n  EXPECT_TRUE(counters.Snapshot(&values1));\n  EXPECT_GT(values1[0], 0);\n  PerfCounterValues values2(1);\n  EXPECT_TRUE(counters.Snapshot(&values2));\n  EXPECT_GT(values2[0], 0);\n  EXPECT_GT(values2[0], values1[0]);\n}\n\nTEST(PerfCountersTest, Read2Counters) {\n  if (!PerfCounters::kSupported) {\n    GTEST_SKIP() << \"Test skipped because libpfm is not supported.\\n\";\n  }\n  EXPECT_TRUE(PerfCounters::Initialize());\n  auto counters =\n      PerfCounters::Create({kGenericPerfEvent1, kGenericPerfEvent2});\n  EXPECT_EQ(counters.num_counters(), 2);\n  PerfCounterValues values1(2);\n  EXPECT_TRUE(counters.Snapshot(&values1));\n  EXPECT_GT(values1[0], 0);\n  EXPECT_GT(values1[1], 0);\n  PerfCounterValues values2(2);\n  EXPECT_TRUE(counters.Snapshot(&values2));\n  EXPECT_GT(values2[0], 0);\n  EXPECT_GT(values2[1], 0);\n}\n\nTEST(PerfCountersTest, ReopenExistingCounters) {\n  // This test works in recent and old Intel hardware\n  // However we cannot make assumptions beyond 3 HW counters\n  if (!PerfCounters::kSupported) {\n    GTEST_SKIP() << \"Test skipped because libpfm is not supported.\\n\";\n  }\n  EXPECT_TRUE(PerfCounters::Initialize());\n  std::vector<std::string> kMetrics({kGenericPerfEvent1});\n  std::vector<PerfCounters> counters(3);\n  for (auto& counter : counters) {\n    counter = PerfCounters::Create(kMetrics);\n  }\n  PerfCounterValues values(1);\n  EXPECT_TRUE(counters[0].Snapshot(&values));\n  EXPECT_TRUE(counters[1].Snapshot(&values));\n  EXPECT_TRUE(counters[2].Snapshot(&values));\n}\n\nTEST(PerfCountersTest, CreateExistingMeasurements) {\n  // The test works (i.e. causes read to fail) for the assumptions\n  // about hardware capabilities (i.e. small number (3) hardware\n  // counters) at this date,\n  // the same as previous test ReopenExistingCounters.\n  if (!PerfCounters::kSupported) {\n    GTEST_SKIP() << \"Test skipped because libpfm is not supported.\\n\";\n  }\n  EXPECT_TRUE(PerfCounters::Initialize());\n\n  // This means we will try 10 counters but we can only guarantee\n  // for sure at this time that only 3 will work. Perhaps in the future\n  // we could use libpfm to query for the hardware limits on this\n  // particular platform.\n  const int kMaxCounters = 10;\n  const int kMinValidCounters = 3;\n\n  // Let's use a ubiquitous counter that is guaranteed to work\n  // on all platforms\n  const std::vector<std::string> kMetrics{\"cycles\"};\n\n  // Cannot create a vector of actual objects because the\n  // copy constructor of PerfCounters is deleted - and so is\n  // implicitly deleted on PerfCountersMeasurement too\n  std::vector<std::unique_ptr<PerfCountersMeasurement>>\n      perf_counter_measurements;\n\n  perf_counter_measurements.reserve(kMaxCounters);\n  for (int j = 0; j < kMaxCounters; ++j) {\n    perf_counter_measurements.emplace_back(\n        new PerfCountersMeasurement(kMetrics));\n  }\n\n  std::vector<std::pair<std::string, double>> measurements;\n\n  // Start all counters together to see if they hold\n  size_t max_counters = kMaxCounters;\n  for (size_t i = 0; i < kMaxCounters; ++i) {\n    auto& counter(*perf_counter_measurements[i]);\n    EXPECT_EQ(counter.num_counters(), 1);\n    if (!counter.Start()) {\n      max_counters = i;\n      break;\n    };\n  }\n\n  ASSERT_GE(max_counters, kMinValidCounters);\n\n  // Start all together\n  for (size_t i = 0; i < max_counters; ++i) {\n    auto& counter(*perf_counter_measurements[i]);\n    EXPECT_TRUE(counter.Stop(measurements) || (i >= kMinValidCounters));\n  }\n\n  // Start/stop individually\n  for (size_t i = 0; i < max_counters; ++i) {\n    auto& counter(*perf_counter_measurements[i]);\n    measurements.clear();\n    counter.Start();\n    EXPECT_TRUE(counter.Stop(measurements) || (i >= kMinValidCounters));\n  }\n}\n\n// We try to do some meaningful work here but the compiler\n// insists in optimizing away our loop so we had to add a\n// no-optimize macro. In case it fails, we added some entropy\n// to this pool as well.\n\nBENCHMARK_DONT_OPTIMIZE size_t do_work() {\n  static std::mt19937 rd{std::random_device{}()};\n  static std::uniform_int_distribution<size_t> mrand(0, 10);\n  const size_t kNumLoops = 1000000;\n  size_t sum = 0;\n  for (size_t j = 0; j < kNumLoops; ++j) {\n    sum += mrand(rd);\n  }\n  benchmark::DoNotOptimize(sum);\n  return sum;\n}\n\nvoid measure(size_t threadcount, PerfCounterValues* before,\n             PerfCounterValues* after) {\n  BM_CHECK_NE(before, nullptr);\n  BM_CHECK_NE(after, nullptr);\n  std::vector<std::thread> threads(threadcount);\n  auto work = [&]() { BM_CHECK(do_work() > 1000); };\n\n  // We need to first set up the counters, then start the threads, so the\n  // threads would inherit the counters. But later, we need to first destroy\n  // the thread pool (so all the work finishes), then measure the counters. So\n  // the scopes overlap, and we need to explicitly control the scope of the\n  // threadpool.\n  auto counters =\n      PerfCounters::Create({kGenericPerfEvent1, kGenericPerfEvent3});\n  for (auto& t : threads) t = std::thread(work);\n  counters.Snapshot(before);\n  for (auto& t : threads) t.join();\n  counters.Snapshot(after);\n}\n\nTEST(PerfCountersTest, MultiThreaded) {\n  if (!PerfCounters::kSupported) {\n    GTEST_SKIP() << \"Test skipped because libpfm is not supported.\";\n  }\n  EXPECT_TRUE(PerfCounters::Initialize());\n  PerfCounterValues before(2);\n  PerfCounterValues after(2);\n\n  // Notice that this test will work even if we taskset it to a single CPU\n  // In this case the threads will run sequentially\n  // Start two threads and measure the number of combined cycles and\n  // instructions\n  measure(2, &before, &after);\n  std::vector<double> Elapsed2Threads{\n      static_cast<double>(after[0] - before[0]),\n      static_cast<double>(after[1] - before[1])};\n\n  // Start four threads and measure the number of combined cycles and\n  // instructions\n  measure(4, &before, &after);\n  std::vector<double> Elapsed4Threads{\n      static_cast<double>(after[0] - before[0]),\n      static_cast<double>(after[1] - before[1])};\n\n  // Some extra work will happen on the main thread - like joining the threads\n  // - so the ratio won't be quite 2.0, but very close.\n  EXPECT_GE(Elapsed4Threads[0], 1.9 * Elapsed2Threads[0]);\n  EXPECT_GE(Elapsed4Threads[1], 1.9 * Elapsed2Threads[1]);\n}\n\nTEST(PerfCountersTest, HardwareLimits) {\n  // The test works (i.e. causes read to fail) for the assumptions\n  // about hardware capabilities (i.e. small number (3-4) hardware\n  // counters) at this date,\n  // the same as previous test ReopenExistingCounters.\n  if (!PerfCounters::kSupported) {\n    GTEST_SKIP() << \"Test skipped because libpfm is not supported.\\n\";\n  }\n  EXPECT_TRUE(PerfCounters::Initialize());\n\n  // Taken straight from `perf list` on x86-64\n  // Got all hardware names since these are the problematic ones\n  std::vector<std::string> counter_names{\"cycles\",  // leader\n                                         \"instructions\",\n                                         \"branches\",\n                                         \"L1-dcache-loads\",\n                                         \"L1-dcache-load-misses\",\n                                         \"L1-dcache-prefetches\",\n                                         \"L1-icache-load-misses\",  // leader\n                                         \"L1-icache-loads\",\n                                         \"branch-load-misses\",\n                                         \"branch-loads\",\n                                         \"dTLB-load-misses\",\n                                         \"dTLB-loads\",\n                                         \"iTLB-load-misses\",  // leader\n                                         \"iTLB-loads\",\n                                         \"branch-instructions\",\n                                         \"branch-misses\",\n                                         \"cache-misses\",\n                                         \"cache-references\",\n                                         \"stalled-cycles-backend\",  // leader\n                                         \"stalled-cycles-frontend\"};\n\n  // In the off-chance that some of these values are not supported,\n  // we filter them out so the test will complete without failure\n  // albeit it might not actually test the grouping on that platform\n  std::vector<std::string> valid_names;\n  for (const std::string& name : counter_names) {\n    if (PerfCounters::IsCounterSupported(name)) {\n      valid_names.push_back(name);\n    }\n  }\n  PerfCountersMeasurement counter(valid_names);\n\n  std::vector<std::pair<std::string, double>> measurements;\n\n  counter.Start();\n  EXPECT_TRUE(counter.Stop(measurements));\n}\n\n}  // namespace\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/perf_counters_test.cc",
    "content": "#undef NDEBUG\n\n#include \"../src/perf_counters.h\"\n\n#include \"benchmark/benchmark.h\"\n#include \"output_test.h\"\n\nstatic void BM_Simple(benchmark::State& state) {\n  for (auto _ : state) {\n    auto iterations = state.iterations();\n    benchmark::DoNotOptimize(iterations);\n  }\n}\nBENCHMARK(BM_Simple);\nADD_CASES(TC_JSONOut, {{\"\\\"name\\\": \\\"BM_Simple\\\",$\"}});\n\nstatic void CheckSimple(Results const& e) {\n  CHECK_COUNTER_VALUE(e, double, \"CYCLES\", GT, 0);\n  CHECK_COUNTER_VALUE(e, double, \"BRANCHES\", GT, 0.0);\n}\nCHECK_BENCHMARK_RESULTS(\"BM_Simple\", &CheckSimple);\n\nint main(int argc, char* argv[]) {\n  if (!benchmark::internal::PerfCounters::kSupported) {\n    return 0;\n  }\n  RunOutputTests(argc, argv);\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/register_benchmark_test.cc",
    "content": "\n#undef NDEBUG\n#include <cassert>\n#include <vector>\n\n#include \"../src/check.h\"  // NOTE: check.h is for internal use only!\n#include \"benchmark/benchmark.h\"\n\nnamespace {\n\nclass TestReporter : public benchmark::ConsoleReporter {\n public:\n  void ReportRuns(const std::vector<Run>& report) override {\n    all_runs_.insert(all_runs_.end(), begin(report), end(report));\n    ConsoleReporter::ReportRuns(report);\n  }\n\n  std::vector<Run> all_runs_;\n};\n\nstruct TestCase {\n  const std::string name;\n  const std::string label;\n  // Note: not explicit as we rely on it being converted through ADD_CASES.\n  TestCase(const std::string& xname) : TestCase(xname, \"\") {}\n  TestCase(const std::string& xname, const std::string& xlabel)\n      : name(xname), label(xlabel) {}\n\n  typedef benchmark::BenchmarkReporter::Run Run;\n\n  void CheckRun(Run const& run) const {\n    // clang-format off\n    BM_CHECK(name == run.benchmark_name()) << \"expected \" << name << \" got \"\n                                      << run.benchmark_name();\n    if (!label.empty()) {\n      BM_CHECK(run.report_label == label) << \"expected \" << label << \" got \"\n                                       << run.report_label;\n    } else {\n      BM_CHECK(run.report_label.empty());\n    }\n    // clang-format on\n  }\n};\n\nstd::vector<TestCase> ExpectedResults;\n\nint AddCases(std::initializer_list<TestCase> const& v) {\n  for (const auto& N : v) {\n    ExpectedResults.push_back(N);\n  }\n  return 0;\n}\n\n#define CONCAT(x, y) CONCAT2(x, y)\n#define CONCAT2(x, y) x##y\n#define ADD_CASES(...) int CONCAT(dummy, __LINE__) = AddCases({__VA_ARGS__})\n\n}  // end namespace\n\ntypedef benchmark::internal::Benchmark* ReturnVal;\n\n//----------------------------------------------------------------------------//\n// Test RegisterBenchmark with no additional arguments\n//----------------------------------------------------------------------------//\nvoid BM_function(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_function);\nReturnVal dummy = benchmark::RegisterBenchmark(\n    \"BM_function_manual_registration\", BM_function);\nADD_CASES({\"BM_function\"}, {\"BM_function_manual_registration\"});\n\n//----------------------------------------------------------------------------//\n// Test RegisterBenchmark with additional arguments\n// Note: GCC <= 4.8 do not support this form of RegisterBenchmark because they\n//       reject the variadic pack expansion of lambda captures.\n//----------------------------------------------------------------------------//\n#ifndef BENCHMARK_HAS_NO_VARIADIC_REGISTER_BENCHMARK\n\nvoid BM_extra_args(benchmark::State& st, const char* label) {\n  for (auto _ : st) {\n  }\n  st.SetLabel(label);\n}\nint RegisterFromFunction() {\n  std::pair<const char*, const char*> cases[] = {\n      {\"test1\", \"One\"}, {\"test2\", \"Two\"}, {\"test3\", \"Three\"}};\n  for (auto const& c : cases)\n    benchmark::RegisterBenchmark(c.first, &BM_extra_args, c.second);\n  return 0;\n}\nint dummy2 = RegisterFromFunction();\nADD_CASES({\"test1\", \"One\"}, {\"test2\", \"Two\"}, {\"test3\", \"Three\"});\n\n#endif  // BENCHMARK_HAS_NO_VARIADIC_REGISTER_BENCHMARK\n\n//----------------------------------------------------------------------------//\n// Test RegisterBenchmark with DISABLED_ benchmark\n//----------------------------------------------------------------------------//\nvoid DISABLED_BM_function(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(DISABLED_BM_function);\nReturnVal dummy3 = benchmark::RegisterBenchmark(\"DISABLED_BM_function_manual\",\n                                                DISABLED_BM_function);\n// No need to add cases because we don't expect them to run.\n\n//----------------------------------------------------------------------------//\n// Test RegisterBenchmark with different callable types\n//----------------------------------------------------------------------------//\n\nstruct CustomFixture {\n  void operator()(benchmark::State& st) {\n    for (auto _ : st) {\n    }\n  }\n};\n\nvoid TestRegistrationAtRuntime() {\n#ifdef BENCHMARK_HAS_CXX11\n  {\n    CustomFixture fx;\n    benchmark::RegisterBenchmark(\"custom_fixture\", fx);\n    AddCases({std::string(\"custom_fixture\")});\n  }\n#endif\n#ifndef BENCHMARK_HAS_NO_VARIADIC_REGISTER_BENCHMARK\n  {\n    const char* x = \"42\";\n    auto capturing_lam = [=](benchmark::State& st) {\n      for (auto _ : st) {\n      }\n      st.SetLabel(x);\n    };\n    benchmark::RegisterBenchmark(\"lambda_benchmark\", capturing_lam);\n    AddCases({{\"lambda_benchmark\", x}});\n  }\n#endif\n}\n\n// Test that all benchmarks, registered at either during static init or runtime,\n// are run and the results are passed to the reported.\nvoid RunTestOne() {\n  TestRegistrationAtRuntime();\n\n  TestReporter test_reporter;\n  benchmark::RunSpecifiedBenchmarks(&test_reporter);\n\n  typedef benchmark::BenchmarkReporter::Run Run;\n  auto EB = ExpectedResults.begin();\n\n  for (Run const& run : test_reporter.all_runs_) {\n    assert(EB != ExpectedResults.end());\n    EB->CheckRun(run);\n    ++EB;\n  }\n  assert(EB == ExpectedResults.end());\n}\n\n// Test that ClearRegisteredBenchmarks() clears all previously registered\n// benchmarks.\n// Also test that new benchmarks can be registered and ran afterwards.\nvoid RunTestTwo() {\n  assert(ExpectedResults.size() != 0 &&\n         \"must have at least one registered benchmark\");\n  ExpectedResults.clear();\n  benchmark::ClearRegisteredBenchmarks();\n\n  TestReporter test_reporter;\n  size_t num_ran = benchmark::RunSpecifiedBenchmarks(&test_reporter);\n  assert(num_ran == 0);\n  assert(test_reporter.all_runs_.begin() == test_reporter.all_runs_.end());\n\n  TestRegistrationAtRuntime();\n  num_ran = benchmark::RunSpecifiedBenchmarks(&test_reporter);\n  assert(num_ran == ExpectedResults.size());\n\n  typedef benchmark::BenchmarkReporter::Run Run;\n  auto EB = ExpectedResults.begin();\n\n  for (Run const& run : test_reporter.all_runs_) {\n    assert(EB != ExpectedResults.end());\n    EB->CheckRun(run);\n    ++EB;\n  }\n  assert(EB == ExpectedResults.end());\n}\n\nint main(int argc, char* argv[]) {\n  benchmark::Initialize(&argc, argv);\n\n  RunTestOne();\n  RunTestTwo();\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/repetitions_test.cc",
    "content": "\n#include \"benchmark/benchmark.h\"\n#include \"output_test.h\"\n\n// ========================================================================= //\n// ------------------------ Testing Basic Output --------------------------- //\n// ========================================================================= //\n\nstatic void BM_ExplicitRepetitions(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_ExplicitRepetitions)->Repetitions(2);\n\nADD_CASES(TC_ConsoleOut,\n          {{\"^BM_ExplicitRepetitions/repeats:2 %console_report$\"}});\nADD_CASES(TC_ConsoleOut,\n          {{\"^BM_ExplicitRepetitions/repeats:2 %console_report$\"}});\nADD_CASES(TC_ConsoleOut,\n          {{\"^BM_ExplicitRepetitions/repeats:2_mean %console_report$\"}});\nADD_CASES(TC_ConsoleOut,\n          {{\"^BM_ExplicitRepetitions/repeats:2_median %console_report$\"}});\nADD_CASES(TC_ConsoleOut,\n          {{\"^BM_ExplicitRepetitions/repeats:2_stddev %console_report$\"}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_ExplicitRepetitions/repeats:2\\\",$\"},\n           {\"\\\"family_index\\\": 0,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_ExplicitRepetitions/repeats:2\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 2,$\", MR_Next},\n           {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\"$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_ExplicitRepetitions/repeats:2\\\",$\"},\n           {\"\\\"family_index\\\": 0,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_ExplicitRepetitions/repeats:2\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 2,$\", MR_Next},\n           {\"\\\"repetition_index\\\": 1,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\"$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_ExplicitRepetitions/repeats:2_mean\\\",$\"},\n           {\"\\\"family_index\\\": 0,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_ExplicitRepetitions/repeats:2\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 2,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"aggregate_name\\\": \\\"mean\\\",$\", MR_Next},\n           {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\"$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_ExplicitRepetitions/repeats:2_median\\\",$\"},\n           {\"\\\"family_index\\\": 0,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_ExplicitRepetitions/repeats:2\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 2,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"aggregate_name\\\": \\\"median\\\",$\", MR_Next},\n           {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\"$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_ExplicitRepetitions/repeats:2_stddev\\\",$\"},\n           {\"\\\"family_index\\\": 0,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_ExplicitRepetitions/repeats:2\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 2,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"aggregate_name\\\": \\\"stddev\\\",$\", MR_Next},\n           {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\"$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_ExplicitRepetitions/repeats:2\\\",%csv_report$\"}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_ExplicitRepetitions/repeats:2\\\",%csv_report$\"}});\nADD_CASES(TC_CSVOut,\n          {{\"^\\\"BM_ExplicitRepetitions/repeats:2_mean\\\",%csv_report$\"}});\nADD_CASES(TC_CSVOut,\n          {{\"^\\\"BM_ExplicitRepetitions/repeats:2_median\\\",%csv_report$\"}});\nADD_CASES(TC_CSVOut,\n          {{\"^\\\"BM_ExplicitRepetitions/repeats:2_stddev\\\",%csv_report$\"}});\n\n// ========================================================================= //\n// ------------------------ Testing Basic Output --------------------------- //\n// ========================================================================= //\n\nstatic void BM_ImplicitRepetitions(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_ImplicitRepetitions);\n\nADD_CASES(TC_ConsoleOut, {{\"^BM_ImplicitRepetitions %console_report$\"}});\nADD_CASES(TC_ConsoleOut, {{\"^BM_ImplicitRepetitions %console_report$\"}});\nADD_CASES(TC_ConsoleOut, {{\"^BM_ImplicitRepetitions %console_report$\"}});\nADD_CASES(TC_ConsoleOut, {{\"^BM_ImplicitRepetitions_mean %console_report$\"}});\nADD_CASES(TC_ConsoleOut, {{\"^BM_ImplicitRepetitions_median %console_report$\"}});\nADD_CASES(TC_ConsoleOut, {{\"^BM_ImplicitRepetitions_stddev %console_report$\"}});\nADD_CASES(TC_JSONOut, {{\"\\\"name\\\": \\\"BM_ImplicitRepetitions\\\",$\"},\n                       {\"\\\"family_index\\\": 1,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_ImplicitRepetitions\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 3,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"iterations\\\": %int,$\", MR_Next},\n                       {\"\\\"real_time\\\": %float,$\", MR_Next},\n                       {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n                       {\"\\\"time_unit\\\": \\\"ns\\\"$\", MR_Next},\n                       {\"}\", MR_Next}});\nADD_CASES(TC_JSONOut, {{\"\\\"name\\\": \\\"BM_ImplicitRepetitions\\\",$\"},\n                       {\"\\\"family_index\\\": 1,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_ImplicitRepetitions\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 3,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 1,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"iterations\\\": %int,$\", MR_Next},\n                       {\"\\\"real_time\\\": %float,$\", MR_Next},\n                       {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n                       {\"\\\"time_unit\\\": \\\"ns\\\"$\", MR_Next},\n                       {\"}\", MR_Next}});\nADD_CASES(TC_JSONOut, {{\"\\\"name\\\": \\\"BM_ImplicitRepetitions\\\",$\"},\n                       {\"\\\"family_index\\\": 1,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_ImplicitRepetitions\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 3,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 2,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"iterations\\\": %int,$\", MR_Next},\n                       {\"\\\"real_time\\\": %float,$\", MR_Next},\n                       {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n                       {\"\\\"time_unit\\\": \\\"ns\\\"$\", MR_Next},\n                       {\"}\", MR_Next}});\nADD_CASES(TC_JSONOut, {{\"\\\"name\\\": \\\"BM_ImplicitRepetitions_mean\\\",$\"},\n                       {\"\\\"family_index\\\": 1,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_ImplicitRepetitions\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 3,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"aggregate_name\\\": \\\"mean\\\",$\", MR_Next},\n                       {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n                       {\"\\\"iterations\\\": %int,$\", MR_Next},\n                       {\"\\\"real_time\\\": %float,$\", MR_Next},\n                       {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n                       {\"\\\"time_unit\\\": \\\"ns\\\"$\", MR_Next},\n                       {\"}\", MR_Next}});\nADD_CASES(TC_JSONOut, {{\"\\\"name\\\": \\\"BM_ImplicitRepetitions_median\\\",$\"},\n                       {\"\\\"family_index\\\": 1,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_ImplicitRepetitions\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 3,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"aggregate_name\\\": \\\"median\\\",$\", MR_Next},\n                       {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n                       {\"\\\"iterations\\\": %int,$\", MR_Next},\n                       {\"\\\"real_time\\\": %float,$\", MR_Next},\n                       {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n                       {\"\\\"time_unit\\\": \\\"ns\\\"$\", MR_Next},\n                       {\"}\", MR_Next}});\nADD_CASES(TC_JSONOut, {{\"\\\"name\\\": \\\"BM_ImplicitRepetitions_stddev\\\",$\"},\n                       {\"\\\"family_index\\\": 1,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_ImplicitRepetitions\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 3,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"aggregate_name\\\": \\\"stddev\\\",$\", MR_Next},\n                       {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n                       {\"\\\"iterations\\\": %int,$\", MR_Next},\n                       {\"\\\"real_time\\\": %float,$\", MR_Next},\n                       {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n                       {\"\\\"time_unit\\\": \\\"ns\\\"$\", MR_Next},\n                       {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_ImplicitRepetitions\\\",%csv_report$\"}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_ImplicitRepetitions\\\",%csv_report$\"}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_ImplicitRepetitions_mean\\\",%csv_report$\"}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_ImplicitRepetitions_median\\\",%csv_report$\"}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_ImplicitRepetitions_stddev\\\",%csv_report$\"}});\n\n// ========================================================================= //\n// --------------------------- TEST CASES END ------------------------------ //\n// ========================================================================= //\n\nint main(int argc, char* argv[]) { RunOutputTests(argc, argv); }\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/report_aggregates_only_test.cc",
    "content": "\n#undef NDEBUG\n#include <cstdio>\n#include <string>\n\n#include \"benchmark/benchmark.h\"\n#include \"output_test.h\"\n\n// Ok this test is super ugly. We want to check what happens with the file\n// reporter in the presence of ReportAggregatesOnly().\n// We do not care about console output, the normal tests check that already.\n\nvoid BM_SummaryRepeat(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_SummaryRepeat)->Repetitions(3)->ReportAggregatesOnly();\n\nint main(int argc, char* argv[]) {\n  const std::string output = GetFileReporterOutput(argc, argv);\n\n  if (SubstrCnt(output, \"\\\"name\\\": \\\"BM_SummaryRepeat/repeats:3\") != 4 ||\n      SubstrCnt(output, \"\\\"name\\\": \\\"BM_SummaryRepeat/repeats:3_mean\\\"\") != 1 ||\n      SubstrCnt(output, \"\\\"name\\\": \\\"BM_SummaryRepeat/repeats:3_median\\\"\") !=\n          1 ||\n      SubstrCnt(output, \"\\\"name\\\": \\\"BM_SummaryRepeat/repeats:3_stddev\\\"\") !=\n          1 ||\n      SubstrCnt(output, \"\\\"name\\\": \\\"BM_SummaryRepeat/repeats:3_cv\\\"\") != 1) {\n    std::cout << \"Precondition mismatch. Expected to only find four \"\n                 \"occurrences of \\\"BM_SummaryRepeat/repeats:3\\\" substring:\\n\"\n                 \"\\\"name\\\": \\\"BM_SummaryRepeat/repeats:3_mean\\\", \"\n                 \"\\\"name\\\": \\\"BM_SummaryRepeat/repeats:3_median\\\", \"\n                 \"\\\"name\\\": \\\"BM_SummaryRepeat/repeats:3_stddev\\\", \"\n                 \"\\\"name\\\": \\\"BM_SummaryRepeat/repeats:3_cv\\\"\\nThe entire \"\n                 \"output:\\n\";\n    std::cout << output;\n    return 1;\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/reporter_output_test.cc",
    "content": "\n#undef NDEBUG\n#include <numeric>\n#include <utility>\n\n#include \"benchmark/benchmark.h\"\n#include \"output_test.h\"\n\n// ========================================================================= //\n// ---------------------- Testing Prologue Output -------------------------- //\n// ========================================================================= //\n\nADD_CASES(TC_ConsoleOut, {{\"^[-]+$\", MR_Next},\n                          {\"^Benchmark %s Time %s CPU %s Iterations$\", MR_Next},\n                          {\"^[-]+$\", MR_Next}});\nstatic int AddContextCases() {\n  AddCases(TC_ConsoleErr,\n           {\n               {\"^%int-%int-%intT%int:%int:%int[-+]%int:%int$\", MR_Default},\n               {\"Running .*(/|\\\\\\\\)reporter_output_test(\\\\.exe)?$\", MR_Next},\n               {\"Run on \\\\(%int X %float MHz CPU s?\\\\)\", MR_Next},\n           });\n  AddCases(TC_JSONOut,\n           {{\"^\\\\{\", MR_Default},\n            {\"\\\"context\\\":\", MR_Next},\n            {\"\\\"date\\\": \\\"\", MR_Next},\n            {\"\\\"host_name\\\":\", MR_Next},\n            {\"\\\"executable\\\": \\\".*(/|\\\\\\\\)reporter_output_test(\\\\.exe)?\\\",\",\n             MR_Next},\n            {\"\\\"num_cpus\\\": %int,$\", MR_Next},\n            {\"\\\"mhz_per_cpu\\\": %float,$\", MR_Next},\n            {\"\\\"caches\\\": \\\\[$\", MR_Default}});\n  auto const& Info = benchmark::CPUInfo::Get();\n  auto const& Caches = Info.caches;\n  if (!Caches.empty()) {\n    AddCases(TC_ConsoleErr, {{\"CPU Caches:$\", MR_Next}});\n  }\n  for (size_t I = 0; I < Caches.size(); ++I) {\n    std::string num_caches_str =\n        Caches[I].num_sharing != 0 ? \" \\\\(x%int\\\\)$\" : \"$\";\n    AddCases(TC_ConsoleErr,\n             {{\"L%int (Data|Instruction|Unified) %int KiB\" + num_caches_str,\n               MR_Next}});\n    AddCases(TC_JSONOut, {{\"\\\\{$\", MR_Next},\n                          {\"\\\"type\\\": \\\"\", MR_Next},\n                          {\"\\\"level\\\": %int,$\", MR_Next},\n                          {\"\\\"size\\\": %int,$\", MR_Next},\n                          {\"\\\"num_sharing\\\": %int$\", MR_Next},\n                          {\"}[,]{0,1}$\", MR_Next}});\n  }\n  AddCases(TC_JSONOut, {{\"],$\"}});\n  auto const& LoadAvg = Info.load_avg;\n  if (!LoadAvg.empty()) {\n    AddCases(TC_ConsoleErr,\n             {{\"Load Average: (%float, ){0,2}%float$\", MR_Next}});\n  }\n  AddCases(TC_JSONOut, {{\"\\\"load_avg\\\": \\\\[(%float,?){0,3}],$\", MR_Next}});\n  return 0;\n}\nint dummy_register = AddContextCases();\nADD_CASES(TC_CSVOut, {{\"%csv_header\"}});\n\n// ========================================================================= //\n// ------------------------ Testing Basic Output --------------------------- //\n// ========================================================================= //\n\nvoid BM_basic(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_basic);\n\nADD_CASES(TC_ConsoleOut, {{\"^BM_basic %console_report$\"}});\nADD_CASES(TC_JSONOut, {{\"\\\"name\\\": \\\"BM_basic\\\",$\"},\n                       {\"\\\"family_index\\\": 0,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_basic\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 1,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"iterations\\\": %int,$\", MR_Next},\n                       {\"\\\"real_time\\\": %float,$\", MR_Next},\n                       {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n                       {\"\\\"time_unit\\\": \\\"ns\\\"$\", MR_Next},\n                       {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_basic\\\",%csv_report$\"}});\n\n// ========================================================================= //\n// ------------------------ Testing Bytes per Second Output ---------------- //\n// ========================================================================= //\n\nvoid BM_bytes_per_second(benchmark::State& state) {\n  for (auto _ : state) {\n    // This test requires a non-zero CPU time to avoid divide-by-zero\n    auto iterations = state.iterations();\n    benchmark::DoNotOptimize(iterations);\n  }\n  state.SetBytesProcessed(1);\n}\nBENCHMARK(BM_bytes_per_second);\n\nADD_CASES(TC_ConsoleOut, {{\"^BM_bytes_per_second %console_report \"\n                           \"bytes_per_second=%float[kM]{0,1}/s$\"}});\nADD_CASES(TC_JSONOut, {{\"\\\"name\\\": \\\"BM_bytes_per_second\\\",$\"},\n                       {\"\\\"family_index\\\": 1,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_bytes_per_second\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 1,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"iterations\\\": %int,$\", MR_Next},\n                       {\"\\\"real_time\\\": %float,$\", MR_Next},\n                       {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n                       {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n                       {\"\\\"bytes_per_second\\\": %float$\", MR_Next},\n                       {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_bytes_per_second\\\",%csv_bytes_report$\"}});\n\n// ========================================================================= //\n// ------------------------ Testing Items per Second Output ---------------- //\n// ========================================================================= //\n\nvoid BM_items_per_second(benchmark::State& state) {\n  for (auto _ : state) {\n    // This test requires a non-zero CPU time to avoid divide-by-zero\n    auto iterations = state.iterations();\n    benchmark::DoNotOptimize(iterations);\n  }\n  state.SetItemsProcessed(1);\n}\nBENCHMARK(BM_items_per_second);\n\nADD_CASES(TC_ConsoleOut, {{\"^BM_items_per_second %console_report \"\n                           \"items_per_second=%float[kM]{0,1}/s$\"}});\nADD_CASES(TC_JSONOut, {{\"\\\"name\\\": \\\"BM_items_per_second\\\",$\"},\n                       {\"\\\"family_index\\\": 2,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_items_per_second\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 1,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"iterations\\\": %int,$\", MR_Next},\n                       {\"\\\"real_time\\\": %float,$\", MR_Next},\n                       {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n                       {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n                       {\"\\\"items_per_second\\\": %float$\", MR_Next},\n                       {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_items_per_second\\\",%csv_items_report$\"}});\n\n// ========================================================================= //\n// ------------------------ Testing Label Output --------------------------- //\n// ========================================================================= //\n\nvoid BM_label(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n  state.SetLabel(\"some label\");\n}\nBENCHMARK(BM_label);\n\nADD_CASES(TC_ConsoleOut, {{\"^BM_label %console_report some label$\"}});\nADD_CASES(TC_JSONOut, {{\"\\\"name\\\": \\\"BM_label\\\",$\"},\n                       {\"\\\"family_index\\\": 3,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_label\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 1,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"iterations\\\": %int,$\", MR_Next},\n                       {\"\\\"real_time\\\": %float,$\", MR_Next},\n                       {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n                       {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n                       {\"\\\"label\\\": \\\"some label\\\"$\", MR_Next},\n                       {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_label\\\",%csv_label_report_begin\\\"some \"\n                       \"label\\\"%csv_label_report_end$\"}});\n\n// ========================================================================= //\n// ------------------------ Testing Time Label Output ---------------------- //\n// ========================================================================= //\n\nvoid BM_time_label_nanosecond(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_time_label_nanosecond)->Unit(benchmark::kNanosecond);\n\nADD_CASES(TC_ConsoleOut, {{\"^BM_time_label_nanosecond %console_report$\"}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_time_label_nanosecond\\\",$\"},\n           {\"\\\"family_index\\\": 4,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_time_label_nanosecond\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 1,$\", MR_Next},\n           {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\"$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_time_label_nanosecond\\\",%csv_report$\"}});\n\nvoid BM_time_label_microsecond(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_time_label_microsecond)->Unit(benchmark::kMicrosecond);\n\nADD_CASES(TC_ConsoleOut, {{\"^BM_time_label_microsecond %console_us_report$\"}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_time_label_microsecond\\\",$\"},\n           {\"\\\"family_index\\\": 5,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_time_label_microsecond\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 1,$\", MR_Next},\n           {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"us\\\"$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_time_label_microsecond\\\",%csv_us_report$\"}});\n\nvoid BM_time_label_millisecond(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_time_label_millisecond)->Unit(benchmark::kMillisecond);\n\nADD_CASES(TC_ConsoleOut, {{\"^BM_time_label_millisecond %console_ms_report$\"}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_time_label_millisecond\\\",$\"},\n           {\"\\\"family_index\\\": 6,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_time_label_millisecond\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 1,$\", MR_Next},\n           {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ms\\\"$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_time_label_millisecond\\\",%csv_ms_report$\"}});\n\nvoid BM_time_label_second(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_time_label_second)->Unit(benchmark::kSecond);\n\nADD_CASES(TC_ConsoleOut, {{\"^BM_time_label_second %console_s_report$\"}});\nADD_CASES(TC_JSONOut, {{\"\\\"name\\\": \\\"BM_time_label_second\\\",$\"},\n                       {\"\\\"family_index\\\": 7,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_time_label_second\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 1,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"iterations\\\": %int,$\", MR_Next},\n                       {\"\\\"real_time\\\": %float,$\", MR_Next},\n                       {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n                       {\"\\\"time_unit\\\": \\\"s\\\"$\", MR_Next},\n                       {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_time_label_second\\\",%csv_s_report$\"}});\n\n// ========================================================================= //\n// ------------------------ Testing Error Output --------------------------- //\n// ========================================================================= //\n\nvoid BM_error(benchmark::State& state) {\n  state.SkipWithError(\"message\");\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_error);\nADD_CASES(TC_ConsoleOut, {{\"^BM_error[ ]+ERROR OCCURRED: 'message'$\"}});\nADD_CASES(TC_JSONOut, {{\"\\\"name\\\": \\\"BM_error\\\",$\"},\n                       {\"\\\"family_index\\\": 8,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_error\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 1,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"error_occurred\\\": true,$\", MR_Next},\n                       {\"\\\"error_message\\\": \\\"message\\\",$\", MR_Next}});\n\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_error\\\",,,,,,,,true,\\\"message\\\"$\"}});\n\n// ========================================================================= //\n// ------------------------ Testing No Arg Name Output -----------------------\n// //\n// ========================================================================= //\n\nvoid BM_no_arg_name(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_no_arg_name)->Arg(3);\nADD_CASES(TC_ConsoleOut, {{\"^BM_no_arg_name/3 %console_report$\"}});\nADD_CASES(TC_JSONOut, {{\"\\\"name\\\": \\\"BM_no_arg_name/3\\\",$\"},\n                       {\"\\\"family_index\\\": 9,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_no_arg_name/3\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 1,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_no_arg_name/3\\\",%csv_report$\"}});\n\n// ========================================================================= //\n// ------------------------ Testing Arg Name Output ------------------------ //\n// ========================================================================= //\n\nvoid BM_arg_name(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_arg_name)->ArgName(\"first\")->Arg(3);\nADD_CASES(TC_ConsoleOut, {{\"^BM_arg_name/first:3 %console_report$\"}});\nADD_CASES(TC_JSONOut, {{\"\\\"name\\\": \\\"BM_arg_name/first:3\\\",$\"},\n                       {\"\\\"family_index\\\": 10,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_arg_name/first:3\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 1,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_arg_name/first:3\\\",%csv_report$\"}});\n\n// ========================================================================= //\n// ------------------------ Testing Arg Names Output ----------------------- //\n// ========================================================================= //\n\nvoid BM_arg_names(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_arg_names)->Args({2, 5, 4})->ArgNames({\"first\", \"\", \"third\"});\nADD_CASES(TC_ConsoleOut,\n          {{\"^BM_arg_names/first:2/5/third:4 %console_report$\"}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_arg_names/first:2/5/third:4\\\",$\"},\n           {\"\\\"family_index\\\": 11,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_arg_names/first:2/5/third:4\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 1,$\", MR_Next},\n           {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_arg_names/first:2/5/third:4\\\",%csv_report$\"}});\n\n// ========================================================================= //\n// ------------------------ Testing Name Output ---------------------------- //\n// ========================================================================= //\n\nvoid BM_name(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_name)->Name(\"BM_custom_name\");\n\nADD_CASES(TC_ConsoleOut, {{\"^BM_custom_name %console_report$\"}});\nADD_CASES(TC_JSONOut, {{\"\\\"name\\\": \\\"BM_custom_name\\\",$\"},\n                       {\"\\\"family_index\\\": 12,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_custom_name\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 1,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"iterations\\\": %int,$\", MR_Next},\n                       {\"\\\"real_time\\\": %float,$\", MR_Next},\n                       {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n                       {\"\\\"time_unit\\\": \\\"ns\\\"$\", MR_Next},\n                       {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_custom_name\\\",%csv_report$\"}});\n\n// ========================================================================= //\n// ------------------------ Testing Big Args Output ------------------------ //\n// ========================================================================= //\n\nvoid BM_BigArgs(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_BigArgs)->RangeMultiplier(2)->Range(1U << 30U, 1U << 31U);\nADD_CASES(TC_ConsoleOut, {{\"^BM_BigArgs/1073741824 %console_report$\"},\n                          {\"^BM_BigArgs/2147483648 %console_report$\"}});\n\n// ========================================================================= //\n// ----------------------- Testing Complexity Output ----------------------- //\n// ========================================================================= //\n\nvoid BM_Complexity_O1(benchmark::State& state) {\n  for (auto _ : state) {\n    // This test requires a non-zero CPU time to avoid divide-by-zero\n    auto iterations = state.iterations();\n    benchmark::DoNotOptimize(iterations);\n  }\n  state.SetComplexityN(state.range(0));\n}\nBENCHMARK(BM_Complexity_O1)->Range(1, 1 << 18)->Complexity(benchmark::o1);\nSET_SUBSTITUTIONS({{\"%bigOStr\", \"[ ]* %float \\\\([0-9]+\\\\)\"},\n                   {\"%RMS\", \"[ ]*[0-9]+ %\"}});\nADD_CASES(TC_ConsoleOut, {{\"^BM_Complexity_O1_BigO %bigOStr %bigOStr[ ]*$\"},\n                          {\"^BM_Complexity_O1_RMS %RMS %RMS[ ]*$\"}});\n\n// ========================================================================= //\n// ----------------------- Testing Aggregate Output ------------------------ //\n// ========================================================================= //\n\n// Test that non-aggregate data is printed by default\nvoid BM_Repeat(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\n// need two repetitions min to be able to output any aggregate output\nBENCHMARK(BM_Repeat)->Repetitions(2);\nADD_CASES(TC_ConsoleOut,\n          {{\"^BM_Repeat/repeats:2 %console_report$\"},\n           {\"^BM_Repeat/repeats:2 %console_report$\"},\n           {\"^BM_Repeat/repeats:2_mean %console_time_only_report [ ]*2$\"},\n           {\"^BM_Repeat/repeats:2_median %console_time_only_report [ ]*2$\"},\n           {\"^BM_Repeat/repeats:2_stddev %console_time_only_report [ ]*2$\"}});\nADD_CASES(TC_JSONOut, {{\"\\\"name\\\": \\\"BM_Repeat/repeats:2\\\",$\"},\n                       {\"\\\"family_index\\\": 15,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_Repeat/repeats:2\\\"\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 2,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"name\\\": \\\"BM_Repeat/repeats:2\\\",$\"},\n                       {\"\\\"family_index\\\": 15,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_Repeat/repeats:2\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 2,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 1,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"name\\\": \\\"BM_Repeat/repeats:2_mean\\\",$\"},\n                       {\"\\\"family_index\\\": 15,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_Repeat/repeats:2\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 2,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"aggregate_name\\\": \\\"mean\\\",$\", MR_Next},\n                       {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n                       {\"\\\"iterations\\\": 2,$\", MR_Next},\n                       {\"\\\"name\\\": \\\"BM_Repeat/repeats:2_median\\\",$\"},\n                       {\"\\\"family_index\\\": 15,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_Repeat/repeats:2\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 2,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"aggregate_name\\\": \\\"median\\\",$\", MR_Next},\n                       {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n                       {\"\\\"iterations\\\": 2,$\", MR_Next},\n                       {\"\\\"name\\\": \\\"BM_Repeat/repeats:2_stddev\\\",$\"},\n                       {\"\\\"family_index\\\": 15,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_Repeat/repeats:2\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 2,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"aggregate_name\\\": \\\"stddev\\\",$\", MR_Next},\n                       {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n                       {\"\\\"iterations\\\": 2,$\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_Repeat/repeats:2\\\",%csv_report$\"},\n                      {\"^\\\"BM_Repeat/repeats:2\\\",%csv_report$\"},\n                      {\"^\\\"BM_Repeat/repeats:2_mean\\\",%csv_report$\"},\n                      {\"^\\\"BM_Repeat/repeats:2_median\\\",%csv_report$\"},\n                      {\"^\\\"BM_Repeat/repeats:2_stddev\\\",%csv_report$\"}});\n// but for two repetitions, mean and median is the same, so let's repeat..\nBENCHMARK(BM_Repeat)->Repetitions(3);\nADD_CASES(TC_ConsoleOut,\n          {{\"^BM_Repeat/repeats:3 %console_report$\"},\n           {\"^BM_Repeat/repeats:3 %console_report$\"},\n           {\"^BM_Repeat/repeats:3 %console_report$\"},\n           {\"^BM_Repeat/repeats:3_mean %console_time_only_report [ ]*3$\"},\n           {\"^BM_Repeat/repeats:3_median %console_time_only_report [ ]*3$\"},\n           {\"^BM_Repeat/repeats:3_stddev %console_time_only_report [ ]*3$\"}});\nADD_CASES(TC_JSONOut, {{\"\\\"name\\\": \\\"BM_Repeat/repeats:3\\\",$\"},\n                       {\"\\\"family_index\\\": 16,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_Repeat/repeats:3\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 3,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"name\\\": \\\"BM_Repeat/repeats:3\\\",$\"},\n                       {\"\\\"family_index\\\": 16,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_Repeat/repeats:3\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 3,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 1,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"name\\\": \\\"BM_Repeat/repeats:3\\\",$\"},\n                       {\"\\\"family_index\\\": 16,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_Repeat/repeats:3\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 3,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 2,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"name\\\": \\\"BM_Repeat/repeats:3_mean\\\",$\"},\n                       {\"\\\"family_index\\\": 16,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_Repeat/repeats:3\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 3,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"aggregate_name\\\": \\\"mean\\\",$\", MR_Next},\n                       {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n                       {\"\\\"iterations\\\": 3,$\", MR_Next},\n                       {\"\\\"name\\\": \\\"BM_Repeat/repeats:3_median\\\",$\"},\n                       {\"\\\"family_index\\\": 16,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_Repeat/repeats:3\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 3,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"aggregate_name\\\": \\\"median\\\",$\", MR_Next},\n                       {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n                       {\"\\\"iterations\\\": 3,$\", MR_Next},\n                       {\"\\\"name\\\": \\\"BM_Repeat/repeats:3_stddev\\\",$\"},\n                       {\"\\\"family_index\\\": 16,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_Repeat/repeats:3\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 3,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"aggregate_name\\\": \\\"stddev\\\",$\", MR_Next},\n                       {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n                       {\"\\\"iterations\\\": 3,$\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_Repeat/repeats:3\\\",%csv_report$\"},\n                      {\"^\\\"BM_Repeat/repeats:3\\\",%csv_report$\"},\n                      {\"^\\\"BM_Repeat/repeats:3\\\",%csv_report$\"},\n                      {\"^\\\"BM_Repeat/repeats:3_mean\\\",%csv_report$\"},\n                      {\"^\\\"BM_Repeat/repeats:3_median\\\",%csv_report$\"},\n                      {\"^\\\"BM_Repeat/repeats:3_stddev\\\",%csv_report$\"}});\n// median differs between even/odd number of repetitions, so just to be sure\nBENCHMARK(BM_Repeat)->Repetitions(4);\nADD_CASES(TC_ConsoleOut,\n          {{\"^BM_Repeat/repeats:4 %console_report$\"},\n           {\"^BM_Repeat/repeats:4 %console_report$\"},\n           {\"^BM_Repeat/repeats:4 %console_report$\"},\n           {\"^BM_Repeat/repeats:4 %console_report$\"},\n           {\"^BM_Repeat/repeats:4_mean %console_time_only_report [ ]*4$\"},\n           {\"^BM_Repeat/repeats:4_median %console_time_only_report [ ]*4$\"},\n           {\"^BM_Repeat/repeats:4_stddev %console_time_only_report [ ]*4$\"}});\nADD_CASES(TC_JSONOut, {{\"\\\"name\\\": \\\"BM_Repeat/repeats:4\\\",$\"},\n                       {\"\\\"family_index\\\": 17,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_Repeat/repeats:4\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 4,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"name\\\": \\\"BM_Repeat/repeats:4\\\",$\"},\n                       {\"\\\"family_index\\\": 17,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_Repeat/repeats:4\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 4,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 1,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"name\\\": \\\"BM_Repeat/repeats:4\\\",$\"},\n                       {\"\\\"family_index\\\": 17,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_Repeat/repeats:4\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 4,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 2,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"name\\\": \\\"BM_Repeat/repeats:4\\\",$\"},\n                       {\"\\\"family_index\\\": 17,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_Repeat/repeats:4\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 4,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 3,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"name\\\": \\\"BM_Repeat/repeats:4_mean\\\",$\"},\n                       {\"\\\"family_index\\\": 17,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_Repeat/repeats:4\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 4,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"aggregate_name\\\": \\\"mean\\\",$\", MR_Next},\n                       {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n                       {\"\\\"iterations\\\": 4,$\", MR_Next},\n                       {\"\\\"name\\\": \\\"BM_Repeat/repeats:4_median\\\",$\"},\n                       {\"\\\"family_index\\\": 17,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_Repeat/repeats:4\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 4,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"aggregate_name\\\": \\\"median\\\",$\", MR_Next},\n                       {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n                       {\"\\\"iterations\\\": 4,$\", MR_Next},\n                       {\"\\\"name\\\": \\\"BM_Repeat/repeats:4_stddev\\\",$\"},\n                       {\"\\\"family_index\\\": 17,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_Repeat/repeats:4\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 4,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"aggregate_name\\\": \\\"stddev\\\",$\", MR_Next},\n                       {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n                       {\"\\\"iterations\\\": 4,$\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_Repeat/repeats:4\\\",%csv_report$\"},\n                      {\"^\\\"BM_Repeat/repeats:4\\\",%csv_report$\"},\n                      {\"^\\\"BM_Repeat/repeats:4\\\",%csv_report$\"},\n                      {\"^\\\"BM_Repeat/repeats:4\\\",%csv_report$\"},\n                      {\"^\\\"BM_Repeat/repeats:4_mean\\\",%csv_report$\"},\n                      {\"^\\\"BM_Repeat/repeats:4_median\\\",%csv_report$\"},\n                      {\"^\\\"BM_Repeat/repeats:4_stddev\\\",%csv_report$\"}});\n\n// Test that a non-repeated test still prints non-aggregate results even when\n// only-aggregate reports have been requested\nvoid BM_RepeatOnce(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_RepeatOnce)->Repetitions(1)->ReportAggregatesOnly();\nADD_CASES(TC_ConsoleOut, {{\"^BM_RepeatOnce/repeats:1 %console_report$\"}});\nADD_CASES(TC_JSONOut, {{\"\\\"name\\\": \\\"BM_RepeatOnce/repeats:1\\\",$\"},\n                       {\"\\\"family_index\\\": 18,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_RepeatOnce/repeats:1\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 1,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_RepeatOnce/repeats:1\\\",%csv_report$\"}});\n\n// Test that non-aggregate data is not reported\nvoid BM_SummaryRepeat(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_SummaryRepeat)->Repetitions(3)->ReportAggregatesOnly();\nADD_CASES(\n    TC_ConsoleOut,\n    {{\".*BM_SummaryRepeat/repeats:3 \", MR_Not},\n     {\"^BM_SummaryRepeat/repeats:3_mean %console_time_only_report [ ]*3$\"},\n     {\"^BM_SummaryRepeat/repeats:3_median %console_time_only_report [ ]*3$\"},\n     {\"^BM_SummaryRepeat/repeats:3_stddev %console_time_only_report [ ]*3$\"}});\nADD_CASES(TC_JSONOut,\n          {{\".*BM_SummaryRepeat/repeats:3 \", MR_Not},\n           {\"\\\"name\\\": \\\"BM_SummaryRepeat/repeats:3_mean\\\",$\"},\n           {\"\\\"family_index\\\": 19,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_SummaryRepeat/repeats:3\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 3,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"aggregate_name\\\": \\\"mean\\\",$\", MR_Next},\n           {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n           {\"\\\"iterations\\\": 3,$\", MR_Next},\n           {\"\\\"name\\\": \\\"BM_SummaryRepeat/repeats:3_median\\\",$\"},\n           {\"\\\"family_index\\\": 19,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_SummaryRepeat/repeats:3\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 3,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"aggregate_name\\\": \\\"median\\\",$\", MR_Next},\n           {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n           {\"\\\"iterations\\\": 3,$\", MR_Next},\n           {\"\\\"name\\\": \\\"BM_SummaryRepeat/repeats:3_stddev\\\",$\"},\n           {\"\\\"family_index\\\": 19,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_SummaryRepeat/repeats:3\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 3,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"aggregate_name\\\": \\\"stddev\\\",$\", MR_Next},\n           {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n           {\"\\\"iterations\\\": 3,$\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\".*BM_SummaryRepeat/repeats:3 \", MR_Not},\n                      {\"^\\\"BM_SummaryRepeat/repeats:3_mean\\\",%csv_report$\"},\n                      {\"^\\\"BM_SummaryRepeat/repeats:3_median\\\",%csv_report$\"},\n                      {\"^\\\"BM_SummaryRepeat/repeats:3_stddev\\\",%csv_report$\"}});\n\n// Test that non-aggregate data is not displayed.\n// NOTE: this test is kinda bad. we are only testing the display output.\n//       But we don't check that the file output still contains everything...\nvoid BM_SummaryDisplay(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_SummaryDisplay)->Repetitions(2)->DisplayAggregatesOnly();\nADD_CASES(\n    TC_ConsoleOut,\n    {{\".*BM_SummaryDisplay/repeats:2 \", MR_Not},\n     {\"^BM_SummaryDisplay/repeats:2_mean %console_time_only_report [ ]*2$\"},\n     {\"^BM_SummaryDisplay/repeats:2_median %console_time_only_report [ ]*2$\"},\n     {\"^BM_SummaryDisplay/repeats:2_stddev %console_time_only_report [ ]*2$\"}});\nADD_CASES(TC_JSONOut,\n          {{\".*BM_SummaryDisplay/repeats:2 \", MR_Not},\n           {\"\\\"name\\\": \\\"BM_SummaryDisplay/repeats:2_mean\\\",$\"},\n           {\"\\\"family_index\\\": 20,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_SummaryDisplay/repeats:2\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 2,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"aggregate_name\\\": \\\"mean\\\",$\", MR_Next},\n           {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n           {\"\\\"iterations\\\": 2,$\", MR_Next},\n           {\"\\\"name\\\": \\\"BM_SummaryDisplay/repeats:2_median\\\",$\"},\n           {\"\\\"family_index\\\": 20,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_SummaryDisplay/repeats:2\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 2,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"aggregate_name\\\": \\\"median\\\",$\", MR_Next},\n           {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n           {\"\\\"iterations\\\": 2,$\", MR_Next},\n           {\"\\\"name\\\": \\\"BM_SummaryDisplay/repeats:2_stddev\\\",$\"},\n           {\"\\\"family_index\\\": 20,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_SummaryDisplay/repeats:2\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 2,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"aggregate_name\\\": \\\"stddev\\\",$\", MR_Next},\n           {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n           {\"\\\"iterations\\\": 2,$\", MR_Next}});\nADD_CASES(TC_CSVOut,\n          {{\".*BM_SummaryDisplay/repeats:2 \", MR_Not},\n           {\"^\\\"BM_SummaryDisplay/repeats:2_mean\\\",%csv_report$\"},\n           {\"^\\\"BM_SummaryDisplay/repeats:2_median\\\",%csv_report$\"},\n           {\"^\\\"BM_SummaryDisplay/repeats:2_stddev\\\",%csv_report$\"}});\n\n// Test repeats with custom time unit.\nvoid BM_RepeatTimeUnit(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_RepeatTimeUnit)\n    ->Repetitions(3)\n    ->ReportAggregatesOnly()\n    ->Unit(benchmark::kMicrosecond);\nADD_CASES(\n    TC_ConsoleOut,\n    {{\".*BM_RepeatTimeUnit/repeats:3 \", MR_Not},\n     {\"^BM_RepeatTimeUnit/repeats:3_mean %console_us_time_only_report [ ]*3$\"},\n     {\"^BM_RepeatTimeUnit/repeats:3_median %console_us_time_only_report [ \"\n      \"]*3$\"},\n     {\"^BM_RepeatTimeUnit/repeats:3_stddev %console_us_time_only_report [ \"\n      \"]*3$\"}});\nADD_CASES(TC_JSONOut,\n          {{\".*BM_RepeatTimeUnit/repeats:3 \", MR_Not},\n           {\"\\\"name\\\": \\\"BM_RepeatTimeUnit/repeats:3_mean\\\",$\"},\n           {\"\\\"family_index\\\": 21,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_RepeatTimeUnit/repeats:3\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 3,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"aggregate_name\\\": \\\"mean\\\",$\", MR_Next},\n           {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n           {\"\\\"iterations\\\": 3,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"us\\\",?$\"},\n           {\"\\\"name\\\": \\\"BM_RepeatTimeUnit/repeats:3_median\\\",$\"},\n           {\"\\\"family_index\\\": 21,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_RepeatTimeUnit/repeats:3\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 3,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"aggregate_name\\\": \\\"median\\\",$\", MR_Next},\n           {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n           {\"\\\"iterations\\\": 3,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"us\\\",?$\"},\n           {\"\\\"name\\\": \\\"BM_RepeatTimeUnit/repeats:3_stddev\\\",$\"},\n           {\"\\\"family_index\\\": 21,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_RepeatTimeUnit/repeats:3\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 3,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"aggregate_name\\\": \\\"stddev\\\",$\", MR_Next},\n           {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n           {\"\\\"iterations\\\": 3,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"us\\\",?$\"}});\nADD_CASES(TC_CSVOut,\n          {{\".*BM_RepeatTimeUnit/repeats:3 \", MR_Not},\n           {\"^\\\"BM_RepeatTimeUnit/repeats:3_mean\\\",%csv_us_report$\"},\n           {\"^\\\"BM_RepeatTimeUnit/repeats:3_median\\\",%csv_us_report$\"},\n           {\"^\\\"BM_RepeatTimeUnit/repeats:3_stddev\\\",%csv_us_report$\"}});\n\n// ========================================================================= //\n// -------------------- Testing user-provided statistics ------------------- //\n// ========================================================================= //\n\nconst auto UserStatistics = [](const std::vector<double>& v) {\n  return v.back();\n};\nvoid BM_UserStats(benchmark::State& state) {\n  for (auto _ : state) {\n    state.SetIterationTime(150 / 10e8);\n  }\n}\n// clang-format off\nBENCHMARK(BM_UserStats)\n  ->Repetitions(3)\n  ->Iterations(5)\n  ->UseManualTime()\n  ->ComputeStatistics(\"\", UserStatistics);\n// clang-format on\n\n// check that user-provided stats is calculated, and is after the default-ones\n// empty string as name is intentional, it would sort before anything else\nADD_CASES(TC_ConsoleOut, {{\"^BM_UserStats/iterations:5/repeats:3/manual_time [ \"\n                           \"]* 150 ns %time [ ]*5$\"},\n                          {\"^BM_UserStats/iterations:5/repeats:3/manual_time [ \"\n                           \"]* 150 ns %time [ ]*5$\"},\n                          {\"^BM_UserStats/iterations:5/repeats:3/manual_time [ \"\n                           \"]* 150 ns %time [ ]*5$\"},\n                          {\"^BM_UserStats/iterations:5/repeats:3/\"\n                           \"manual_time_mean [ ]* 150 ns %time [ ]*3$\"},\n                          {\"^BM_UserStats/iterations:5/repeats:3/\"\n                           \"manual_time_median [ ]* 150 ns %time [ ]*3$\"},\n                          {\"^BM_UserStats/iterations:5/repeats:3/\"\n                           \"manual_time_stddev [ ]* 0.000 ns %time [ ]*3$\"},\n                          {\"^BM_UserStats/iterations:5/repeats:3/manual_time_ \"\n                           \"[ ]* 150 ns %time [ ]*3$\"}});\nADD_CASES(\n    TC_JSONOut,\n    {{\"\\\"name\\\": \\\"BM_UserStats/iterations:5/repeats:3/manual_time\\\",$\"},\n     {\"\\\"family_index\\\": 22,$\", MR_Next},\n     {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n     {\"\\\"run_name\\\": \\\"BM_UserStats/iterations:5/repeats:3/manual_time\\\",$\",\n      MR_Next},\n     {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n     {\"\\\"repetitions\\\": 3,$\", MR_Next},\n     {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n     {\"\\\"threads\\\": 1,$\", MR_Next},\n     {\"\\\"iterations\\\": 5,$\", MR_Next},\n     {\"\\\"real_time\\\": 1\\\\.5(0)*e\\\\+(0)*2,$\", MR_Next},\n     {\"\\\"name\\\": \\\"BM_UserStats/iterations:5/repeats:3/manual_time\\\",$\"},\n     {\"\\\"family_index\\\": 22,$\", MR_Next},\n     {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n     {\"\\\"run_name\\\": \\\"BM_UserStats/iterations:5/repeats:3/manual_time\\\",$\",\n      MR_Next},\n     {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n     {\"\\\"repetitions\\\": 3,$\", MR_Next},\n     {\"\\\"repetition_index\\\": 1,$\", MR_Next},\n     {\"\\\"threads\\\": 1,$\", MR_Next},\n     {\"\\\"iterations\\\": 5,$\", MR_Next},\n     {\"\\\"real_time\\\": 1\\\\.5(0)*e\\\\+(0)*2,$\", MR_Next},\n     {\"\\\"name\\\": \\\"BM_UserStats/iterations:5/repeats:3/manual_time\\\",$\"},\n     {\"\\\"family_index\\\": 22,$\", MR_Next},\n     {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n     {\"\\\"run_name\\\": \\\"BM_UserStats/iterations:5/repeats:3/manual_time\\\",$\",\n      MR_Next},\n     {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n     {\"\\\"repetitions\\\": 3,$\", MR_Next},\n     {\"\\\"repetition_index\\\": 2,$\", MR_Next},\n     {\"\\\"threads\\\": 1,$\", MR_Next},\n     {\"\\\"iterations\\\": 5,$\", MR_Next},\n     {\"\\\"real_time\\\": 1\\\\.5(0)*e\\\\+(0)*2,$\", MR_Next},\n     {\"\\\"name\\\": \\\"BM_UserStats/iterations:5/repeats:3/manual_time_mean\\\",$\"},\n     {\"\\\"family_index\\\": 22,$\", MR_Next},\n     {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n     {\"\\\"run_name\\\": \\\"BM_UserStats/iterations:5/repeats:3/manual_time\\\",$\",\n      MR_Next},\n     {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n     {\"\\\"repetitions\\\": 3,$\", MR_Next},\n     {\"\\\"threads\\\": 1,$\", MR_Next},\n     {\"\\\"aggregate_name\\\": \\\"mean\\\",$\", MR_Next},\n     {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n     {\"\\\"iterations\\\": 3,$\", MR_Next},\n     {\"\\\"real_time\\\": 1\\\\.5(0)*e\\\\+(0)*2,$\", MR_Next},\n     {\"\\\"name\\\": \\\"BM_UserStats/iterations:5/repeats:3/manual_time_median\\\",$\"},\n     {\"\\\"family_index\\\": 22,$\", MR_Next},\n     {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n     {\"\\\"run_name\\\": \\\"BM_UserStats/iterations:5/repeats:3/manual_time\\\",$\",\n      MR_Next},\n     {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n     {\"\\\"repetitions\\\": 3,$\", MR_Next},\n     {\"\\\"threads\\\": 1,$\", MR_Next},\n     {\"\\\"aggregate_name\\\": \\\"median\\\",$\", MR_Next},\n     {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n     {\"\\\"iterations\\\": 3,$\", MR_Next},\n     {\"\\\"real_time\\\": 1\\\\.5(0)*e\\\\+(0)*2,$\", MR_Next},\n     {\"\\\"name\\\": \\\"BM_UserStats/iterations:5/repeats:3/manual_time_stddev\\\",$\"},\n     {\"\\\"family_index\\\": 22,$\", MR_Next},\n     {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n     {\"\\\"run_name\\\": \\\"BM_UserStats/iterations:5/repeats:3/manual_time\\\",$\",\n      MR_Next},\n     {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n     {\"\\\"repetitions\\\": 3,$\", MR_Next},\n     {\"\\\"threads\\\": 1,$\", MR_Next},\n     {\"\\\"aggregate_name\\\": \\\"stddev\\\",$\", MR_Next},\n     {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n     {\"\\\"iterations\\\": 3,$\", MR_Next},\n     {\"\\\"real_time\\\": %float,$\", MR_Next},\n     {\"\\\"name\\\": \\\"BM_UserStats/iterations:5/repeats:3/manual_time_\\\",$\"},\n     {\"\\\"family_index\\\": 22,$\", MR_Next},\n     {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n     {\"\\\"run_name\\\": \\\"BM_UserStats/iterations:5/repeats:3/manual_time\\\",$\",\n      MR_Next},\n     {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n     {\"\\\"repetitions\\\": 3,$\", MR_Next},\n     {\"\\\"threads\\\": 1,$\", MR_Next},\n     {\"\\\"aggregate_name\\\": \\\"\\\",$\", MR_Next},\n     {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n     {\"\\\"iterations\\\": 3,$\", MR_Next},\n     {\"\\\"real_time\\\": 1\\\\.5(0)*e\\\\+(0)*2,$\", MR_Next}});\nADD_CASES(\n    TC_CSVOut,\n    {{\"^\\\"BM_UserStats/iterations:5/repeats:3/manual_time\\\",%csv_report$\"},\n     {\"^\\\"BM_UserStats/iterations:5/repeats:3/manual_time\\\",%csv_report$\"},\n     {\"^\\\"BM_UserStats/iterations:5/repeats:3/manual_time\\\",%csv_report$\"},\n     {\"^\\\"BM_UserStats/iterations:5/repeats:3/manual_time_mean\\\",%csv_report$\"},\n     {\"^\\\"BM_UserStats/iterations:5/repeats:3/\"\n      \"manual_time_median\\\",%csv_report$\"},\n     {\"^\\\"BM_UserStats/iterations:5/repeats:3/\"\n      \"manual_time_stddev\\\",%csv_report$\"},\n     {\"^\\\"BM_UserStats/iterations:5/repeats:3/manual_time_\\\",%csv_report$\"}});\n\n// ========================================================================= //\n// ------------- Testing relative standard deviation statistics ------------ //\n// ========================================================================= //\n\nconst auto UserPercentStatistics = [](const std::vector<double>&) {\n  return 1. / 100.;\n};\nvoid BM_UserPercentStats(benchmark::State& state) {\n  for (auto _ : state) {\n    state.SetIterationTime(150 / 10e8);\n  }\n}\n// clang-format off\nBENCHMARK(BM_UserPercentStats)\n  ->Repetitions(3)\n  ->Iterations(5)\n  ->UseManualTime()\n  ->Unit(benchmark::TimeUnit::kNanosecond)\n  ->ComputeStatistics(\"\", UserPercentStatistics, benchmark::StatisticUnit::kPercentage);\n// clang-format on\n\n// check that UserPercent-provided stats is calculated, and is after the\n// default-ones empty string as name is intentional, it would sort before\n// anything else\nADD_CASES(TC_ConsoleOut,\n          {{\"^BM_UserPercentStats/iterations:5/repeats:3/manual_time [ \"\n            \"]* 150 ns %time [ ]*5$\"},\n           {\"^BM_UserPercentStats/iterations:5/repeats:3/manual_time [ \"\n            \"]* 150 ns %time [ ]*5$\"},\n           {\"^BM_UserPercentStats/iterations:5/repeats:3/manual_time [ \"\n            \"]* 150 ns %time [ ]*5$\"},\n           {\"^BM_UserPercentStats/iterations:5/repeats:3/\"\n            \"manual_time_mean [ ]* 150 ns %time [ ]*3$\"},\n           {\"^BM_UserPercentStats/iterations:5/repeats:3/\"\n            \"manual_time_median [ ]* 150 ns %time [ ]*3$\"},\n           {\"^BM_UserPercentStats/iterations:5/repeats:3/\"\n            \"manual_time_stddev [ ]* 0.000 ns %time [ ]*3$\"},\n           {\"^BM_UserPercentStats/iterations:5/repeats:3/manual_time_ \"\n            \"[ ]* 1.00 % [ ]* 1.00 %[ ]*3$\"}});\nADD_CASES(\n    TC_JSONOut,\n    {{\"\\\"name\\\": \\\"BM_UserPercentStats/iterations:5/repeats:3/manual_time\\\",$\"},\n     {\"\\\"family_index\\\": 23,$\", MR_Next},\n     {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n     {\"\\\"run_name\\\": \"\n      \"\\\"BM_UserPercentStats/iterations:5/repeats:3/manual_time\\\",$\",\n      MR_Next},\n     {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n     {\"\\\"repetitions\\\": 3,$\", MR_Next},\n     {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n     {\"\\\"threads\\\": 1,$\", MR_Next},\n     {\"\\\"iterations\\\": 5,$\", MR_Next},\n     {\"\\\"real_time\\\": 1\\\\.5(0)*e\\\\+(0)*2,$\", MR_Next},\n     {\"\\\"name\\\": \\\"BM_UserPercentStats/iterations:5/repeats:3/manual_time\\\",$\"},\n     {\"\\\"family_index\\\": 23,$\", MR_Next},\n     {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n     {\"\\\"run_name\\\": \"\n      \"\\\"BM_UserPercentStats/iterations:5/repeats:3/manual_time\\\",$\",\n      MR_Next},\n     {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n     {\"\\\"repetitions\\\": 3,$\", MR_Next},\n     {\"\\\"repetition_index\\\": 1,$\", MR_Next},\n     {\"\\\"threads\\\": 1,$\", MR_Next},\n     {\"\\\"iterations\\\": 5,$\", MR_Next},\n     {\"\\\"real_time\\\": 1\\\\.5(0)*e\\\\+(0)*2,$\", MR_Next},\n     {\"\\\"name\\\": \\\"BM_UserPercentStats/iterations:5/repeats:3/manual_time\\\",$\"},\n     {\"\\\"family_index\\\": 23,$\", MR_Next},\n     {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n     {\"\\\"run_name\\\": \"\n      \"\\\"BM_UserPercentStats/iterations:5/repeats:3/manual_time\\\",$\",\n      MR_Next},\n     {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n     {\"\\\"repetitions\\\": 3,$\", MR_Next},\n     {\"\\\"repetition_index\\\": 2,$\", MR_Next},\n     {\"\\\"threads\\\": 1,$\", MR_Next},\n     {\"\\\"iterations\\\": 5,$\", MR_Next},\n     {\"\\\"real_time\\\": 1\\\\.5(0)*e\\\\+(0)*2,$\", MR_Next},\n     {\"\\\"name\\\": \"\n      \"\\\"BM_UserPercentStats/iterations:5/repeats:3/manual_time_mean\\\",$\"},\n     {\"\\\"family_index\\\": 23,$\", MR_Next},\n     {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n     {\"\\\"run_name\\\": \"\n      \"\\\"BM_UserPercentStats/iterations:5/repeats:3/manual_time\\\",$\",\n      MR_Next},\n     {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n     {\"\\\"repetitions\\\": 3,$\", MR_Next},\n     {\"\\\"threads\\\": 1,$\", MR_Next},\n     {\"\\\"aggregate_name\\\": \\\"mean\\\",$\", MR_Next},\n     {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n     {\"\\\"iterations\\\": 3,$\", MR_Next},\n     {\"\\\"real_time\\\": 1\\\\.5(0)*e\\\\+(0)*2,$\", MR_Next},\n     {\"\\\"name\\\": \"\n      \"\\\"BM_UserPercentStats/iterations:5/repeats:3/manual_time_median\\\",$\"},\n     {\"\\\"family_index\\\": 23,$\", MR_Next},\n     {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n     {\"\\\"run_name\\\": \"\n      \"\\\"BM_UserPercentStats/iterations:5/repeats:3/manual_time\\\",$\",\n      MR_Next},\n     {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n     {\"\\\"repetitions\\\": 3,$\", MR_Next},\n     {\"\\\"threads\\\": 1,$\", MR_Next},\n     {\"\\\"aggregate_name\\\": \\\"median\\\",$\", MR_Next},\n     {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n     {\"\\\"iterations\\\": 3,$\", MR_Next},\n     {\"\\\"real_time\\\": 1\\\\.5(0)*e\\\\+(0)*2,$\", MR_Next},\n     {\"\\\"name\\\": \"\n      \"\\\"BM_UserPercentStats/iterations:5/repeats:3/manual_time_stddev\\\",$\"},\n     {\"\\\"family_index\\\": 23,$\", MR_Next},\n     {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n     {\"\\\"run_name\\\": \"\n      \"\\\"BM_UserPercentStats/iterations:5/repeats:3/manual_time\\\",$\",\n      MR_Next},\n     {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n     {\"\\\"repetitions\\\": 3,$\", MR_Next},\n     {\"\\\"threads\\\": 1,$\", MR_Next},\n     {\"\\\"aggregate_name\\\": \\\"stddev\\\",$\", MR_Next},\n     {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n     {\"\\\"iterations\\\": 3,$\", MR_Next},\n     {\"\\\"real_time\\\": %float,$\", MR_Next},\n     {\"\\\"name\\\": \"\n      \"\\\"BM_UserPercentStats/iterations:5/repeats:3/manual_time_\\\",$\"},\n     {\"\\\"family_index\\\": 23,$\", MR_Next},\n     {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n     {\"\\\"run_name\\\": \"\n      \"\\\"BM_UserPercentStats/iterations:5/repeats:3/manual_time\\\",$\",\n      MR_Next},\n     {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n     {\"\\\"repetitions\\\": 3,$\", MR_Next},\n     {\"\\\"threads\\\": 1,$\", MR_Next},\n     {\"\\\"aggregate_name\\\": \\\"\\\",$\", MR_Next},\n     {\"\\\"aggregate_unit\\\": \\\"percentage\\\",$\", MR_Next},\n     {\"\\\"iterations\\\": 3,$\", MR_Next},\n     {\"\\\"real_time\\\": 1\\\\.(0)*e-(0)*2,$\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_UserPercentStats/iterations:5/repeats:3/\"\n                       \"manual_time\\\",%csv_report$\"},\n                      {\"^\\\"BM_UserPercentStats/iterations:5/repeats:3/\"\n                       \"manual_time\\\",%csv_report$\"},\n                      {\"^\\\"BM_UserPercentStats/iterations:5/repeats:3/\"\n                       \"manual_time\\\",%csv_report$\"},\n                      {\"^\\\"BM_UserPercentStats/iterations:5/repeats:3/\"\n                       \"manual_time_mean\\\",%csv_report$\"},\n                      {\"^\\\"BM_UserPercentStats/iterations:5/repeats:3/\"\n                       \"manual_time_median\\\",%csv_report$\"},\n                      {\"^\\\"BM_UserPercentStats/iterations:5/repeats:3/\"\n                       \"manual_time_stddev\\\",%csv_report$\"},\n                      {\"^\\\"BM_UserPercentStats/iterations:5/repeats:3/\"\n                       \"manual_time_\\\",%csv_report$\"}});\n\n// ========================================================================= //\n// ------------------------- Testing StrEscape JSON ------------------------ //\n// ========================================================================= //\n#if 0  // enable when csv testing code correctly handles multi-line fields\nvoid BM_JSON_Format(benchmark::State& state) {\n  state.SkipWithError(\"val\\b\\f\\n\\r\\t\\\\\\\"with\\\"es,capes\");\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_JSON_Format);\nADD_CASES(TC_JSONOut, {{\"\\\"name\\\": \\\"BM_JSON_Format\\\",$\"},\n                                              {\"\\\"family_index\\\": 23,$\", MR_Next},\n{\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_JSON_Format\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 1,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"error_occurred\\\": true,$\", MR_Next},\n                       {R\"(\"error_message\": \"val\\\\b\\\\f\\\\n\\\\r\\\\t\\\\\\\\\\\\\"with\\\\\"es,capes\",$)\", MR_Next}});\n#endif\n// ========================================================================= //\n// -------------------------- Testing CsvEscape ---------------------------- //\n// ========================================================================= //\n\nvoid BM_CSV_Format(benchmark::State& state) {\n  state.SkipWithError(\"\\\"freedom\\\"\");\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_CSV_Format);\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_CSV_Format\\\",,,,,,,,true,\\\"\\\"\\\"freedom\\\"\\\"\\\"$\"}});\n\n// ========================================================================= //\n// --------------------------- TEST CASES END ------------------------------ //\n// ========================================================================= //\n\nint main(int argc, char* argv[]) { RunOutputTests(argc, argv); }\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/skip_with_error_test.cc",
    "content": "\n#undef NDEBUG\n#include <cassert>\n#include <vector>\n\n#include \"../src/check.h\"  // NOTE: check.h is for internal use only!\n#include \"benchmark/benchmark.h\"\n\nnamespace {\n\nclass TestReporter : public benchmark::ConsoleReporter {\n public:\n  bool ReportContext(const Context& context) override {\n    return ConsoleReporter::ReportContext(context);\n  };\n\n  void ReportRuns(const std::vector<Run>& report) override {\n    all_runs_.insert(all_runs_.end(), begin(report), end(report));\n    ConsoleReporter::ReportRuns(report);\n  }\n\n  TestReporter() {}\n  ~TestReporter() override {}\n\n  mutable std::vector<Run> all_runs_;\n};\n\nstruct TestCase {\n  std::string name;\n  bool error_occurred;\n  std::string error_message;\n\n  typedef benchmark::BenchmarkReporter::Run Run;\n\n  void CheckRun(Run const& run) const {\n    BM_CHECK(name == run.benchmark_name())\n        << \"expected \" << name << \" got \" << run.benchmark_name();\n    BM_CHECK_EQ(error_occurred,\n                benchmark::internal::SkippedWithError == run.skipped);\n    BM_CHECK(error_message == run.skip_message);\n    if (error_occurred) {\n      // BM_CHECK(run.iterations == 0);\n    } else {\n      BM_CHECK(run.iterations != 0);\n    }\n  }\n};\n\nstd::vector<TestCase> ExpectedResults;\n\nint AddCases(const std::string& base_name,\n             std::initializer_list<TestCase> const& v) {\n  for (auto TC : v) {\n    TC.name = base_name + TC.name;\n    ExpectedResults.push_back(std::move(TC));\n  }\n  return 0;\n}\n\n#define CONCAT(x, y) CONCAT2(x, y)\n#define CONCAT2(x, y) x##y\n#define ADD_CASES(...) int CONCAT(dummy, __LINE__) = AddCases(__VA_ARGS__)\n\n}  // end namespace\n\nvoid BM_error_no_running(benchmark::State& state) {\n  state.SkipWithError(\"error message\");\n}\nBENCHMARK(BM_error_no_running);\nADD_CASES(\"BM_error_no_running\", {{\"\", true, \"error message\"}});\n\nvoid BM_error_before_running(benchmark::State& state) {\n  state.SkipWithError(\"error message\");\n  while (state.KeepRunning()) {\n    assert(false);\n  }\n}\nBENCHMARK(BM_error_before_running);\nADD_CASES(\"BM_error_before_running\", {{\"\", true, \"error message\"}});\n\nvoid BM_error_before_running_batch(benchmark::State& state) {\n  state.SkipWithError(\"error message\");\n  while (state.KeepRunningBatch(17)) {\n    assert(false);\n  }\n}\nBENCHMARK(BM_error_before_running_batch);\nADD_CASES(\"BM_error_before_running_batch\", {{\"\", true, \"error message\"}});\n\nvoid BM_error_before_running_range_for(benchmark::State& state) {\n  state.SkipWithError(\"error message\");\n  for (auto _ : state) {\n    assert(false);\n  }\n}\nBENCHMARK(BM_error_before_running_range_for);\nADD_CASES(\"BM_error_before_running_range_for\", {{\"\", true, \"error message\"}});\n\nvoid BM_error_during_running(benchmark::State& state) {\n  int first_iter = true;\n  while (state.KeepRunning()) {\n    if (state.range(0) == 1 && state.thread_index() <= (state.threads() / 2)) {\n      assert(first_iter);\n      first_iter = false;\n      state.SkipWithError(\"error message\");\n    } else {\n      state.PauseTiming();\n      state.ResumeTiming();\n    }\n  }\n}\nBENCHMARK(BM_error_during_running)->Arg(1)->Arg(2)->ThreadRange(1, 8);\nADD_CASES(\"BM_error_during_running\", {{\"/1/threads:1\", true, \"error message\"},\n                                      {\"/1/threads:2\", true, \"error message\"},\n                                      {\"/1/threads:4\", true, \"error message\"},\n                                      {\"/1/threads:8\", true, \"error message\"},\n                                      {\"/2/threads:1\", false, \"\"},\n                                      {\"/2/threads:2\", false, \"\"},\n                                      {\"/2/threads:4\", false, \"\"},\n                                      {\"/2/threads:8\", false, \"\"}});\n\nvoid BM_error_during_running_ranged_for(benchmark::State& state) {\n  assert(state.max_iterations > 3 && \"test requires at least a few iterations\");\n  bool first_iter = true;\n  // NOTE: Users should not write the for loop explicitly.\n  for (auto It = state.begin(), End = state.end(); It != End; ++It) {\n    if (state.range(0) == 1) {\n      assert(first_iter);\n      first_iter = false;\n      (void)first_iter;\n      state.SkipWithError(\"error message\");\n      // Test the unfortunate but documented behavior that the ranged-for loop\n      // doesn't automatically terminate when SkipWithError is set.\n      assert(++It != End);\n      break;  // Required behavior\n    }\n  }\n}\nBENCHMARK(BM_error_during_running_ranged_for)->Arg(1)->Arg(2)->Iterations(5);\nADD_CASES(\"BM_error_during_running_ranged_for\",\n          {{\"/1/iterations:5\", true, \"error message\"},\n           {\"/2/iterations:5\", false, \"\"}});\n\nvoid BM_error_after_running(benchmark::State& state) {\n  for (auto _ : state) {\n    auto iterations = state.iterations();\n    benchmark::DoNotOptimize(iterations);\n  }\n  if (state.thread_index() <= (state.threads() / 2))\n    state.SkipWithError(\"error message\");\n}\nBENCHMARK(BM_error_after_running)->ThreadRange(1, 8);\nADD_CASES(\"BM_error_after_running\", {{\"/threads:1\", true, \"error message\"},\n                                     {\"/threads:2\", true, \"error message\"},\n                                     {\"/threads:4\", true, \"error message\"},\n                                     {\"/threads:8\", true, \"error message\"}});\n\nvoid BM_error_while_paused(benchmark::State& state) {\n  bool first_iter = true;\n  while (state.KeepRunning()) {\n    if (state.range(0) == 1 && state.thread_index() <= (state.threads() / 2)) {\n      assert(first_iter);\n      first_iter = false;\n      state.PauseTiming();\n      state.SkipWithError(\"error message\");\n    } else {\n      state.PauseTiming();\n      state.ResumeTiming();\n    }\n  }\n}\nBENCHMARK(BM_error_while_paused)->Arg(1)->Arg(2)->ThreadRange(1, 8);\nADD_CASES(\"BM_error_while_paused\", {{\"/1/threads:1\", true, \"error message\"},\n                                    {\"/1/threads:2\", true, \"error message\"},\n                                    {\"/1/threads:4\", true, \"error message\"},\n                                    {\"/1/threads:8\", true, \"error message\"},\n                                    {\"/2/threads:1\", false, \"\"},\n                                    {\"/2/threads:2\", false, \"\"},\n                                    {\"/2/threads:4\", false, \"\"},\n                                    {\"/2/threads:8\", false, \"\"}});\n\nint main(int argc, char* argv[]) {\n  benchmark::Initialize(&argc, argv);\n\n  TestReporter test_reporter;\n  benchmark::RunSpecifiedBenchmarks(&test_reporter);\n\n  typedef benchmark::BenchmarkReporter::Run Run;\n  auto EB = ExpectedResults.begin();\n\n  for (Run const& run : test_reporter.all_runs_) {\n    assert(EB != ExpectedResults.end());\n    EB->CheckRun(run);\n    ++EB;\n  }\n  assert(EB == ExpectedResults.end());\n\n  return 0;\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/spec_arg_test.cc",
    "content": "#include <algorithm>\n#include <cassert>\n#include <cstdint>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <limits>\n#include <string>\n#include <vector>\n\n#include \"benchmark/benchmark.h\"\n\n// Tests that we can override benchmark-spec value from FLAGS_benchmark_filter\n// with argument to RunSpecifiedBenchmarks(...).\n\nnamespace {\n\nclass TestReporter : public benchmark::ConsoleReporter {\n public:\n  bool ReportContext(const Context& context) override {\n    return ConsoleReporter::ReportContext(context);\n  };\n\n  void ReportRuns(const std::vector<Run>& report) override {\n    assert(report.size() == 1);\n    matched_functions.push_back(report[0].run_name.function_name);\n    ConsoleReporter::ReportRuns(report);\n  };\n\n  TestReporter() {}\n\n  ~TestReporter() override {}\n\n  const std::vector<std::string>& GetMatchedFunctions() const {\n    return matched_functions;\n  }\n\n private:\n  std::vector<std::string> matched_functions;\n};\n\n}  // end namespace\n\nstatic void BM_NotChosen(benchmark::State& state) {\n  assert(false && \"SHOULD NOT BE CALLED\");\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_NotChosen);\n\nstatic void BM_Chosen(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_Chosen);\n\nint main(int argc, char** argv) {\n  const std::string flag = \"BM_NotChosen\";\n\n  // Verify that argv specify --benchmark_filter=BM_NotChosen.\n  bool found = false;\n  for (int i = 0; i < argc; ++i) {\n    if (strcmp(\"--benchmark_filter=BM_NotChosen\", argv[i]) == 0) {\n      found = true;\n      break;\n    }\n  }\n  assert(found);\n\n  benchmark::Initialize(&argc, argv);\n\n  // Check that the current flag value is reported accurately via the\n  // GetBenchmarkFilter() function.\n  if (flag != benchmark::GetBenchmarkFilter()) {\n    std::cerr\n        << \"Seeing different value for flags. GetBenchmarkFilter() returns [\"\n        << benchmark::GetBenchmarkFilter() << \"] expected flag=[\" << flag\n        << \"]\\n\";\n    return 1;\n  }\n  TestReporter test_reporter;\n  const char* const spec = \"BM_Chosen\";\n  const size_t returned_count =\n      benchmark::RunSpecifiedBenchmarks(&test_reporter, spec);\n  assert(returned_count == 1);\n  const std::vector<std::string> matched_functions =\n      test_reporter.GetMatchedFunctions();\n  assert(matched_functions.size() == 1);\n  if (strcmp(spec, matched_functions.front().c_str()) != 0) {\n    std::cerr << \"Expected benchmark [\" << spec << \"] to run, but got [\"\n              << matched_functions.front() << \"]\\n\";\n    return 2;\n  }\n\n  // Test that SetBenchmarkFilter works.\n  const std::string golden_value = \"golden_value\";\n  benchmark::SetBenchmarkFilter(golden_value);\n  std::string current_value = benchmark::GetBenchmarkFilter();\n  if (golden_value != current_value) {\n    std::cerr << \"Expected [\" << golden_value\n              << \"] for --benchmark_filter but got [\" << current_value << \"]\\n\";\n    return 3;\n  }\n  return 0;\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/spec_arg_verbosity_test.cc",
    "content": "#include <string.h>\n\n#include <iostream>\n\n#include \"benchmark/benchmark.h\"\n\n// Tests that the user specified verbosity level can be get.\nstatic void BM_Verbosity(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n}\nBENCHMARK(BM_Verbosity);\n\nint main(int argc, char** argv) {\n  const int32_t flagv = 42;\n\n  // Verify that argv specify --v=42.\n  bool found = false;\n  for (int i = 0; i < argc; ++i) {\n    if (strcmp(\"--v=42\", argv[i]) == 0) {\n      found = true;\n      break;\n    }\n  }\n  if (!found) {\n    std::cerr << \"This test requires '--v=42' to be passed as a command-line \"\n              << \"argument.\\n\";\n    return 1;\n  }\n\n  benchmark::Initialize(&argc, argv);\n\n  // Check that the current flag value is reported accurately via the\n  // GetBenchmarkVerbosity() function.\n  if (flagv != benchmark::GetBenchmarkVerbosity()) {\n    std::cerr\n        << \"Seeing different value for flags. GetBenchmarkVerbosity() returns [\"\n        << benchmark::GetBenchmarkVerbosity() << \"] expected flag=[\" << flagv\n        << \"]\\n\";\n    return 1;\n  }\n  return 0;\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/state_assembly_test.cc",
    "content": "#include <benchmark/benchmark.h>\n\n#ifdef __clang__\n#pragma clang diagnostic ignored \"-Wreturn-type\"\n#endif\n\n// clang-format off\nextern \"C\" {\n  extern int ExternInt;\n  benchmark::State& GetState();\n  void Fn();\n}\n// clang-format on\n\nusing benchmark::State;\n\n// CHECK-LABEL: test_for_auto_loop:\nextern \"C\" int test_for_auto_loop() {\n  State& S = GetState();\n  int x = 42;\n  // CHECK: \t[[CALL:call(q)*]]\t_ZN9benchmark5State16StartKeepRunningEv\n  // CHECK-NEXT: testq %rbx, %rbx\n  // CHECK-NEXT: je [[LOOP_END:.*]]\n\n  for (auto _ : S) {\n    // CHECK: .L[[LOOP_HEAD:[a-zA-Z0-9_]+]]:\n    // CHECK-GNU-NEXT: subq $1, %rbx\n    // CHECK-CLANG-NEXT: {{(addq \\$1, %rax|incq %rax|addq \\$-1, %rbx)}}\n    // CHECK-NEXT: jne .L[[LOOP_HEAD]]\n    benchmark::DoNotOptimize(x);\n  }\n  // CHECK: [[LOOP_END]]:\n  // CHECK: [[CALL]]\t_ZN9benchmark5State17FinishKeepRunningEv\n\n  // CHECK: movl $101, %eax\n  // CHECK: ret\n  return 101;\n}\n\n// CHECK-LABEL: test_while_loop:\nextern \"C\" int test_while_loop() {\n  State& S = GetState();\n  int x = 42;\n\n  // CHECK: j{{(e|mp)}} .L[[LOOP_HEADER:[a-zA-Z0-9_]+]]\n  // CHECK-NEXT: .L[[LOOP_BODY:[a-zA-Z0-9_]+]]:\n  while (S.KeepRunning()) {\n    // CHECK-GNU-NEXT: subq $1, %[[IREG:[a-z]+]]\n    // CHECK-CLANG-NEXT: {{(addq \\$-1,|decq)}} %[[IREG:[a-z]+]]\n    // CHECK: movq %[[IREG]], [[DEST:.*]]\n    benchmark::DoNotOptimize(x);\n  }\n  // CHECK-DAG: movq [[DEST]], %[[IREG]]\n  // CHECK-DAG: testq %[[IREG]], %[[IREG]]\n  // CHECK-DAG: jne .L[[LOOP_BODY]]\n  // CHECK-DAG: .L[[LOOP_HEADER]]:\n\n  // CHECK: cmpb $0\n  // CHECK-NEXT: jne .L[[LOOP_END:[a-zA-Z0-9_]+]]\n  // CHECK: [[CALL:call(q)*]] _ZN9benchmark5State16StartKeepRunningEv\n\n  // CHECK: .L[[LOOP_END]]:\n  // CHECK: [[CALL]] _ZN9benchmark5State17FinishKeepRunningEv\n\n  // CHECK: movl $101, %eax\n  // CHECK: ret\n  return 101;\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/statistics_gtest.cc",
    "content": "//===---------------------------------------------------------------------===//\n// statistics_test - Unit tests for src/statistics.cc\n//===---------------------------------------------------------------------===//\n\n#include \"../src/statistics.h\"\n#include \"gtest/gtest.h\"\n\nnamespace {\nTEST(StatisticsTest, Mean) {\n  EXPECT_DOUBLE_EQ(benchmark::StatisticsMean({42, 42, 42, 42}), 42.0);\n  EXPECT_DOUBLE_EQ(benchmark::StatisticsMean({1, 2, 3, 4}), 2.5);\n  EXPECT_DOUBLE_EQ(benchmark::StatisticsMean({1, 2, 5, 10, 10, 14}), 7.0);\n}\n\nTEST(StatisticsTest, Median) {\n  EXPECT_DOUBLE_EQ(benchmark::StatisticsMedian({42, 42, 42, 42}), 42.0);\n  EXPECT_DOUBLE_EQ(benchmark::StatisticsMedian({1, 2, 3, 4}), 2.5);\n  EXPECT_DOUBLE_EQ(benchmark::StatisticsMedian({1, 2, 5, 10, 10}), 5.0);\n}\n\nTEST(StatisticsTest, StdDev) {\n  EXPECT_DOUBLE_EQ(benchmark::StatisticsStdDev({101, 101, 101, 101}), 0.0);\n  EXPECT_DOUBLE_EQ(benchmark::StatisticsStdDev({1, 2, 3}), 1.0);\n  EXPECT_DOUBLE_EQ(benchmark::StatisticsStdDev({2.5, 2.4, 3.3, 4.2, 5.1}),\n                   1.151086443322134);\n}\n\nTEST(StatisticsTest, CV) {\n  EXPECT_DOUBLE_EQ(benchmark::StatisticsCV({101, 101, 101, 101}), 0.0);\n  EXPECT_DOUBLE_EQ(benchmark::StatisticsCV({1, 2, 3}), 1. / 2.);\n  EXPECT_DOUBLE_EQ(benchmark::StatisticsCV({2.5, 2.4, 3.3, 4.2, 5.1}),\n                   0.32888184094918121);\n}\n\n}  // end namespace\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/string_util_gtest.cc",
    "content": "//===---------------------------------------------------------------------===//\n// statistics_test - Unit tests for src/statistics.cc\n//===---------------------------------------------------------------------===//\n\n#include <tuple>\n\n#include \"../src/internal_macros.h\"\n#include \"../src/string_util.h\"\n#include \"gtest/gtest.h\"\n\nnamespace {\nTEST(StringUtilTest, stoul) {\n  {\n    size_t pos = 0;\n    EXPECT_EQ(0ul, benchmark::stoul(\"0\", &pos));\n    EXPECT_EQ(1ul, pos);\n  }\n  {\n    size_t pos = 0;\n    EXPECT_EQ(7ul, benchmark::stoul(\"7\", &pos));\n    EXPECT_EQ(1ul, pos);\n  }\n  {\n    size_t pos = 0;\n    EXPECT_EQ(135ul, benchmark::stoul(\"135\", &pos));\n    EXPECT_EQ(3ul, pos);\n  }\n#if ULONG_MAX == 0xFFFFFFFFul\n  {\n    size_t pos = 0;\n    EXPECT_EQ(0xFFFFFFFFul, benchmark::stoul(\"4294967295\", &pos));\n    EXPECT_EQ(10ul, pos);\n  }\n#elif ULONG_MAX == 0xFFFFFFFFFFFFFFFFul\n  {\n    size_t pos = 0;\n    EXPECT_EQ(0xFFFFFFFFFFFFFFFFul,\n              benchmark::stoul(\"18446744073709551615\", &pos));\n    EXPECT_EQ(20ul, pos);\n  }\n#endif\n  {\n    size_t pos = 0;\n    EXPECT_EQ(10ul, benchmark::stoul(\"1010\", &pos, 2));\n    EXPECT_EQ(4ul, pos);\n  }\n  {\n    size_t pos = 0;\n    EXPECT_EQ(520ul, benchmark::stoul(\"1010\", &pos, 8));\n    EXPECT_EQ(4ul, pos);\n  }\n  {\n    size_t pos = 0;\n    EXPECT_EQ(1010ul, benchmark::stoul(\"1010\", &pos, 10));\n    EXPECT_EQ(4ul, pos);\n  }\n  {\n    size_t pos = 0;\n    EXPECT_EQ(4112ul, benchmark::stoul(\"1010\", &pos, 16));\n    EXPECT_EQ(4ul, pos);\n  }\n  {\n    size_t pos = 0;\n    EXPECT_EQ(0xBEEFul, benchmark::stoul(\"BEEF\", &pos, 16));\n    EXPECT_EQ(4ul, pos);\n  }\n#ifndef BENCHMARK_HAS_NO_EXCEPTIONS\n  {\n    ASSERT_THROW(std::ignore = benchmark::stoul(\"this is a test\"),\n                 std::invalid_argument);\n  }\n#endif\n}\n\nTEST(StringUtilTest, stoi){{size_t pos = 0;\nEXPECT_EQ(0, benchmark::stoi(\"0\", &pos));\nEXPECT_EQ(1ul, pos);\n}  // namespace\n{\n  size_t pos = 0;\n  EXPECT_EQ(-17, benchmark::stoi(\"-17\", &pos));\n  EXPECT_EQ(3ul, pos);\n}\n{\n  size_t pos = 0;\n  EXPECT_EQ(1357, benchmark::stoi(\"1357\", &pos));\n  EXPECT_EQ(4ul, pos);\n}\n{\n  size_t pos = 0;\n  EXPECT_EQ(10, benchmark::stoi(\"1010\", &pos, 2));\n  EXPECT_EQ(4ul, pos);\n}\n{\n  size_t pos = 0;\n  EXPECT_EQ(520, benchmark::stoi(\"1010\", &pos, 8));\n  EXPECT_EQ(4ul, pos);\n}\n{\n  size_t pos = 0;\n  EXPECT_EQ(1010, benchmark::stoi(\"1010\", &pos, 10));\n  EXPECT_EQ(4ul, pos);\n}\n{\n  size_t pos = 0;\n  EXPECT_EQ(4112, benchmark::stoi(\"1010\", &pos, 16));\n  EXPECT_EQ(4ul, pos);\n}\n{\n  size_t pos = 0;\n  EXPECT_EQ(0xBEEF, benchmark::stoi(\"BEEF\", &pos, 16));\n  EXPECT_EQ(4ul, pos);\n}\n#ifndef BENCHMARK_HAS_NO_EXCEPTIONS\n{\n  ASSERT_THROW(std::ignore = benchmark::stoi(\"this is a test\"),\n               std::invalid_argument);\n}\n#endif\n}\n\nTEST(StringUtilTest, stod){{size_t pos = 0;\nEXPECT_EQ(0.0, benchmark::stod(\"0\", &pos));\nEXPECT_EQ(1ul, pos);\n}\n{\n  size_t pos = 0;\n  EXPECT_EQ(-84.0, benchmark::stod(\"-84\", &pos));\n  EXPECT_EQ(3ul, pos);\n}\n{\n  size_t pos = 0;\n  EXPECT_EQ(1234.0, benchmark::stod(\"1234\", &pos));\n  EXPECT_EQ(4ul, pos);\n}\n{\n  size_t pos = 0;\n  EXPECT_EQ(1.5, benchmark::stod(\"1.5\", &pos));\n  EXPECT_EQ(3ul, pos);\n}\n{\n  size_t pos = 0;\n  /* Note: exactly representable as double */\n  EXPECT_EQ(-1.25e+9, benchmark::stod(\"-1.25e+9\", &pos));\n  EXPECT_EQ(8ul, pos);\n}\n#ifndef BENCHMARK_HAS_NO_EXCEPTIONS\n{\n  ASSERT_THROW(std::ignore = benchmark::stod(\"this is a test\"),\n               std::invalid_argument);\n}\n#endif\n}\n\nTEST(StringUtilTest, StrSplit) {\n  EXPECT_EQ(benchmark::StrSplit(\"\", ','), std::vector<std::string>{});\n  EXPECT_EQ(benchmark::StrSplit(\"hello\", ','),\n            std::vector<std::string>({\"hello\"}));\n  EXPECT_EQ(benchmark::StrSplit(\"hello,there,is,more\", ','),\n            std::vector<std::string>({\"hello\", \"there\", \"is\", \"more\"}));\n}\n\n}  // end namespace\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/templated_fixture_test.cc",
    "content": "\n#include <cassert>\n#include <memory>\n\n#include \"benchmark/benchmark.h\"\n\ntemplate <typename T>\nclass MyFixture : public ::benchmark::Fixture {\n public:\n  MyFixture() : data(0) {}\n\n  T data;\n};\n\nBENCHMARK_TEMPLATE_F(MyFixture, Foo, int)(benchmark::State& st) {\n  for (auto _ : st) {\n    data += 1;\n  }\n}\n\nBENCHMARK_TEMPLATE_DEFINE_F(MyFixture, Bar, double)(benchmark::State& st) {\n  for (auto _ : st) {\n    data += 1.0;\n  }\n}\nBENCHMARK_REGISTER_F(MyFixture, Bar);\n\nBENCHMARK_MAIN();\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/time_unit_gtest.cc",
    "content": "#include \"../include/benchmark/benchmark.h\"\n#include \"gtest/gtest.h\"\n\nnamespace benchmark {\nnamespace internal {\n\nnamespace {\n\nclass DummyBenchmark : public Benchmark {\n public:\n  DummyBenchmark() : Benchmark(\"dummy\") {}\n  void Run(State&) override {}\n};\n\nTEST(DefaultTimeUnitTest, TimeUnitIsNotSet) {\n  DummyBenchmark benchmark;\n  EXPECT_EQ(benchmark.GetTimeUnit(), kNanosecond);\n}\n\nTEST(DefaultTimeUnitTest, DefaultIsSet) {\n  DummyBenchmark benchmark;\n  EXPECT_EQ(benchmark.GetTimeUnit(), kNanosecond);\n  SetDefaultTimeUnit(kMillisecond);\n  EXPECT_EQ(benchmark.GetTimeUnit(), kMillisecond);\n}\n\nTEST(DefaultTimeUnitTest, DefaultAndExplicitUnitIsSet) {\n  DummyBenchmark benchmark;\n  benchmark.Unit(kMillisecond);\n  SetDefaultTimeUnit(kMicrosecond);\n\n  EXPECT_EQ(benchmark.GetTimeUnit(), kMillisecond);\n}\n\n}  // namespace\n}  // namespace internal\n}  // namespace benchmark\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/user_counters_tabular_test.cc",
    "content": "\n#undef NDEBUG\n\n#include \"benchmark/benchmark.h\"\n#include \"output_test.h\"\n\n// @todo: <jpmag> this checks the full output at once; the rule for\n// CounterSet1 was failing because it was not matching \"^[-]+$\".\n// @todo: <jpmag> check that the counters are vertically aligned.\nADD_CASES(TC_ConsoleOut,\n          {\n              // keeping these lines long improves readability, so:\n              // clang-format off\n    {\"^[-]+$\", MR_Next},\n    {\"^Benchmark %s Time %s CPU %s Iterations %s Bar %s Bat %s Baz %s Foo %s Frob %s Lob$\", MR_Next},\n    {\"^[-]+$\", MR_Next},\n      {\"^BM_Counters_Tabular/repeats:2/threads:1 %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$\", MR_Next},\n      {\"^BM_Counters_Tabular/repeats:2/threads:1 %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$\", MR_Next},\n      {\"^BM_Counters_Tabular/repeats:2/threads:1_mean %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$\", MR_Next},\n      {\"^BM_Counters_Tabular/repeats:2/threads:1_median %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$\", MR_Next},\n            {\"^BM_Counters_Tabular/repeats:2/threads:1_stddev %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$\", MR_Next},\n            {\"^BM_Counters_Tabular/repeats:2/threads:1_cv %console_percentage_report [ ]*%percentage[ ]*% [ ]*%percentage[ ]*% [ ]*%percentage[ ]*% [ ]*%percentage[ ]*% [ ]*%percentage[ ]*% [ ]*%percentage[ ]*%$\", MR_Next},\n      {\"^BM_Counters_Tabular/repeats:2/threads:2 %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$\", MR_Next},\n      {\"^BM_Counters_Tabular/repeats:2/threads:2 %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$\", MR_Next},\n      {\"^BM_Counters_Tabular/repeats:2/threads:2_mean %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$\", MR_Next},\n      {\"^BM_Counters_Tabular/repeats:2/threads:2_median %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$\", MR_Next},\n            {\"^BM_Counters_Tabular/repeats:2/threads:2_stddev %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$\", MR_Next},\n            {\"^BM_Counters_Tabular/repeats:2/threads:2_cv %console_percentage_report [ ]*%percentage[ ]*% [ ]*%percentage[ ]*% [ ]*%percentage[ ]*% [ ]*%percentage[ ]*% [ ]*%percentage[ ]*% [ ]*%percentage[ ]*%$\", MR_Next},\n    {\"^BM_CounterRates_Tabular/threads:%int %console_report [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s$\", MR_Next},\n    {\"^BM_CounterRates_Tabular/threads:%int %console_report [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s$\", MR_Next},\n    {\"^BM_CounterRates_Tabular/threads:%int %console_report [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s$\", MR_Next},\n    {\"^BM_CounterRates_Tabular/threads:%int %console_report [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s$\", MR_Next},\n    {\"^BM_CounterRates_Tabular/threads:%int %console_report [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s [ ]*%hrfloat/s$\", MR_Next},\n    {\"^[-]+$\", MR_Next},\n    {\"^Benchmark %s Time %s CPU %s Iterations %s Bar %s Baz %s Foo$\", MR_Next},\n    {\"^[-]+$\", MR_Next},\n    {\"^BM_CounterSet0_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$\", MR_Next},\n    {\"^BM_CounterSet0_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$\", MR_Next},\n    {\"^BM_CounterSet0_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$\", MR_Next},\n    {\"^BM_CounterSet0_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$\", MR_Next},\n    {\"^BM_CounterSet0_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$\", MR_Next},\n    {\"^BM_CounterSet1_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$\", MR_Next},\n    {\"^BM_CounterSet1_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$\", MR_Next},\n    {\"^BM_CounterSet1_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$\", MR_Next},\n    {\"^BM_CounterSet1_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$\", MR_Next},\n    {\"^BM_CounterSet1_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$\", MR_Next},\n    {\"^[-]+$\", MR_Next},\n    {\"^Benchmark %s Time %s CPU %s Iterations %s Bat %s Baz %s Foo$\", MR_Next},\n    {\"^[-]+$\", MR_Next},\n    {\"^BM_CounterSet2_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$\", MR_Next},\n    {\"^BM_CounterSet2_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$\", MR_Next},\n    {\"^BM_CounterSet2_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$\", MR_Next},\n    {\"^BM_CounterSet2_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$\", MR_Next},\n    {\"^BM_CounterSet2_Tabular/threads:%int %console_report [ ]*%hrfloat [ ]*%hrfloat [ ]*%hrfloat$\"},\n              // clang-format on\n          });\nADD_CASES(TC_CSVOut, {{\"%csv_header,\"\n                       \"\\\"Bar\\\",\\\"Bat\\\",\\\"Baz\\\",\\\"Foo\\\",\\\"Frob\\\",\\\"Lob\\\"\"}});\n\n// ========================================================================= //\n// ------------------------- Tabular Counters Output ----------------------- //\n// ========================================================================= //\n\nvoid BM_Counters_Tabular(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n  namespace bm = benchmark;\n  state.counters.insert({\n      {\"Foo\", {1, bm::Counter::kAvgThreads}},\n      {\"Bar\", {2, bm::Counter::kAvgThreads}},\n      {\"Baz\", {4, bm::Counter::kAvgThreads}},\n      {\"Bat\", {8, bm::Counter::kAvgThreads}},\n      {\"Frob\", {16, bm::Counter::kAvgThreads}},\n      {\"Lob\", {32, bm::Counter::kAvgThreads}},\n  });\n}\nBENCHMARK(BM_Counters_Tabular)->ThreadRange(1, 2)->Repetitions(2);\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_Counters_Tabular/repeats:2/threads:1\\\",$\"},\n           {\"\\\"family_index\\\": 0,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_Counters_Tabular/repeats:2/threads:1\\\",$\",\n            MR_Next},\n           {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 2,$\", MR_Next},\n           {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"Bar\\\": %float,$\", MR_Next},\n           {\"\\\"Bat\\\": %float,$\", MR_Next},\n           {\"\\\"Baz\\\": %float,$\", MR_Next},\n           {\"\\\"Foo\\\": %float,$\", MR_Next},\n           {\"\\\"Frob\\\": %float,$\", MR_Next},\n           {\"\\\"Lob\\\": %float$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_Counters_Tabular/repeats:2/threads:1\\\",$\"},\n           {\"\\\"family_index\\\": 0,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_Counters_Tabular/repeats:2/threads:1\\\",$\",\n            MR_Next},\n           {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 2,$\", MR_Next},\n           {\"\\\"repetition_index\\\": 1,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"Bar\\\": %float,$\", MR_Next},\n           {\"\\\"Bat\\\": %float,$\", MR_Next},\n           {\"\\\"Baz\\\": %float,$\", MR_Next},\n           {\"\\\"Foo\\\": %float,$\", MR_Next},\n           {\"\\\"Frob\\\": %float,$\", MR_Next},\n           {\"\\\"Lob\\\": %float$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_Counters_Tabular/repeats:2/threads:1_mean\\\",$\"},\n           {\"\\\"family_index\\\": 0,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_Counters_Tabular/repeats:2/threads:1\\\",$\",\n            MR_Next},\n           {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 2,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"aggregate_name\\\": \\\"mean\\\",$\", MR_Next},\n           {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"Bar\\\": %float,$\", MR_Next},\n           {\"\\\"Bat\\\": %float,$\", MR_Next},\n           {\"\\\"Baz\\\": %float,$\", MR_Next},\n           {\"\\\"Foo\\\": %float,$\", MR_Next},\n           {\"\\\"Frob\\\": %float,$\", MR_Next},\n           {\"\\\"Lob\\\": %float$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_Counters_Tabular/repeats:2/threads:1_median\\\",$\"},\n           {\"\\\"family_index\\\": 0,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_Counters_Tabular/repeats:2/threads:1\\\",$\",\n            MR_Next},\n           {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 2,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"aggregate_name\\\": \\\"median\\\",$\", MR_Next},\n           {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"Bar\\\": %float,$\", MR_Next},\n           {\"\\\"Bat\\\": %float,$\", MR_Next},\n           {\"\\\"Baz\\\": %float,$\", MR_Next},\n           {\"\\\"Foo\\\": %float,$\", MR_Next},\n           {\"\\\"Frob\\\": %float,$\", MR_Next},\n           {\"\\\"Lob\\\": %float$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_Counters_Tabular/repeats:2/threads:1_stddev\\\",$\"},\n           {\"\\\"family_index\\\": 0,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_Counters_Tabular/repeats:2/threads:1\\\",$\",\n            MR_Next},\n           {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 2,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"aggregate_name\\\": \\\"stddev\\\",$\", MR_Next},\n           {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"Bar\\\": %float,$\", MR_Next},\n           {\"\\\"Bat\\\": %float,$\", MR_Next},\n           {\"\\\"Baz\\\": %float,$\", MR_Next},\n           {\"\\\"Foo\\\": %float,$\", MR_Next},\n           {\"\\\"Frob\\\": %float,$\", MR_Next},\n           {\"\\\"Lob\\\": %float$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_Counters_Tabular/repeats:2/threads:1_cv\\\",$\"},\n           {\"\\\"family_index\\\": 0,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_Counters_Tabular/repeats:2/threads:1\\\",$\",\n            MR_Next},\n           {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 2,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"aggregate_name\\\": \\\"cv\\\",$\", MR_Next},\n           {\"\\\"aggregate_unit\\\": \\\"percentage\\\",$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"Bar\\\": %float,$\", MR_Next},\n           {\"\\\"Bat\\\": %float,$\", MR_Next},\n           {\"\\\"Baz\\\": %float,$\", MR_Next},\n           {\"\\\"Foo\\\": %float,$\", MR_Next},\n           {\"\\\"Frob\\\": %float,$\", MR_Next},\n           {\"\\\"Lob\\\": %float$\", MR_Next},\n           {\"}\", MR_Next}});\n\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_Counters_Tabular/repeats:2/threads:2\\\",$\"},\n           {\"\\\"family_index\\\": 0,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 1,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_Counters_Tabular/repeats:2/threads:2\\\",$\",\n            MR_Next},\n           {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 2,$\", MR_Next},\n           {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n           {\"\\\"threads\\\": 2,$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"Bar\\\": %float,$\", MR_Next},\n           {\"\\\"Bat\\\": %float,$\", MR_Next},\n           {\"\\\"Baz\\\": %float,$\", MR_Next},\n           {\"\\\"Foo\\\": %float,$\", MR_Next},\n           {\"\\\"Frob\\\": %float,$\", MR_Next},\n           {\"\\\"Lob\\\": %float$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_Counters_Tabular/repeats:2/threads:2\\\",$\"},\n           {\"\\\"family_index\\\": 0,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 1,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_Counters_Tabular/repeats:2/threads:2\\\",$\",\n            MR_Next},\n           {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 2,$\", MR_Next},\n           {\"\\\"repetition_index\\\": 1,$\", MR_Next},\n           {\"\\\"threads\\\": 2,$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"Bar\\\": %float,$\", MR_Next},\n           {\"\\\"Bat\\\": %float,$\", MR_Next},\n           {\"\\\"Baz\\\": %float,$\", MR_Next},\n           {\"\\\"Foo\\\": %float,$\", MR_Next},\n           {\"\\\"Frob\\\": %float,$\", MR_Next},\n           {\"\\\"Lob\\\": %float$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_Counters_Tabular/repeats:2/threads:2_median\\\",$\"},\n           {\"\\\"family_index\\\": 0,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 1,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_Counters_Tabular/repeats:2/threads:2\\\",$\",\n            MR_Next},\n           {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 2,$\", MR_Next},\n           {\"\\\"threads\\\": 2,$\", MR_Next},\n           {\"\\\"aggregate_name\\\": \\\"median\\\",$\", MR_Next},\n           {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"Bar\\\": %float,$\", MR_Next},\n           {\"\\\"Bat\\\": %float,$\", MR_Next},\n           {\"\\\"Baz\\\": %float,$\", MR_Next},\n           {\"\\\"Foo\\\": %float,$\", MR_Next},\n           {\"\\\"Frob\\\": %float,$\", MR_Next},\n           {\"\\\"Lob\\\": %float$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_Counters_Tabular/repeats:2/threads:2_stddev\\\",$\"},\n           {\"\\\"family_index\\\": 0,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 1,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_Counters_Tabular/repeats:2/threads:2\\\",$\",\n            MR_Next},\n           {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 2,$\", MR_Next},\n           {\"\\\"threads\\\": 2,$\", MR_Next},\n           {\"\\\"aggregate_name\\\": \\\"stddev\\\",$\", MR_Next},\n           {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"Bar\\\": %float,$\", MR_Next},\n           {\"\\\"Bat\\\": %float,$\", MR_Next},\n           {\"\\\"Baz\\\": %float,$\", MR_Next},\n           {\"\\\"Foo\\\": %float,$\", MR_Next},\n           {\"\\\"Frob\\\": %float,$\", MR_Next},\n           {\"\\\"Lob\\\": %float$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_Counters_Tabular/repeats:2/threads:2_cv\\\",$\"},\n           {\"\\\"family_index\\\": 0,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 1,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_Counters_Tabular/repeats:2/threads:2\\\",$\",\n            MR_Next},\n           {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 2,$\", MR_Next},\n           {\"\\\"threads\\\": 2,$\", MR_Next},\n           {\"\\\"aggregate_name\\\": \\\"cv\\\",$\", MR_Next},\n           {\"\\\"aggregate_unit\\\": \\\"percentage\\\",$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"Bar\\\": %float,$\", MR_Next},\n           {\"\\\"Bat\\\": %float,$\", MR_Next},\n           {\"\\\"Baz\\\": %float,$\", MR_Next},\n           {\"\\\"Foo\\\": %float,$\", MR_Next},\n           {\"\\\"Frob\\\": %float,$\", MR_Next},\n           {\"\\\"Lob\\\": %float$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut,\n          {{\"^\\\"BM_Counters_Tabular/repeats:2/threads:1\\\",%csv_report,\"\n            \"%float,%float,%float,%float,%float,%float$\"}});\nADD_CASES(TC_CSVOut,\n          {{\"^\\\"BM_Counters_Tabular/repeats:2/threads:1\\\",%csv_report,\"\n            \"%float,%float,%float,%float,%float,%float$\"}});\nADD_CASES(TC_CSVOut,\n          {{\"^\\\"BM_Counters_Tabular/repeats:2/threads:1_mean\\\",%csv_report,\"\n            \"%float,%float,%float,%float,%float,%float$\"}});\nADD_CASES(TC_CSVOut,\n          {{\"^\\\"BM_Counters_Tabular/repeats:2/threads:1_median\\\",%csv_report,\"\n            \"%float,%float,%float,%float,%float,%float$\"}});\nADD_CASES(TC_CSVOut,\n          {{\"^\\\"BM_Counters_Tabular/repeats:2/threads:1_stddev\\\",%csv_report,\"\n            \"%float,%float,%float,%float,%float,%float$\"}});\nADD_CASES(TC_CSVOut,\n          {{\"^\\\"BM_Counters_Tabular/repeats:2/threads:1_cv\\\",%csv_report,\"\n            \"%float,%float,%float,%float,%float,%float$\"}});\nADD_CASES(TC_CSVOut,\n          {{\"^\\\"BM_Counters_Tabular/repeats:2/threads:2\\\",%csv_report,\"\n            \"%float,%float,%float,%float,%float,%float$\"}});\nADD_CASES(TC_CSVOut,\n          {{\"^\\\"BM_Counters_Tabular/repeats:2/threads:2\\\",%csv_report,\"\n            \"%float,%float,%float,%float,%float,%float$\"}});\nADD_CASES(TC_CSVOut,\n          {{\"^\\\"BM_Counters_Tabular/repeats:2/threads:2_mean\\\",%csv_report,\"\n            \"%float,%float,%float,%float,%float,%float$\"}});\nADD_CASES(TC_CSVOut,\n          {{\"^\\\"BM_Counters_Tabular/repeats:2/threads:2_median\\\",%csv_report,\"\n            \"%float,%float,%float,%float,%float,%float$\"}});\nADD_CASES(TC_CSVOut,\n          {{\"^\\\"BM_Counters_Tabular/repeats:2/threads:2_stddev\\\",%csv_report,\"\n            \"%float,%float,%float,%float,%float,%float$\"}});\nADD_CASES(TC_CSVOut,\n          {{\"^\\\"BM_Counters_Tabular/repeats:2/threads:2_cv\\\",%csv_report,\"\n            \"%float,%float,%float,%float,%float,%float$\"}});\n// VS2013 does not allow this function to be passed as a lambda argument\n// to CHECK_BENCHMARK_RESULTS()\nvoid CheckTabular(Results const& e) {\n  CHECK_COUNTER_VALUE(e, int, \"Foo\", EQ, 1);\n  CHECK_COUNTER_VALUE(e, int, \"Bar\", EQ, 2);\n  CHECK_COUNTER_VALUE(e, int, \"Baz\", EQ, 4);\n  CHECK_COUNTER_VALUE(e, int, \"Bat\", EQ, 8);\n  CHECK_COUNTER_VALUE(e, int, \"Frob\", EQ, 16);\n  CHECK_COUNTER_VALUE(e, int, \"Lob\", EQ, 32);\n}\nCHECK_BENCHMARK_RESULTS(\"BM_Counters_Tabular/repeats:2/threads:1$\",\n                        &CheckTabular);\nCHECK_BENCHMARK_RESULTS(\"BM_Counters_Tabular/repeats:2/threads:2$\",\n                        &CheckTabular);\n\n// ========================================================================= //\n// -------------------- Tabular+Rate Counters Output ----------------------- //\n// ========================================================================= //\n\nvoid BM_CounterRates_Tabular(benchmark::State& state) {\n  for (auto _ : state) {\n    // This test requires a non-zero CPU time to avoid divide-by-zero\n    auto iterations = state.iterations();\n    benchmark::DoNotOptimize(iterations);\n  }\n  namespace bm = benchmark;\n  state.counters.insert({\n      {\"Foo\", {1, bm::Counter::kAvgThreadsRate}},\n      {\"Bar\", {2, bm::Counter::kAvgThreadsRate}},\n      {\"Baz\", {4, bm::Counter::kAvgThreadsRate}},\n      {\"Bat\", {8, bm::Counter::kAvgThreadsRate}},\n      {\"Frob\", {16, bm::Counter::kAvgThreadsRate}},\n      {\"Lob\", {32, bm::Counter::kAvgThreadsRate}},\n  });\n}\nBENCHMARK(BM_CounterRates_Tabular)->ThreadRange(1, 16);\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_CounterRates_Tabular/threads:%int\\\",$\"},\n           {\"\\\"family_index\\\": 1,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_CounterRates_Tabular/threads:%int\\\",$\",\n            MR_Next},\n           {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 1,$\", MR_Next},\n           {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"Bar\\\": %float,$\", MR_Next},\n           {\"\\\"Bat\\\": %float,$\", MR_Next},\n           {\"\\\"Baz\\\": %float,$\", MR_Next},\n           {\"\\\"Foo\\\": %float,$\", MR_Next},\n           {\"\\\"Frob\\\": %float,$\", MR_Next},\n           {\"\\\"Lob\\\": %float$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_CounterRates_Tabular/threads:%int\\\",%csv_report,\"\n                       \"%float,%float,%float,%float,%float,%float$\"}});\n// VS2013 does not allow this function to be passed as a lambda argument\n// to CHECK_BENCHMARK_RESULTS()\nvoid CheckTabularRate(Results const& e) {\n  double t = e.DurationCPUTime();\n  CHECK_FLOAT_COUNTER_VALUE(e, \"Foo\", EQ, 1. / t, 0.001);\n  CHECK_FLOAT_COUNTER_VALUE(e, \"Bar\", EQ, 2. / t, 0.001);\n  CHECK_FLOAT_COUNTER_VALUE(e, \"Baz\", EQ, 4. / t, 0.001);\n  CHECK_FLOAT_COUNTER_VALUE(e, \"Bat\", EQ, 8. / t, 0.001);\n  CHECK_FLOAT_COUNTER_VALUE(e, \"Frob\", EQ, 16. / t, 0.001);\n  CHECK_FLOAT_COUNTER_VALUE(e, \"Lob\", EQ, 32. / t, 0.001);\n}\nCHECK_BENCHMARK_RESULTS(\"BM_CounterRates_Tabular/threads:%int\",\n                        &CheckTabularRate);\n\n// ========================================================================= //\n// ------------------------- Tabular Counters Output ----------------------- //\n// ========================================================================= //\n\n// set only some of the counters\nvoid BM_CounterSet0_Tabular(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n  namespace bm = benchmark;\n  state.counters.insert({\n      {\"Foo\", {10, bm::Counter::kAvgThreads}},\n      {\"Bar\", {20, bm::Counter::kAvgThreads}},\n      {\"Baz\", {40, bm::Counter::kAvgThreads}},\n  });\n}\nBENCHMARK(BM_CounterSet0_Tabular)->ThreadRange(1, 16);\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_CounterSet0_Tabular/threads:%int\\\",$\"},\n           {\"\\\"family_index\\\": 2,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_CounterSet0_Tabular/threads:%int\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 1,$\", MR_Next},\n           {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"Bar\\\": %float,$\", MR_Next},\n           {\"\\\"Baz\\\": %float,$\", MR_Next},\n           {\"\\\"Foo\\\": %float$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_CounterSet0_Tabular/threads:%int\\\",%csv_report,\"\n                       \"%float,,%float,%float,,\"}});\n// VS2013 does not allow this function to be passed as a lambda argument\n// to CHECK_BENCHMARK_RESULTS()\nvoid CheckSet0(Results const& e) {\n  CHECK_COUNTER_VALUE(e, int, \"Foo\", EQ, 10);\n  CHECK_COUNTER_VALUE(e, int, \"Bar\", EQ, 20);\n  CHECK_COUNTER_VALUE(e, int, \"Baz\", EQ, 40);\n}\nCHECK_BENCHMARK_RESULTS(\"BM_CounterSet0_Tabular\", &CheckSet0);\n\n// again.\nvoid BM_CounterSet1_Tabular(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n  namespace bm = benchmark;\n  state.counters.insert({\n      {\"Foo\", {15, bm::Counter::kAvgThreads}},\n      {\"Bar\", {25, bm::Counter::kAvgThreads}},\n      {\"Baz\", {45, bm::Counter::kAvgThreads}},\n  });\n}\nBENCHMARK(BM_CounterSet1_Tabular)->ThreadRange(1, 16);\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_CounterSet1_Tabular/threads:%int\\\",$\"},\n           {\"\\\"family_index\\\": 3,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_CounterSet1_Tabular/threads:%int\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 1,$\", MR_Next},\n           {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"Bar\\\": %float,$\", MR_Next},\n           {\"\\\"Baz\\\": %float,$\", MR_Next},\n           {\"\\\"Foo\\\": %float$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_CounterSet1_Tabular/threads:%int\\\",%csv_report,\"\n                       \"%float,,%float,%float,,\"}});\n// VS2013 does not allow this function to be passed as a lambda argument\n// to CHECK_BENCHMARK_RESULTS()\nvoid CheckSet1(Results const& e) {\n  CHECK_COUNTER_VALUE(e, int, \"Foo\", EQ, 15);\n  CHECK_COUNTER_VALUE(e, int, \"Bar\", EQ, 25);\n  CHECK_COUNTER_VALUE(e, int, \"Baz\", EQ, 45);\n}\nCHECK_BENCHMARK_RESULTS(\"BM_CounterSet1_Tabular/threads:%int\", &CheckSet1);\n\n// ========================================================================= //\n// ------------------------- Tabular Counters Output ----------------------- //\n// ========================================================================= //\n\n// set only some of the counters, different set now.\nvoid BM_CounterSet2_Tabular(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n  namespace bm = benchmark;\n  state.counters.insert({\n      {\"Foo\", {10, bm::Counter::kAvgThreads}},\n      {\"Bat\", {30, bm::Counter::kAvgThreads}},\n      {\"Baz\", {40, bm::Counter::kAvgThreads}},\n  });\n}\nBENCHMARK(BM_CounterSet2_Tabular)->ThreadRange(1, 16);\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_CounterSet2_Tabular/threads:%int\\\",$\"},\n           {\"\\\"family_index\\\": 4,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_CounterSet2_Tabular/threads:%int\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 1,$\", MR_Next},\n           {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"Bat\\\": %float,$\", MR_Next},\n           {\"\\\"Baz\\\": %float,$\", MR_Next},\n           {\"\\\"Foo\\\": %float$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_CounterSet2_Tabular/threads:%int\\\",%csv_report,\"\n                       \",%float,%float,%float,,\"}});\n// VS2013 does not allow this function to be passed as a lambda argument\n// to CHECK_BENCHMARK_RESULTS()\nvoid CheckSet2(Results const& e) {\n  CHECK_COUNTER_VALUE(e, int, \"Foo\", EQ, 10);\n  CHECK_COUNTER_VALUE(e, int, \"Bat\", EQ, 30);\n  CHECK_COUNTER_VALUE(e, int, \"Baz\", EQ, 40);\n}\nCHECK_BENCHMARK_RESULTS(\"BM_CounterSet2_Tabular\", &CheckSet2);\n\n// ========================================================================= //\n// --------------------------- TEST CASES END ------------------------------ //\n// ========================================================================= //\n\nint main(int argc, char* argv[]) { RunOutputTests(argc, argv); }\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/user_counters_test.cc",
    "content": "\n#undef NDEBUG\n\n#include \"benchmark/benchmark.h\"\n#include \"output_test.h\"\n\n// ========================================================================= //\n// ---------------------- Testing Prologue Output -------------------------- //\n// ========================================================================= //\n\n// clang-format off\n\nADD_CASES(TC_ConsoleOut,\n          {{\"^[-]+$\", MR_Next},\n           {\"^Benchmark %s Time %s CPU %s Iterations UserCounters...$\", MR_Next},\n           {\"^[-]+$\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"%csv_header,\\\"bar\\\",\\\"foo\\\"\"}});\n\n// clang-format on\n\n// ========================================================================= //\n// ------------------------- Simple Counters Output ------------------------ //\n// ========================================================================= //\n\nvoid BM_Counters_Simple(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n  state.counters[\"foo\"] = 1;\n  state.counters[\"bar\"] = 2 * static_cast<double>(state.iterations());\n}\nBENCHMARK(BM_Counters_Simple);\nADD_CASES(TC_ConsoleOut,\n          {{\"^BM_Counters_Simple %console_report bar=%hrfloat foo=%hrfloat$\"}});\nADD_CASES(TC_JSONOut, {{\"\\\"name\\\": \\\"BM_Counters_Simple\\\",$\"},\n                       {\"\\\"family_index\\\": 0,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_Counters_Simple\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 1,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"iterations\\\": %int,$\", MR_Next},\n                       {\"\\\"real_time\\\": %float,$\", MR_Next},\n                       {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n                       {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n                       {\"\\\"bar\\\": %float,$\", MR_Next},\n                       {\"\\\"foo\\\": %float$\", MR_Next},\n                       {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_Counters_Simple\\\",%csv_report,%float,%float$\"}});\n// VS2013 does not allow this function to be passed as a lambda argument\n// to CHECK_BENCHMARK_RESULTS()\nvoid CheckSimple(Results const& e) {\n  double its = e.NumIterations();\n  CHECK_COUNTER_VALUE(e, int, \"foo\", EQ, 1);\n  // check that the value of bar is within 0.1% of the expected value\n  CHECK_FLOAT_COUNTER_VALUE(e, \"bar\", EQ, 2. * its, 0.001);\n}\nCHECK_BENCHMARK_RESULTS(\"BM_Counters_Simple\", &CheckSimple);\n\n// ========================================================================= //\n// --------------------- Counters+Items+Bytes/s Output --------------------- //\n// ========================================================================= //\n\nnamespace {\nint num_calls1 = 0;\n}\nvoid BM_Counters_WithBytesAndItemsPSec(benchmark::State& state) {\n  for (auto _ : state) {\n    // This test requires a non-zero CPU time to avoid divide-by-zero\n    auto iterations = state.iterations();\n    benchmark::DoNotOptimize(iterations);\n  }\n  state.counters[\"foo\"] = 1;\n  state.counters[\"bar\"] = ++num_calls1;\n  state.SetBytesProcessed(364);\n  state.SetItemsProcessed(150);\n}\nBENCHMARK(BM_Counters_WithBytesAndItemsPSec);\nADD_CASES(TC_ConsoleOut, {{\"^BM_Counters_WithBytesAndItemsPSec %console_report \"\n                           \"bar=%hrfloat bytes_per_second=%hrfloat/s \"\n                           \"foo=%hrfloat items_per_second=%hrfloat/s$\"}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_Counters_WithBytesAndItemsPSec\\\",$\"},\n           {\"\\\"family_index\\\": 1,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_Counters_WithBytesAndItemsPSec\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 1,$\", MR_Next},\n           {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"bar\\\": %float,$\", MR_Next},\n           {\"\\\"bytes_per_second\\\": %float,$\", MR_Next},\n           {\"\\\"foo\\\": %float,$\", MR_Next},\n           {\"\\\"items_per_second\\\": %float$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_Counters_WithBytesAndItemsPSec\\\",\"\n                       \"%csv_bytes_items_report,%float,%float$\"}});\n// VS2013 does not allow this function to be passed as a lambda argument\n// to CHECK_BENCHMARK_RESULTS()\nvoid CheckBytesAndItemsPSec(Results const& e) {\n  double t = e.DurationCPUTime();  // this (and not real time) is the time used\n  CHECK_COUNTER_VALUE(e, int, \"foo\", EQ, 1);\n  CHECK_COUNTER_VALUE(e, int, \"bar\", EQ, num_calls1);\n  // check that the values are within 0.1% of the expected values\n  CHECK_FLOAT_RESULT_VALUE(e, \"bytes_per_second\", EQ, 364. / t, 0.001);\n  CHECK_FLOAT_RESULT_VALUE(e, \"items_per_second\", EQ, 150. / t, 0.001);\n}\nCHECK_BENCHMARK_RESULTS(\"BM_Counters_WithBytesAndItemsPSec\",\n                        &CheckBytesAndItemsPSec);\n\n// ========================================================================= //\n// ------------------------- Rate Counters Output -------------------------- //\n// ========================================================================= //\n\nvoid BM_Counters_Rate(benchmark::State& state) {\n  for (auto _ : state) {\n    // This test requires a non-zero CPU time to avoid divide-by-zero\n    auto iterations = state.iterations();\n    benchmark::DoNotOptimize(iterations);\n  }\n  namespace bm = benchmark;\n  state.counters[\"foo\"] = bm::Counter{1, bm::Counter::kIsRate};\n  state.counters[\"bar\"] = bm::Counter{2, bm::Counter::kIsRate};\n}\nBENCHMARK(BM_Counters_Rate);\nADD_CASES(\n    TC_ConsoleOut,\n    {{\"^BM_Counters_Rate %console_report bar=%hrfloat/s foo=%hrfloat/s$\"}});\nADD_CASES(TC_JSONOut, {{\"\\\"name\\\": \\\"BM_Counters_Rate\\\",$\"},\n                       {\"\\\"family_index\\\": 2,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_Counters_Rate\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 1,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"iterations\\\": %int,$\", MR_Next},\n                       {\"\\\"real_time\\\": %float,$\", MR_Next},\n                       {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n                       {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n                       {\"\\\"bar\\\": %float,$\", MR_Next},\n                       {\"\\\"foo\\\": %float$\", MR_Next},\n                       {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_Counters_Rate\\\",%csv_report,%float,%float$\"}});\n// VS2013 does not allow this function to be passed as a lambda argument\n// to CHECK_BENCHMARK_RESULTS()\nvoid CheckRate(Results const& e) {\n  double t = e.DurationCPUTime();  // this (and not real time) is the time used\n  // check that the values are within 0.1% of the expected values\n  CHECK_FLOAT_COUNTER_VALUE(e, \"foo\", EQ, 1. / t, 0.001);\n  CHECK_FLOAT_COUNTER_VALUE(e, \"bar\", EQ, 2. / t, 0.001);\n}\nCHECK_BENCHMARK_RESULTS(\"BM_Counters_Rate\", &CheckRate);\n\n// ========================================================================= //\n// ----------------------- Inverted Counters Output ------------------------ //\n// ========================================================================= //\n\nvoid BM_Invert(benchmark::State& state) {\n  for (auto _ : state) {\n    // This test requires a non-zero CPU time to avoid divide-by-zero\n    auto iterations = state.iterations();\n    benchmark::DoNotOptimize(iterations);\n  }\n  namespace bm = benchmark;\n  state.counters[\"foo\"] = bm::Counter{0.0001, bm::Counter::kInvert};\n  state.counters[\"bar\"] = bm::Counter{10000, bm::Counter::kInvert};\n}\nBENCHMARK(BM_Invert);\nADD_CASES(TC_ConsoleOut,\n          {{\"^BM_Invert %console_report bar=%hrfloatu foo=%hrfloatk$\"}});\nADD_CASES(TC_JSONOut, {{\"\\\"name\\\": \\\"BM_Invert\\\",$\"},\n                       {\"\\\"family_index\\\": 3,$\", MR_Next},\n                       {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n                       {\"\\\"run_name\\\": \\\"BM_Invert\\\",$\", MR_Next},\n                       {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n                       {\"\\\"repetitions\\\": 1,$\", MR_Next},\n                       {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n                       {\"\\\"threads\\\": 1,$\", MR_Next},\n                       {\"\\\"iterations\\\": %int,$\", MR_Next},\n                       {\"\\\"real_time\\\": %float,$\", MR_Next},\n                       {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n                       {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n                       {\"\\\"bar\\\": %float,$\", MR_Next},\n                       {\"\\\"foo\\\": %float$\", MR_Next},\n                       {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_Invert\\\",%csv_report,%float,%float$\"}});\n// VS2013 does not allow this function to be passed as a lambda argument\n// to CHECK_BENCHMARK_RESULTS()\nvoid CheckInvert(Results const& e) {\n  CHECK_FLOAT_COUNTER_VALUE(e, \"foo\", EQ, 10000, 0.0001);\n  CHECK_FLOAT_COUNTER_VALUE(e, \"bar\", EQ, 0.0001, 0.0001);\n}\nCHECK_BENCHMARK_RESULTS(\"BM_Invert\", &CheckInvert);\n\n// ========================================================================= //\n// --------------------- InvertedRate Counters Output ---------------------- //\n// ========================================================================= //\n\nvoid BM_Counters_InvertedRate(benchmark::State& state) {\n  for (auto _ : state) {\n    // This test requires a non-zero CPU time to avoid divide-by-zero\n    auto iterations = state.iterations();\n    benchmark::DoNotOptimize(iterations);\n  }\n  namespace bm = benchmark;\n  state.counters[\"foo\"] =\n      bm::Counter{1, bm::Counter::kIsRate | bm::Counter::kInvert};\n  state.counters[\"bar\"] =\n      bm::Counter{8192, bm::Counter::kIsRate | bm::Counter::kInvert};\n}\nBENCHMARK(BM_Counters_InvertedRate);\nADD_CASES(TC_ConsoleOut, {{\"^BM_Counters_InvertedRate %console_report \"\n                           \"bar=%hrfloats foo=%hrfloats$\"}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_Counters_InvertedRate\\\",$\"},\n           {\"\\\"family_index\\\": 4,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_Counters_InvertedRate\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 1,$\", MR_Next},\n           {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"bar\\\": %float,$\", MR_Next},\n           {\"\\\"foo\\\": %float$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut,\n          {{\"^\\\"BM_Counters_InvertedRate\\\",%csv_report,%float,%float$\"}});\n// VS2013 does not allow this function to be passed as a lambda argument\n// to CHECK_BENCHMARK_RESULTS()\nvoid CheckInvertedRate(Results const& e) {\n  double t = e.DurationCPUTime();  // this (and not real time) is the time used\n  // check that the values are within 0.1% of the expected values\n  CHECK_FLOAT_COUNTER_VALUE(e, \"foo\", EQ, t, 0.001);\n  CHECK_FLOAT_COUNTER_VALUE(e, \"bar\", EQ, t / 8192.0, 0.001);\n}\nCHECK_BENCHMARK_RESULTS(\"BM_Counters_InvertedRate\", &CheckInvertedRate);\n\n// ========================================================================= //\n// ------------------------- Thread Counters Output ------------------------ //\n// ========================================================================= //\n\nvoid BM_Counters_Threads(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n  state.counters[\"foo\"] = 1;\n  state.counters[\"bar\"] = 2;\n}\nBENCHMARK(BM_Counters_Threads)->ThreadRange(1, 8);\nADD_CASES(TC_ConsoleOut, {{\"^BM_Counters_Threads/threads:%int %console_report \"\n                           \"bar=%hrfloat foo=%hrfloat$\"}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_Counters_Threads/threads:%int\\\",$\"},\n           {\"\\\"family_index\\\": 5,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_Counters_Threads/threads:%int\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 1,$\", MR_Next},\n           {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"bar\\\": %float,$\", MR_Next},\n           {\"\\\"foo\\\": %float$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(\n    TC_CSVOut,\n    {{\"^\\\"BM_Counters_Threads/threads:%int\\\",%csv_report,%float,%float$\"}});\n// VS2013 does not allow this function to be passed as a lambda argument\n// to CHECK_BENCHMARK_RESULTS()\nvoid CheckThreads(Results const& e) {\n  CHECK_COUNTER_VALUE(e, int, \"foo\", EQ, e.NumThreads());\n  CHECK_COUNTER_VALUE(e, int, \"bar\", EQ, 2 * e.NumThreads());\n}\nCHECK_BENCHMARK_RESULTS(\"BM_Counters_Threads/threads:%int\", &CheckThreads);\n\n// ========================================================================= //\n// ---------------------- ThreadAvg Counters Output ------------------------ //\n// ========================================================================= //\n\nvoid BM_Counters_AvgThreads(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n  namespace bm = benchmark;\n  state.counters[\"foo\"] = bm::Counter{1, bm::Counter::kAvgThreads};\n  state.counters[\"bar\"] = bm::Counter{2, bm::Counter::kAvgThreads};\n}\nBENCHMARK(BM_Counters_AvgThreads)->ThreadRange(1, 8);\nADD_CASES(TC_ConsoleOut, {{\"^BM_Counters_AvgThreads/threads:%int \"\n                           \"%console_report bar=%hrfloat foo=%hrfloat$\"}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_Counters_AvgThreads/threads:%int\\\",$\"},\n           {\"\\\"family_index\\\": 6,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_Counters_AvgThreads/threads:%int\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 1,$\", MR_Next},\n           {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"bar\\\": %float,$\", MR_Next},\n           {\"\\\"foo\\\": %float$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(\n    TC_CSVOut,\n    {{\"^\\\"BM_Counters_AvgThreads/threads:%int\\\",%csv_report,%float,%float$\"}});\n// VS2013 does not allow this function to be passed as a lambda argument\n// to CHECK_BENCHMARK_RESULTS()\nvoid CheckAvgThreads(Results const& e) {\n  CHECK_COUNTER_VALUE(e, int, \"foo\", EQ, 1);\n  CHECK_COUNTER_VALUE(e, int, \"bar\", EQ, 2);\n}\nCHECK_BENCHMARK_RESULTS(\"BM_Counters_AvgThreads/threads:%int\",\n                        &CheckAvgThreads);\n\n// ========================================================================= //\n// ---------------------- ThreadAvg Counters Output ------------------------ //\n// ========================================================================= //\n\nvoid BM_Counters_AvgThreadsRate(benchmark::State& state) {\n  for (auto _ : state) {\n    // This test requires a non-zero CPU time to avoid divide-by-zero\n    auto iterations = state.iterations();\n    benchmark::DoNotOptimize(iterations);\n  }\n  namespace bm = benchmark;\n  state.counters[\"foo\"] = bm::Counter{1, bm::Counter::kAvgThreadsRate};\n  state.counters[\"bar\"] = bm::Counter{2, bm::Counter::kAvgThreadsRate};\n}\nBENCHMARK(BM_Counters_AvgThreadsRate)->ThreadRange(1, 8);\nADD_CASES(TC_ConsoleOut, {{\"^BM_Counters_AvgThreadsRate/threads:%int \"\n                           \"%console_report bar=%hrfloat/s foo=%hrfloat/s$\"}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_Counters_AvgThreadsRate/threads:%int\\\",$\"},\n           {\"\\\"family_index\\\": 7,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_Counters_AvgThreadsRate/threads:%int\\\",$\",\n            MR_Next},\n           {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 1,$\", MR_Next},\n           {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"bar\\\": %float,$\", MR_Next},\n           {\"\\\"foo\\\": %float$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_Counters_AvgThreadsRate/\"\n                       \"threads:%int\\\",%csv_report,%float,%float$\"}});\n// VS2013 does not allow this function to be passed as a lambda argument\n// to CHECK_BENCHMARK_RESULTS()\nvoid CheckAvgThreadsRate(Results const& e) {\n  CHECK_FLOAT_COUNTER_VALUE(e, \"foo\", EQ, 1. / e.DurationCPUTime(), 0.001);\n  CHECK_FLOAT_COUNTER_VALUE(e, \"bar\", EQ, 2. / e.DurationCPUTime(), 0.001);\n}\nCHECK_BENCHMARK_RESULTS(\"BM_Counters_AvgThreadsRate/threads:%int\",\n                        &CheckAvgThreadsRate);\n\n// ========================================================================= //\n// ------------------- IterationInvariant Counters Output ------------------ //\n// ========================================================================= //\n\nvoid BM_Counters_IterationInvariant(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n  namespace bm = benchmark;\n  state.counters[\"foo\"] = bm::Counter{1, bm::Counter::kIsIterationInvariant};\n  state.counters[\"bar\"] = bm::Counter{2, bm::Counter::kIsIterationInvariant};\n}\nBENCHMARK(BM_Counters_IterationInvariant);\nADD_CASES(TC_ConsoleOut, {{\"^BM_Counters_IterationInvariant %console_report \"\n                           \"bar=%hrfloat foo=%hrfloat$\"}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_Counters_IterationInvariant\\\",$\"},\n           {\"\\\"family_index\\\": 8,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_Counters_IterationInvariant\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 1,$\", MR_Next},\n           {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"bar\\\": %float,$\", MR_Next},\n           {\"\\\"foo\\\": %float$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut,\n          {{\"^\\\"BM_Counters_IterationInvariant\\\",%csv_report,%float,%float$\"}});\n// VS2013 does not allow this function to be passed as a lambda argument\n// to CHECK_BENCHMARK_RESULTS()\nvoid CheckIterationInvariant(Results const& e) {\n  double its = e.NumIterations();\n  // check that the values are within 0.1% of the expected value\n  CHECK_FLOAT_COUNTER_VALUE(e, \"foo\", EQ, its, 0.001);\n  CHECK_FLOAT_COUNTER_VALUE(e, \"bar\", EQ, 2. * its, 0.001);\n}\nCHECK_BENCHMARK_RESULTS(\"BM_Counters_IterationInvariant\",\n                        &CheckIterationInvariant);\n\n// ========================================================================= //\n// ----------------- IterationInvariantRate Counters Output ---------------- //\n// ========================================================================= //\n\nvoid BM_Counters_kIsIterationInvariantRate(benchmark::State& state) {\n  for (auto _ : state) {\n    // This test requires a non-zero CPU time to avoid divide-by-zero\n    auto iterations = state.iterations();\n    benchmark::DoNotOptimize(iterations);\n  }\n  namespace bm = benchmark;\n  state.counters[\"foo\"] =\n      bm::Counter{1, bm::Counter::kIsIterationInvariantRate};\n  state.counters[\"bar\"] =\n      bm::Counter{2, bm::Counter::kIsRate | bm::Counter::kIsIterationInvariant};\n}\nBENCHMARK(BM_Counters_kIsIterationInvariantRate);\nADD_CASES(TC_ConsoleOut, {{\"^BM_Counters_kIsIterationInvariantRate \"\n                           \"%console_report bar=%hrfloat/s foo=%hrfloat/s$\"}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_Counters_kIsIterationInvariantRate\\\",$\"},\n           {\"\\\"family_index\\\": 9,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_Counters_kIsIterationInvariantRate\\\",$\",\n            MR_Next},\n           {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 1,$\", MR_Next},\n           {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"bar\\\": %float,$\", MR_Next},\n           {\"\\\"foo\\\": %float$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_Counters_kIsIterationInvariantRate\\\",%csv_report,\"\n                       \"%float,%float$\"}});\n// VS2013 does not allow this function to be passed as a lambda argument\n// to CHECK_BENCHMARK_RESULTS()\nvoid CheckIsIterationInvariantRate(Results const& e) {\n  double its = e.NumIterations();\n  double t = e.DurationCPUTime();  // this (and not real time) is the time used\n  // check that the values are within 0.1% of the expected values\n  CHECK_FLOAT_COUNTER_VALUE(e, \"foo\", EQ, its * 1. / t, 0.001);\n  CHECK_FLOAT_COUNTER_VALUE(e, \"bar\", EQ, its * 2. / t, 0.001);\n}\nCHECK_BENCHMARK_RESULTS(\"BM_Counters_kIsIterationInvariantRate\",\n                        &CheckIsIterationInvariantRate);\n\n// ========================================================================= //\n// --------------------- AvgIterations Counters Output --------------------- //\n// ========================================================================= //\n\nvoid BM_Counters_AvgIterations(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n  namespace bm = benchmark;\n  state.counters[\"foo\"] = bm::Counter{1, bm::Counter::kAvgIterations};\n  state.counters[\"bar\"] = bm::Counter{2, bm::Counter::kAvgIterations};\n}\nBENCHMARK(BM_Counters_AvgIterations);\nADD_CASES(TC_ConsoleOut, {{\"^BM_Counters_AvgIterations %console_report \"\n                           \"bar=%hrfloat foo=%hrfloat$\"}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_Counters_AvgIterations\\\",$\"},\n           {\"\\\"family_index\\\": 10,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_Counters_AvgIterations\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 1,$\", MR_Next},\n           {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"bar\\\": %float,$\", MR_Next},\n           {\"\\\"foo\\\": %float$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut,\n          {{\"^\\\"BM_Counters_AvgIterations\\\",%csv_report,%float,%float$\"}});\n// VS2013 does not allow this function to be passed as a lambda argument\n// to CHECK_BENCHMARK_RESULTS()\nvoid CheckAvgIterations(Results const& e) {\n  double its = e.NumIterations();\n  // check that the values are within 0.1% of the expected value\n  CHECK_FLOAT_COUNTER_VALUE(e, \"foo\", EQ, 1. / its, 0.001);\n  CHECK_FLOAT_COUNTER_VALUE(e, \"bar\", EQ, 2. / its, 0.001);\n}\nCHECK_BENCHMARK_RESULTS(\"BM_Counters_AvgIterations\", &CheckAvgIterations);\n\n// ========================================================================= //\n// ------------------- AvgIterationsRate Counters Output ------------------- //\n// ========================================================================= //\n\nvoid BM_Counters_kAvgIterationsRate(benchmark::State& state) {\n  for (auto _ : state) {\n    // This test requires a non-zero CPU time to avoid divide-by-zero\n    auto iterations = state.iterations();\n    benchmark::DoNotOptimize(iterations);\n  }\n  namespace bm = benchmark;\n  state.counters[\"foo\"] = bm::Counter{1, bm::Counter::kAvgIterationsRate};\n  state.counters[\"bar\"] =\n      bm::Counter{2, bm::Counter::kIsRate | bm::Counter::kAvgIterations};\n}\nBENCHMARK(BM_Counters_kAvgIterationsRate);\nADD_CASES(TC_ConsoleOut, {{\"^BM_Counters_kAvgIterationsRate \"\n                           \"%console_report bar=%hrfloat/s foo=%hrfloat/s$\"}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_Counters_kAvgIterationsRate\\\",$\"},\n           {\"\\\"family_index\\\": 11,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_Counters_kAvgIterationsRate\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 1,$\", MR_Next},\n           {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"bar\\\": %float,$\", MR_Next},\n           {\"\\\"foo\\\": %float$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_CSVOut, {{\"^\\\"BM_Counters_kAvgIterationsRate\\\",%csv_report,\"\n                       \"%float,%float$\"}});\n// VS2013 does not allow this function to be passed as a lambda argument\n// to CHECK_BENCHMARK_RESULTS()\nvoid CheckAvgIterationsRate(Results const& e) {\n  double its = e.NumIterations();\n  double t = e.DurationCPUTime();  // this (and not real time) is the time used\n  // check that the values are within 0.1% of the expected values\n  CHECK_FLOAT_COUNTER_VALUE(e, \"foo\", EQ, 1. / its / t, 0.001);\n  CHECK_FLOAT_COUNTER_VALUE(e, \"bar\", EQ, 2. / its / t, 0.001);\n}\nCHECK_BENCHMARK_RESULTS(\"BM_Counters_kAvgIterationsRate\",\n                        &CheckAvgIterationsRate);\n\n// ========================================================================= //\n// --------------------------- TEST CASES END ------------------------------ //\n// ========================================================================= //\n\nint main(int argc, char* argv[]) { RunOutputTests(argc, argv); }\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/test/user_counters_thousands_test.cc",
    "content": "\n#undef NDEBUG\n\n#include \"benchmark/benchmark.h\"\n#include \"output_test.h\"\n\n// ========================================================================= //\n// ------------------------ Thousands Customisation ------------------------ //\n// ========================================================================= //\n\nvoid BM_Counters_Thousands(benchmark::State& state) {\n  for (auto _ : state) {\n  }\n  namespace bm = benchmark;\n  state.counters.insert({\n      {\"t0_1000000DefaultBase\",\n       bm::Counter(1000 * 1000, bm::Counter::kDefaults)},\n      {\"t1_1000000Base1000\", bm::Counter(1000 * 1000, bm::Counter::kDefaults,\n                                         benchmark::Counter::OneK::kIs1000)},\n      {\"t2_1000000Base1024\", bm::Counter(1000 * 1000, bm::Counter::kDefaults,\n                                         benchmark::Counter::OneK::kIs1024)},\n      {\"t3_1048576Base1000\", bm::Counter(1024 * 1024, bm::Counter::kDefaults,\n                                         benchmark::Counter::OneK::kIs1000)},\n      {\"t4_1048576Base1024\", bm::Counter(1024 * 1024, bm::Counter::kDefaults,\n                                         benchmark::Counter::OneK::kIs1024)},\n  });\n}\nBENCHMARK(BM_Counters_Thousands)->Repetitions(2);\nADD_CASES(\n    TC_ConsoleOut,\n    {\n        {\"^BM_Counters_Thousands/repeats:2 %console_report \"\n         \"t0_1000000DefaultBase=1000k \"\n         \"t1_1000000Base1000=1000k t2_1000000Base1024=976.56[23]k \"\n         \"t3_1048576Base1000=1048.58k t4_1048576Base1024=1024k$\"},\n        {\"^BM_Counters_Thousands/repeats:2 %console_report \"\n         \"t0_1000000DefaultBase=1000k \"\n         \"t1_1000000Base1000=1000k t2_1000000Base1024=976.56[23]k \"\n         \"t3_1048576Base1000=1048.58k t4_1048576Base1024=1024k$\"},\n        {\"^BM_Counters_Thousands/repeats:2_mean %console_report \"\n         \"t0_1000000DefaultBase=1000k t1_1000000Base1000=1000k \"\n         \"t2_1000000Base1024=976.56[23]k t3_1048576Base1000=1048.58k \"\n         \"t4_1048576Base1024=1024k$\"},\n        {\"^BM_Counters_Thousands/repeats:2_median %console_report \"\n         \"t0_1000000DefaultBase=1000k t1_1000000Base1000=1000k \"\n         \"t2_1000000Base1024=976.56[23]k t3_1048576Base1000=1048.58k \"\n         \"t4_1048576Base1024=1024k$\"},\n        {\"^BM_Counters_Thousands/repeats:2_stddev %console_time_only_report [ \"\n         \"]*2 t0_1000000DefaultBase=0 t1_1000000Base1000=0 \"\n         \"t2_1000000Base1024=0 t3_1048576Base1000=0 t4_1048576Base1024=0$\"},\n    });\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_Counters_Thousands/repeats:2\\\",$\"},\n           {\"\\\"family_index\\\": 0,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_Counters_Thousands/repeats:2\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 2,$\", MR_Next},\n           {\"\\\"repetition_index\\\": 0,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"t0_1000000DefaultBase\\\": 1\\\\.(0)*e\\\\+(0)*6,$\", MR_Next},\n           {\"\\\"t1_1000000Base1000\\\": 1\\\\.(0)*e\\\\+(0)*6,$\", MR_Next},\n           {\"\\\"t2_1000000Base1024\\\": 1\\\\.(0)*e\\\\+(0)*6,$\", MR_Next},\n           {\"\\\"t3_1048576Base1000\\\": 1\\\\.048576(0)*e\\\\+(0)*6,$\", MR_Next},\n           {\"\\\"t4_1048576Base1024\\\": 1\\\\.048576(0)*e\\\\+(0)*6$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_Counters_Thousands/repeats:2\\\",$\"},\n           {\"\\\"family_index\\\": 0,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_Counters_Thousands/repeats:2\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"iteration\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 2,$\", MR_Next},\n           {\"\\\"repetition_index\\\": 1,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"iterations\\\": %int,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"t0_1000000DefaultBase\\\": 1\\\\.(0)*e\\\\+(0)*6,$\", MR_Next},\n           {\"\\\"t1_1000000Base1000\\\": 1\\\\.(0)*e\\\\+(0)*6,$\", MR_Next},\n           {\"\\\"t2_1000000Base1024\\\": 1\\\\.(0)*e\\\\+(0)*6,$\", MR_Next},\n           {\"\\\"t3_1048576Base1000\\\": 1\\\\.048576(0)*e\\\\+(0)*6,$\", MR_Next},\n           {\"\\\"t4_1048576Base1024\\\": 1\\\\.048576(0)*e\\\\+(0)*6$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_Counters_Thousands/repeats:2_mean\\\",$\"},\n           {\"\\\"family_index\\\": 0,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_Counters_Thousands/repeats:2\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 2,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"aggregate_name\\\": \\\"mean\\\",$\", MR_Next},\n           {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n           {\"\\\"iterations\\\": 2,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"t0_1000000DefaultBase\\\": 1\\\\.(0)*e\\\\+(0)*6,$\", MR_Next},\n           {\"\\\"t1_1000000Base1000\\\": 1\\\\.(0)*e\\\\+(0)*6,$\", MR_Next},\n           {\"\\\"t2_1000000Base1024\\\": 1\\\\.(0)*e\\\\+(0)*6,$\", MR_Next},\n           {\"\\\"t3_1048576Base1000\\\": 1\\\\.048576(0)*e\\\\+(0)*6,$\", MR_Next},\n           {\"\\\"t4_1048576Base1024\\\": 1\\\\.048576(0)*e\\\\+(0)*6$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_Counters_Thousands/repeats:2_median\\\",$\"},\n           {\"\\\"family_index\\\": 0,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_Counters_Thousands/repeats:2\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 2,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"aggregate_name\\\": \\\"median\\\",$\", MR_Next},\n           {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n           {\"\\\"iterations\\\": 2,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"t0_1000000DefaultBase\\\": 1\\\\.(0)*e\\\\+(0)*6,$\", MR_Next},\n           {\"\\\"t1_1000000Base1000\\\": 1\\\\.(0)*e\\\\+(0)*6,$\", MR_Next},\n           {\"\\\"t2_1000000Base1024\\\": 1\\\\.(0)*e\\\\+(0)*6,$\", MR_Next},\n           {\"\\\"t3_1048576Base1000\\\": 1\\\\.048576(0)*e\\\\+(0)*6,$\", MR_Next},\n           {\"\\\"t4_1048576Base1024\\\": 1\\\\.048576(0)*e\\\\+(0)*6$\", MR_Next},\n           {\"}\", MR_Next}});\nADD_CASES(TC_JSONOut,\n          {{\"\\\"name\\\": \\\"BM_Counters_Thousands/repeats:2_stddev\\\",$\"},\n           {\"\\\"family_index\\\": 0,$\", MR_Next},\n           {\"\\\"per_family_instance_index\\\": 0,$\", MR_Next},\n           {\"\\\"run_name\\\": \\\"BM_Counters_Thousands/repeats:2\\\",$\", MR_Next},\n           {\"\\\"run_type\\\": \\\"aggregate\\\",$\", MR_Next},\n           {\"\\\"repetitions\\\": 2,$\", MR_Next},\n           {\"\\\"threads\\\": 1,$\", MR_Next},\n           {\"\\\"aggregate_name\\\": \\\"stddev\\\",$\", MR_Next},\n           {\"\\\"aggregate_unit\\\": \\\"time\\\",$\", MR_Next},\n           {\"\\\"iterations\\\": 2,$\", MR_Next},\n           {\"\\\"real_time\\\": %float,$\", MR_Next},\n           {\"\\\"cpu_time\\\": %float,$\", MR_Next},\n           {\"\\\"time_unit\\\": \\\"ns\\\",$\", MR_Next},\n           {\"\\\"t0_1000000DefaultBase\\\": 0\\\\.(0)*e\\\\+(0)*,$\", MR_Next},\n           {\"\\\"t1_1000000Base1000\\\": 0\\\\.(0)*e\\\\+(0)*,$\", MR_Next},\n           {\"\\\"t2_1000000Base1024\\\": 0\\\\.(0)*e\\\\+(0)*,$\", MR_Next},\n           {\"\\\"t3_1048576Base1000\\\": 0\\\\.(0)*e\\\\+(0)*,$\", MR_Next},\n           {\"\\\"t4_1048576Base1024\\\": 0\\\\.(0)*e\\\\+(0)*$\", MR_Next},\n           {\"}\", MR_Next}});\n\nADD_CASES(\n    TC_CSVOut,\n    {{\"^\\\"BM_Counters_Thousands/\"\n      \"repeats:2\\\",%csv_report,1e\\\\+(0)*6,1e\\\\+(0)*6,1e\\\\+(0)*6,1\\\\.04858e\\\\+(\"\n      \"0)*6,1\\\\.04858e\\\\+(0)*6$\"},\n     {\"^\\\"BM_Counters_Thousands/\"\n      \"repeats:2\\\",%csv_report,1e\\\\+(0)*6,1e\\\\+(0)*6,1e\\\\+(0)*6,1\\\\.04858e\\\\+(\"\n      \"0)*6,1\\\\.04858e\\\\+(0)*6$\"},\n     {\"^\\\"BM_Counters_Thousands/\"\n      \"repeats:2_mean\\\",%csv_report,1e\\\\+(0)*6,1e\\\\+(0)*6,1e\\\\+(0)*6,1\\\\.\"\n      \"04858e\\\\+(0)*6,1\\\\.04858e\\\\+(0)*6$\"},\n     {\"^\\\"BM_Counters_Thousands/\"\n      \"repeats:2_median\\\",%csv_report,1e\\\\+(0)*6,1e\\\\+(0)*6,1e\\\\+(0)*6,1\\\\.\"\n      \"04858e\\\\+(0)*6,1\\\\.04858e\\\\+(0)*6$\"},\n     {\"^\\\"BM_Counters_Thousands/repeats:2_stddev\\\",%csv_report,0,0,0,0,0$\"}});\n// VS2013 does not allow this function to be passed as a lambda argument\n// to CHECK_BENCHMARK_RESULTS()\nvoid CheckThousands(Results const& e) {\n  if (e.name != \"BM_Counters_Thousands/repeats:2\")\n    return;  // Do not check the aggregates!\n\n  // check that the values are within 0.01% of the expected values\n  CHECK_FLOAT_COUNTER_VALUE(e, \"t0_1000000DefaultBase\", EQ, 1000 * 1000,\n                            0.0001);\n  CHECK_FLOAT_COUNTER_VALUE(e, \"t1_1000000Base1000\", EQ, 1000 * 1000, 0.0001);\n  CHECK_FLOAT_COUNTER_VALUE(e, \"t2_1000000Base1024\", EQ, 1000 * 1000, 0.0001);\n  CHECK_FLOAT_COUNTER_VALUE(e, \"t3_1048576Base1000\", EQ, 1024 * 1024, 0.0001);\n  CHECK_FLOAT_COUNTER_VALUE(e, \"t4_1048576Base1024\", EQ, 1024 * 1024, 0.0001);\n}\nCHECK_BENCHMARK_RESULTS(\"BM_Counters_Thousands\", &CheckThousands);\n\n// ========================================================================= //\n// --------------------------- TEST CASES END ------------------------------ //\n// ========================================================================= //\n\nint main(int argc, char* argv[]) { RunOutputTests(argc, argv); }\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/tools/BUILD.bazel",
    "content": "load(\"@tools_pip_deps//:requirements.bzl\", \"requirement\")\n\npy_library(\n    name = \"gbench\",\n    srcs = glob([\"gbench/*.py\"]),\n    deps = [\n      requirement(\"numpy\"),\n      requirement(\"scipy\"),\n    ],\n)\n\npy_binary(\n    name = \"compare\",\n    srcs = [\"compare.py\"],\n    python_version = \"PY3\",\n    deps = [\n        \":gbench\",\n    ],\n)\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/tools/compare.py",
    "content": "#!/usr/bin/env python3\n\nimport unittest\n\"\"\"\ncompare.py - versatile benchmark output compare tool\n\"\"\"\n\nimport argparse\nfrom argparse import ArgumentParser\nimport json\nimport sys\nimport os\nimport gbench\nfrom gbench import util, report\n\n\ndef check_inputs(in1, in2, flags):\n    \"\"\"\n    Perform checking on the user provided inputs and diagnose any abnormalities\n    \"\"\"\n    in1_kind, in1_err = util.classify_input_file(in1)\n    in2_kind, in2_err = util.classify_input_file(in2)\n    output_file = util.find_benchmark_flag('--benchmark_out=', flags)\n    output_type = util.find_benchmark_flag('--benchmark_out_format=', flags)\n    if in1_kind == util.IT_Executable and in2_kind == util.IT_Executable and output_file:\n        print((\"WARNING: '--benchmark_out=%s' will be passed to both \"\n               \"benchmarks causing it to be overwritten\") % output_file)\n    if in1_kind == util.IT_JSON and in2_kind == util.IT_JSON:\n        # When both sides are JSON the only supported flag is\n        # --benchmark_filter=\n        for flag in util.remove_benchmark_flags('--benchmark_filter=', flags):\n            print(\"WARNING: passing %s has no effect since both \"\n                  \"inputs are JSON\" % flag)\n    if output_type is not None and output_type != 'json':\n        print((\"ERROR: passing '--benchmark_out_format=%s' to 'compare.py`\"\n               \" is not supported.\") % output_type)\n        sys.exit(1)\n\n\ndef create_parser():\n    parser = ArgumentParser(\n        description='versatile benchmark output compare tool')\n\n    parser.add_argument(\n        '-a',\n        '--display_aggregates_only',\n        dest='display_aggregates_only',\n        action=\"store_true\",\n        help=\"If there are repetitions, by default, we display everything - the\"\n             \" actual runs, and the aggregates computed. Sometimes, it is \"\n             \"desirable to only view the aggregates. E.g. when there are a lot \"\n             \"of repetitions. Do note that only the display is affected. \"\n             \"Internally, all the actual runs are still used, e.g. for U test.\")\n\n    parser.add_argument(\n        '--no-color',\n        dest='color',\n        default=True,\n        action=\"store_false\",\n        help=\"Do not use colors in the terminal output\"\n    )\n\n    parser.add_argument(\n        '-d',\n        '--dump_to_json',\n        dest='dump_to_json',\n        help=\"Additionally, dump benchmark comparison output to this file in JSON format.\")\n\n    utest = parser.add_argument_group()\n    utest.add_argument(\n        '--no-utest',\n        dest='utest',\n        default=True,\n        action=\"store_false\",\n        help=\"The tool can do a two-tailed Mann-Whitney U test with the null hypothesis that it is equally likely that a randomly selected value from one sample will be less than or greater than a randomly selected value from a second sample.\\nWARNING: requires **LARGE** (no less than {}) number of repetitions to be meaningful!\\nThe test is being done by default, if at least {} repetitions were done.\\nThis option can disable the U Test.\".format(report.UTEST_OPTIMAL_REPETITIONS, report.UTEST_MIN_REPETITIONS))\n    alpha_default = 0.05\n    utest.add_argument(\n        \"--alpha\",\n        dest='utest_alpha',\n        default=alpha_default,\n        type=float,\n        help=(\"significance level alpha. if the calculated p-value is below this value, then the result is said to be statistically significant and the null hypothesis is rejected.\\n(default: %0.4f)\") %\n        alpha_default)\n\n    subparsers = parser.add_subparsers(\n        help='This tool has multiple modes of operation:',\n        dest='mode')\n\n    parser_a = subparsers.add_parser(\n        'benchmarks',\n        help='The most simple use-case, compare all the output of these two benchmarks')\n    baseline = parser_a.add_argument_group(\n        'baseline', 'The benchmark baseline')\n    baseline.add_argument(\n        'test_baseline',\n        metavar='test_baseline',\n        type=argparse.FileType('r'),\n        nargs=1,\n        help='A benchmark executable or JSON output file')\n    contender = parser_a.add_argument_group(\n        'contender', 'The benchmark that will be compared against the baseline')\n    contender.add_argument(\n        'test_contender',\n        metavar='test_contender',\n        type=argparse.FileType('r'),\n        nargs=1,\n        help='A benchmark executable or JSON output file')\n    parser_a.add_argument(\n        'benchmark_options',\n        metavar='benchmark_options',\n        nargs=argparse.REMAINDER,\n        help='Arguments to pass when running benchmark executables')\n\n    parser_b = subparsers.add_parser(\n        'filters', help='Compare filter one with the filter two of benchmark')\n    baseline = parser_b.add_argument_group(\n        'baseline', 'The benchmark baseline')\n    baseline.add_argument(\n        'test',\n        metavar='test',\n        type=argparse.FileType('r'),\n        nargs=1,\n        help='A benchmark executable or JSON output file')\n    baseline.add_argument(\n        'filter_baseline',\n        metavar='filter_baseline',\n        type=str,\n        nargs=1,\n        help='The first filter, that will be used as baseline')\n    contender = parser_b.add_argument_group(\n        'contender', 'The benchmark that will be compared against the baseline')\n    contender.add_argument(\n        'filter_contender',\n        metavar='filter_contender',\n        type=str,\n        nargs=1,\n        help='The second filter, that will be compared against the baseline')\n    parser_b.add_argument(\n        'benchmark_options',\n        metavar='benchmark_options',\n        nargs=argparse.REMAINDER,\n        help='Arguments to pass when running benchmark executables')\n\n    parser_c = subparsers.add_parser(\n        'benchmarksfiltered',\n        help='Compare filter one of first benchmark with filter two of the second benchmark')\n    baseline = parser_c.add_argument_group(\n        'baseline', 'The benchmark baseline')\n    baseline.add_argument(\n        'test_baseline',\n        metavar='test_baseline',\n        type=argparse.FileType('r'),\n        nargs=1,\n        help='A benchmark executable or JSON output file')\n    baseline.add_argument(\n        'filter_baseline',\n        metavar='filter_baseline',\n        type=str,\n        nargs=1,\n        help='The first filter, that will be used as baseline')\n    contender = parser_c.add_argument_group(\n        'contender', 'The benchmark that will be compared against the baseline')\n    contender.add_argument(\n        'test_contender',\n        metavar='test_contender',\n        type=argparse.FileType('r'),\n        nargs=1,\n        help='The second benchmark executable or JSON output file, that will be compared against the baseline')\n    contender.add_argument(\n        'filter_contender',\n        metavar='filter_contender',\n        type=str,\n        nargs=1,\n        help='The second filter, that will be compared against the baseline')\n    parser_c.add_argument(\n        'benchmark_options',\n        metavar='benchmark_options',\n        nargs=argparse.REMAINDER,\n        help='Arguments to pass when running benchmark executables')\n\n    return parser\n\n\ndef main():\n    # Parse the command line flags\n    parser = create_parser()\n    args, unknown_args = parser.parse_known_args()\n    if args.mode is None:\n        parser.print_help()\n        exit(1)\n    assert not unknown_args\n    benchmark_options = args.benchmark_options\n\n    if args.mode == 'benchmarks':\n        test_baseline = args.test_baseline[0].name\n        test_contender = args.test_contender[0].name\n        filter_baseline = ''\n        filter_contender = ''\n\n        # NOTE: if test_baseline == test_contender, you are analyzing the stdev\n\n        description = 'Comparing %s to %s' % (test_baseline, test_contender)\n    elif args.mode == 'filters':\n        test_baseline = args.test[0].name\n        test_contender = args.test[0].name\n        filter_baseline = args.filter_baseline[0]\n        filter_contender = args.filter_contender[0]\n\n        # NOTE: if filter_baseline == filter_contender, you are analyzing the\n        # stdev\n\n        description = 'Comparing %s to %s (from %s)' % (\n            filter_baseline, filter_contender, args.test[0].name)\n    elif args.mode == 'benchmarksfiltered':\n        test_baseline = args.test_baseline[0].name\n        test_contender = args.test_contender[0].name\n        filter_baseline = args.filter_baseline[0]\n        filter_contender = args.filter_contender[0]\n\n        # NOTE: if test_baseline == test_contender and\n        # filter_baseline == filter_contender, you are analyzing the stdev\n\n        description = 'Comparing %s (from %s) to %s (from %s)' % (\n            filter_baseline, test_baseline, filter_contender, test_contender)\n    else:\n        # should never happen\n        print(\"Unrecognized mode of operation: '%s'\" % args.mode)\n        parser.print_help()\n        exit(1)\n\n    check_inputs(test_baseline, test_contender, benchmark_options)\n\n    if args.display_aggregates_only:\n        benchmark_options += ['--benchmark_display_aggregates_only=true']\n\n    options_baseline = []\n    options_contender = []\n\n    if filter_baseline and filter_contender:\n        options_baseline = ['--benchmark_filter=%s' % filter_baseline]\n        options_contender = ['--benchmark_filter=%s' % filter_contender]\n\n    # Run the benchmarks and report the results\n    json1 = json1_orig = gbench.util.sort_benchmark_results(gbench.util.run_or_load_benchmark(\n        test_baseline, benchmark_options + options_baseline))\n    json2 = json2_orig = gbench.util.sort_benchmark_results(gbench.util.run_or_load_benchmark(\n        test_contender, benchmark_options + options_contender))\n\n    # Now, filter the benchmarks so that the difference report can work\n    if filter_baseline and filter_contender:\n        replacement = '[%s vs. %s]' % (filter_baseline, filter_contender)\n        json1 = gbench.report.filter_benchmark(\n            json1_orig, filter_baseline, replacement)\n        json2 = gbench.report.filter_benchmark(\n            json2_orig, filter_contender, replacement)\n\n    diff_report = gbench.report.get_difference_report(\n        json1, json2, args.utest)\n    output_lines = gbench.report.print_difference_report(\n        diff_report,\n        args.display_aggregates_only,\n        args.utest, args.utest_alpha, args.color)\n    print(description)\n    for ln in output_lines:\n        print(ln)\n\n    # Optionally, diff and output to JSON\n    if args.dump_to_json is not None:\n        with open(args.dump_to_json, 'w') as f_json:\n            json.dump(diff_report, f_json)\n\nclass TestParser(unittest.TestCase):\n    def setUp(self):\n        self.parser = create_parser()\n        testInputs = os.path.join(\n            os.path.dirname(\n                os.path.realpath(__file__)),\n            'gbench',\n            'Inputs')\n        self.testInput0 = os.path.join(testInputs, 'test1_run1.json')\n        self.testInput1 = os.path.join(testInputs, 'test1_run2.json')\n\n    def test_benchmarks_basic(self):\n        parsed = self.parser.parse_args(\n            ['benchmarks', self.testInput0, self.testInput1])\n        self.assertFalse(parsed.display_aggregates_only)\n        self.assertTrue(parsed.utest)\n        self.assertEqual(parsed.mode, 'benchmarks')\n        self.assertEqual(parsed.test_baseline[0].name, self.testInput0)\n        self.assertEqual(parsed.test_contender[0].name, self.testInput1)\n        self.assertFalse(parsed.benchmark_options)\n\n    def test_benchmarks_basic_without_utest(self):\n        parsed = self.parser.parse_args(\n            ['--no-utest', 'benchmarks', self.testInput0, self.testInput1])\n        self.assertFalse(parsed.display_aggregates_only)\n        self.assertFalse(parsed.utest)\n        self.assertEqual(parsed.utest_alpha, 0.05)\n        self.assertEqual(parsed.mode, 'benchmarks')\n        self.assertEqual(parsed.test_baseline[0].name, self.testInput0)\n        self.assertEqual(parsed.test_contender[0].name, self.testInput1)\n        self.assertFalse(parsed.benchmark_options)\n\n    def test_benchmarks_basic_display_aggregates_only(self):\n        parsed = self.parser.parse_args(\n            ['-a', 'benchmarks', self.testInput0, self.testInput1])\n        self.assertTrue(parsed.display_aggregates_only)\n        self.assertTrue(parsed.utest)\n        self.assertEqual(parsed.mode, 'benchmarks')\n        self.assertEqual(parsed.test_baseline[0].name, self.testInput0)\n        self.assertEqual(parsed.test_contender[0].name, self.testInput1)\n        self.assertFalse(parsed.benchmark_options)\n\n    def test_benchmarks_basic_with_utest_alpha(self):\n        parsed = self.parser.parse_args(\n            ['--alpha=0.314', 'benchmarks', self.testInput0, self.testInput1])\n        self.assertFalse(parsed.display_aggregates_only)\n        self.assertTrue(parsed.utest)\n        self.assertEqual(parsed.utest_alpha, 0.314)\n        self.assertEqual(parsed.mode, 'benchmarks')\n        self.assertEqual(parsed.test_baseline[0].name, self.testInput0)\n        self.assertEqual(parsed.test_contender[0].name, self.testInput1)\n        self.assertFalse(parsed.benchmark_options)\n\n    def test_benchmarks_basic_without_utest_with_utest_alpha(self):\n        parsed = self.parser.parse_args(\n            ['--no-utest', '--alpha=0.314', 'benchmarks', self.testInput0, self.testInput1])\n        self.assertFalse(parsed.display_aggregates_only)\n        self.assertFalse(parsed.utest)\n        self.assertEqual(parsed.utest_alpha, 0.314)\n        self.assertEqual(parsed.mode, 'benchmarks')\n        self.assertEqual(parsed.test_baseline[0].name, self.testInput0)\n        self.assertEqual(parsed.test_contender[0].name, self.testInput1)\n        self.assertFalse(parsed.benchmark_options)\n\n    def test_benchmarks_with_remainder(self):\n        parsed = self.parser.parse_args(\n            ['benchmarks', self.testInput0, self.testInput1, 'd'])\n        self.assertFalse(parsed.display_aggregates_only)\n        self.assertTrue(parsed.utest)\n        self.assertEqual(parsed.mode, 'benchmarks')\n        self.assertEqual(parsed.test_baseline[0].name, self.testInput0)\n        self.assertEqual(parsed.test_contender[0].name, self.testInput1)\n        self.assertEqual(parsed.benchmark_options, ['d'])\n\n    def test_benchmarks_with_remainder_after_doubleminus(self):\n        parsed = self.parser.parse_args(\n            ['benchmarks', self.testInput0, self.testInput1, '--', 'e'])\n        self.assertFalse(parsed.display_aggregates_only)\n        self.assertTrue(parsed.utest)\n        self.assertEqual(parsed.mode, 'benchmarks')\n        self.assertEqual(parsed.test_baseline[0].name, self.testInput0)\n        self.assertEqual(parsed.test_contender[0].name, self.testInput1)\n        self.assertEqual(parsed.benchmark_options, ['e'])\n\n    def test_filters_basic(self):\n        parsed = self.parser.parse_args(\n            ['filters', self.testInput0, 'c', 'd'])\n        self.assertFalse(parsed.display_aggregates_only)\n        self.assertTrue(parsed.utest)\n        self.assertEqual(parsed.mode, 'filters')\n        self.assertEqual(parsed.test[0].name, self.testInput0)\n        self.assertEqual(parsed.filter_baseline[0], 'c')\n        self.assertEqual(parsed.filter_contender[0], 'd')\n        self.assertFalse(parsed.benchmark_options)\n\n    def test_filters_with_remainder(self):\n        parsed = self.parser.parse_args(\n            ['filters', self.testInput0, 'c', 'd', 'e'])\n        self.assertFalse(parsed.display_aggregates_only)\n        self.assertTrue(parsed.utest)\n        self.assertEqual(parsed.mode, 'filters')\n        self.assertEqual(parsed.test[0].name, self.testInput0)\n        self.assertEqual(parsed.filter_baseline[0], 'c')\n        self.assertEqual(parsed.filter_contender[0], 'd')\n        self.assertEqual(parsed.benchmark_options, ['e'])\n\n    def test_filters_with_remainder_after_doubleminus(self):\n        parsed = self.parser.parse_args(\n            ['filters', self.testInput0, 'c', 'd', '--', 'f'])\n        self.assertFalse(parsed.display_aggregates_only)\n        self.assertTrue(parsed.utest)\n        self.assertEqual(parsed.mode, 'filters')\n        self.assertEqual(parsed.test[0].name, self.testInput0)\n        self.assertEqual(parsed.filter_baseline[0], 'c')\n        self.assertEqual(parsed.filter_contender[0], 'd')\n        self.assertEqual(parsed.benchmark_options, ['f'])\n\n    def test_benchmarksfiltered_basic(self):\n        parsed = self.parser.parse_args(\n            ['benchmarksfiltered', self.testInput0, 'c', self.testInput1, 'e'])\n        self.assertFalse(parsed.display_aggregates_only)\n        self.assertTrue(parsed.utest)\n        self.assertEqual(parsed.mode, 'benchmarksfiltered')\n        self.assertEqual(parsed.test_baseline[0].name, self.testInput0)\n        self.assertEqual(parsed.filter_baseline[0], 'c')\n        self.assertEqual(parsed.test_contender[0].name, self.testInput1)\n        self.assertEqual(parsed.filter_contender[0], 'e')\n        self.assertFalse(parsed.benchmark_options)\n\n    def test_benchmarksfiltered_with_remainder(self):\n        parsed = self.parser.parse_args(\n            ['benchmarksfiltered', self.testInput0, 'c', self.testInput1, 'e', 'f'])\n        self.assertFalse(parsed.display_aggregates_only)\n        self.assertTrue(parsed.utest)\n        self.assertEqual(parsed.mode, 'benchmarksfiltered')\n        self.assertEqual(parsed.test_baseline[0].name, self.testInput0)\n        self.assertEqual(parsed.filter_baseline[0], 'c')\n        self.assertEqual(parsed.test_contender[0].name, self.testInput1)\n        self.assertEqual(parsed.filter_contender[0], 'e')\n        self.assertEqual(parsed.benchmark_options[0], 'f')\n\n    def test_benchmarksfiltered_with_remainder_after_doubleminus(self):\n        parsed = self.parser.parse_args(\n            ['benchmarksfiltered', self.testInput0, 'c', self.testInput1, 'e', '--', 'g'])\n        self.assertFalse(parsed.display_aggregates_only)\n        self.assertTrue(parsed.utest)\n        self.assertEqual(parsed.mode, 'benchmarksfiltered')\n        self.assertEqual(parsed.test_baseline[0].name, self.testInput0)\n        self.assertEqual(parsed.filter_baseline[0], 'c')\n        self.assertEqual(parsed.test_contender[0].name, self.testInput1)\n        self.assertEqual(parsed.filter_contender[0], 'e')\n        self.assertEqual(parsed.benchmark_options[0], 'g')\n\n\nif __name__ == '__main__':\n    # unittest.main()\n    main()\n\n# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4\n# kate: tab-width: 4; replace-tabs on; indent-width 4; tab-indents: off;\n# kate: indent-mode python; remove-trailing-spaces modified;\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/tools/gbench/Inputs/test1_run1.json",
    "content": "{\n  \"context\": {\n    \"date\": \"2016-08-02 17:44:46\",\n    \"num_cpus\": 4,\n    \"mhz_per_cpu\": 4228,\n    \"cpu_scaling_enabled\": false,\n    \"library_build_type\": \"release\"\n  },\n  \"benchmarks\": [\n    {\n      \"name\": \"BM_SameTimes\",\n      \"iterations\": 1000,\n      \"real_time\": 10,\n      \"cpu_time\": 10,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_2xFaster\",\n      \"iterations\": 1000,\n      \"real_time\": 50,\n      \"cpu_time\": 50,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_2xSlower\",\n      \"iterations\": 1000,\n      \"real_time\": 50,\n      \"cpu_time\": 50,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_1PercentFaster\",\n      \"iterations\": 1000,\n      \"real_time\": 100,\n      \"cpu_time\": 100,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_1PercentSlower\",\n      \"iterations\": 1000,\n      \"real_time\": 100,\n      \"cpu_time\": 100,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_10PercentFaster\",\n      \"iterations\": 1000,\n      \"real_time\": 100,\n      \"cpu_time\": 100,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_10PercentSlower\",\n      \"iterations\": 1000,\n      \"real_time\": 100,\n      \"cpu_time\": 100,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_100xSlower\",\n      \"iterations\": 1000,\n      \"real_time\": 100,\n      \"cpu_time\": 100,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_100xFaster\",\n      \"iterations\": 1000,\n      \"real_time\": 10000,\n      \"cpu_time\": 10000,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_10PercentCPUToTime\",\n      \"iterations\": 1000,\n      \"real_time\": 100,\n      \"cpu_time\": 100,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_ThirdFaster\",\n      \"iterations\": 1000,\n      \"real_time\": 100,\n      \"cpu_time\": 100,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"MyComplexityTest_BigO\",\n      \"run_name\": \"MyComplexityTest\",\n      \"run_type\": \"aggregate\",\n      \"aggregate_name\": \"BigO\",\n      \"cpu_coefficient\": 4.2749856294592886e+00,\n      \"real_coefficient\": 6.4789275289789780e+00,\n      \"big_o\": \"N\",\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"MyComplexityTest_RMS\",\n      \"run_name\": \"MyComplexityTest\",\n      \"run_type\": \"aggregate\",\n      \"aggregate_name\": \"RMS\",\n      \"rms\": 4.5097802512472874e-03\n    },\n    {\n      \"name\": \"BM_NotBadTimeUnit\",\n      \"iterations\": 1000,\n      \"real_time\": 0.4,\n      \"cpu_time\": 0.5,\n      \"time_unit\": \"s\"\n    },\n    {\n      \"name\": \"BM_DifferentTimeUnit\",\n      \"iterations\": 1,\n      \"real_time\": 1,\n      \"cpu_time\": 1,\n      \"time_unit\": \"s\"\n    },\n    {\n      \"name\": \"BM_hasLabel\",\n      \"label\": \"a label\",\n      \"iterations\": 1,\n      \"real_time\": 1,\n      \"cpu_time\": 1,\n      \"time_unit\": \"s\"\n    }\n  ]\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/tools/gbench/Inputs/test1_run2.json",
    "content": "{\n  \"context\": {\n    \"date\": \"2016-08-02 17:44:46\",\n    \"num_cpus\": 4,\n    \"mhz_per_cpu\": 4228,\n    \"cpu_scaling_enabled\": false,\n    \"library_build_type\": \"release\"\n  },\n  \"benchmarks\": [\n    {\n      \"name\": \"BM_SameTimes\",\n      \"iterations\": 1000,\n      \"real_time\": 10,\n      \"cpu_time\": 10,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_2xFaster\",\n      \"iterations\": 1000,\n      \"real_time\": 25,\n      \"cpu_time\": 25,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_2xSlower\",\n      \"iterations\": 20833333,\n      \"real_time\": 100,\n      \"cpu_time\": 100,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_1PercentFaster\",\n      \"iterations\": 1000,\n      \"real_time\": 98.9999999,\n      \"cpu_time\": 98.9999999,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_1PercentSlower\",\n      \"iterations\": 1000,\n      \"real_time\": 100.9999999,\n      \"cpu_time\": 100.9999999,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_10PercentFaster\",\n      \"iterations\": 1000,\n      \"real_time\": 90,\n      \"cpu_time\": 90,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_10PercentSlower\",\n      \"iterations\": 1000,\n      \"real_time\": 110,\n      \"cpu_time\": 110,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_100xSlower\",\n      \"iterations\": 1000,\n      \"real_time\": 1.0000e+04,\n      \"cpu_time\": 1.0000e+04,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_100xFaster\",\n      \"iterations\": 1000,\n      \"real_time\": 100,\n      \"cpu_time\": 100,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_10PercentCPUToTime\",\n      \"iterations\": 1000,\n      \"real_time\": 110,\n      \"cpu_time\": 90,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_ThirdFaster\",\n      \"iterations\": 1000,\n      \"real_time\": 66.665,\n      \"cpu_time\": 66.664,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"MyComplexityTest_BigO\",\n      \"run_name\": \"MyComplexityTest\",\n      \"run_type\": \"aggregate\",\n      \"aggregate_name\": \"BigO\",\n      \"cpu_coefficient\": 5.6215779594361486e+00,\n      \"real_coefficient\": 5.6288314793554610e+00,\n      \"big_o\": \"N\",\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"MyComplexityTest_RMS\",\n      \"run_name\": \"MyComplexityTest\",\n      \"run_type\": \"aggregate\",\n      \"aggregate_name\": \"RMS\",\n      \"rms\": 3.3128901852342174e-03\n    },\n    {\n      \"name\": \"BM_NotBadTimeUnit\",\n      \"iterations\": 1000,\n      \"real_time\": 0.04,\n      \"cpu_time\": 0.6,\n      \"time_unit\": \"s\"\n    },\n    {\n      \"name\": \"BM_DifferentTimeUnit\",\n      \"iterations\": 1,\n      \"real_time\": 1,\n      \"cpu_time\": 1,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_hasLabel\",\n      \"label\": \"a label\",\n      \"iterations\": 1,\n      \"real_time\": 1,\n      \"cpu_time\": 1,\n      \"time_unit\": \"s\"\n    }\n  ]\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/tools/gbench/Inputs/test2_run.json",
    "content": "{\n  \"context\": {\n    \"date\": \"2016-08-02 17:44:46\",\n    \"num_cpus\": 4,\n    \"mhz_per_cpu\": 4228,\n    \"cpu_scaling_enabled\": false,\n    \"library_build_type\": \"release\"\n  },\n  \"benchmarks\": [\n    {\n      \"name\": \"BM_Hi\",\n      \"iterations\": 1234,\n      \"real_time\": 42,\n      \"cpu_time\": 24,\n      \"time_unit\": \"ms\"\n    },\n    {\n      \"name\": \"BM_Zero\",\n      \"iterations\": 1000,\n      \"real_time\": 10,\n      \"cpu_time\": 10,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_Zero/4\",\n      \"iterations\": 4000,\n      \"real_time\": 40,\n      \"cpu_time\": 40,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"Prefix/BM_Zero\",\n      \"iterations\": 2000,\n      \"real_time\": 20,\n      \"cpu_time\": 20,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"Prefix/BM_Zero/3\",\n      \"iterations\": 3000,\n      \"real_time\": 30,\n      \"cpu_time\": 30,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_One\",\n      \"iterations\": 5000,\n      \"real_time\": 5,\n      \"cpu_time\": 5,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_One/4\",\n      \"iterations\": 2000,\n      \"real_time\": 20,\n      \"cpu_time\": 20,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"Prefix/BM_One\",\n      \"iterations\": 1000,\n      \"real_time\": 10,\n      \"cpu_time\": 10,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"Prefix/BM_One/3\",\n      \"iterations\": 1500,\n      \"real_time\": 15,\n      \"cpu_time\": 15,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_Bye\",\n      \"iterations\": 5321,\n      \"real_time\": 11,\n      \"cpu_time\": 63,\n      \"time_unit\": \"ns\"\n    }\n  ]\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/tools/gbench/Inputs/test3_run0.json",
    "content": "{\n  \"context\": {\n    \"date\": \"2016-08-02 17:44:46\",\n    \"num_cpus\": 4,\n    \"mhz_per_cpu\": 4228,\n    \"cpu_scaling_enabled\": false,\n    \"library_build_type\": \"release\"\n  },\n  \"benchmarks\": [\n    {\n      \"name\": \"BM_One\",\n      \"run_type\": \"aggregate\",\n      \"iterations\": 1000,\n      \"real_time\": 10,\n      \"cpu_time\": 100,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_Two\",\n      \"iterations\": 1000,\n      \"real_time\": 9,\n      \"cpu_time\": 90,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_Two\",\n      \"iterations\": 1000,\n      \"real_time\": 8,\n      \"cpu_time\": 86,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"short\",\n      \"run_type\": \"aggregate\",\n      \"iterations\": 1000,\n      \"real_time\": 8,\n      \"cpu_time\": 80,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"short\",\n      \"run_type\": \"aggregate\",\n      \"iterations\": 1000,\n      \"real_time\": 8,\n      \"cpu_time\": 77,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"medium\",\n      \"run_type\": \"iteration\",\n      \"iterations\": 1000,\n      \"real_time\": 8,\n      \"cpu_time\": 80,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"medium\",\n      \"run_type\": \"iteration\",\n      \"iterations\": 1000,\n      \"real_time\": 9,\n      \"cpu_time\": 82,\n      \"time_unit\": \"ns\"\n    }\n  ]\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/tools/gbench/Inputs/test3_run1.json",
    "content": "{\n  \"context\": {\n    \"date\": \"2016-08-02 17:44:46\",\n    \"num_cpus\": 4,\n    \"mhz_per_cpu\": 4228,\n    \"cpu_scaling_enabled\": false,\n    \"library_build_type\": \"release\"\n  },\n  \"benchmarks\": [\n    {\n      \"name\": \"BM_One\",\n      \"iterations\": 1000,\n      \"real_time\": 9,\n      \"cpu_time\": 110,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_Two\",\n      \"run_type\": \"aggregate\",\n      \"iterations\": 1000,\n      \"real_time\": 10,\n      \"cpu_time\": 89,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"BM_Two\",\n      \"iterations\": 1000,\n      \"real_time\": 7,\n      \"cpu_time\": 72,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"short\",\n      \"run_type\": \"aggregate\",\n      \"iterations\": 1000,\n      \"real_time\": 7,\n      \"cpu_time\": 75,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"short\",\n      \"run_type\": \"aggregate\",\n      \"iterations\": 762,\n      \"real_time\": 4.54,\n      \"cpu_time\": 66.6,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"short\",\n      \"run_type\": \"iteration\",\n      \"iterations\": 1000,\n      \"real_time\": 800,\n      \"cpu_time\": 1,\n      \"time_unit\": \"ns\"\n    },\n    {\n      \"name\": \"medium\",\n      \"run_type\": \"iteration\",\n      \"iterations\": 1200,\n      \"real_time\": 5,\n      \"cpu_time\": 53,\n      \"time_unit\": \"ns\"\n    }\n  ]\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/tools/gbench/Inputs/test4_run.json",
    "content": "{\n  \"benchmarks\": [\n    {\n      \"name\": \"99 family 0 instance 0 repetition 0\",\n      \"run_type\": \"iteration\",\n      \"family_index\": 0,\n      \"per_family_instance_index\": 0,\n      \"repetition_index\": 0\n    },\n    {\n      \"name\": \"98 family 0 instance 0 repetition 1\",\n      \"run_type\": \"iteration\",\n      \"family_index\": 0,\n      \"per_family_instance_index\": 0,\n      \"repetition_index\": 1\n    },\n    {\n      \"name\": \"97 family 0 instance 0 aggregate\",\n      \"run_type\": \"aggregate\",\n      \"family_index\": 0,\n      \"per_family_instance_index\": 0,\n      \"aggregate_name\": \"9 aggregate\"\n    },\n\n\n    {\n      \"name\": \"96 family 0 instance 1 repetition 0\",\n      \"run_type\": \"iteration\",\n      \"family_index\": 0,\n      \"per_family_instance_index\": 1,\n      \"repetition_index\": 0\n    },\n    {\n      \"name\": \"95 family 0 instance 1 repetition 1\",\n      \"run_type\": \"iteration\",\n      \"family_index\": 0,\n      \"per_family_instance_index\": 1,\n      \"repetition_index\": 1\n    },\n    {\n      \"name\": \"94 family 0 instance 1 aggregate\",\n      \"run_type\": \"aggregate\",\n      \"family_index\": 0,\n      \"per_family_instance_index\": 1,\n      \"aggregate_name\": \"9 aggregate\"\n    },\n\n\n\n\n    {\n      \"name\": \"93 family 1 instance 0 repetition 0\",\n      \"run_type\": \"iteration\",\n      \"family_index\": 1,\n      \"per_family_instance_index\": 0,\n      \"repetition_index\": 0\n    },\n    {\n      \"name\": \"92 family 1 instance 0 repetition 1\",\n      \"run_type\": \"iteration\",\n      \"family_index\": 1,\n      \"per_family_instance_index\": 0,\n      \"repetition_index\": 1\n    },\n    {\n      \"name\": \"91 family 1 instance 0 aggregate\",\n      \"run_type\": \"aggregate\",\n      \"family_index\": 1,\n      \"per_family_instance_index\": 0,\n      \"aggregate_name\": \"9 aggregate\"\n    },\n\n\n    {\n      \"name\": \"90 family 1 instance 1 repetition 0\",\n      \"run_type\": \"iteration\",\n      \"family_index\": 1,\n      \"per_family_instance_index\": 1,\n      \"repetition_index\": 0\n    },\n    {\n      \"name\": \"89 family 1 instance 1 repetition 1\",\n      \"run_type\": \"iteration\",\n      \"family_index\": 1,\n      \"per_family_instance_index\": 1,\n      \"repetition_index\": 1\n    },\n    {\n      \"name\": \"88 family 1 instance 1 aggregate\",\n      \"run_type\": \"aggregate\",\n      \"family_index\": 1,\n      \"per_family_instance_index\": 1,\n      \"aggregate_name\": \"9 aggregate\"\n    }\n  ]\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/tools/gbench/Inputs/test4_run0.json",
    "content": "{\n  \"context\": {\n    \"date\": \"2016-08-02 17:44:46\",\n    \"num_cpus\": 4,\n    \"mhz_per_cpu\": 4228,\n    \"cpu_scaling_enabled\": false,\n    \"library_build_type\": \"release\"\n  },\n  \"benchmarks\": [\n    {\n      \"name\": \"whocares\",\n      \"run_type\": \"aggregate\",\n      \"aggregate_name\": \"zz\",\n      \"aggregate_unit\": \"percentage\",\n      \"iterations\": 1000,\n      \"real_time\": 0.01,\n      \"cpu_time\": 0.10,\n      \"time_unit\": \"ns\"\n    }\n  ]\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/tools/gbench/Inputs/test4_run1.json",
    "content": "{\n  \"context\": {\n    \"date\": \"2016-08-02 17:44:46\",\n    \"num_cpus\": 4,\n    \"mhz_per_cpu\": 4228,\n    \"cpu_scaling_enabled\": false,\n    \"library_build_type\": \"release\"\n  },\n  \"benchmarks\": [\n    {\n      \"name\": \"whocares\",\n      \"run_type\": \"aggregate\",\n      \"aggregate_name\": \"zz\",\n      \"aggregate_unit\": \"percentage\",\n      \"iterations\": 1000,\n      \"real_time\": 0.005,\n      \"cpu_time\": 0.15,\n      \"time_unit\": \"ns\"\n    }\n  ]\n}\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/tools/gbench/__init__.py",
    "content": "\"\"\"Google Benchmark tooling\"\"\"\n\n__author__ = 'Eric Fiselier'\n__email__ = 'eric@efcs.ca'\n__versioninfo__ = (0, 5, 0)\n__version__ = '.'.join(str(v) for v in __versioninfo__) + 'dev'\n\n__all__ = []\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/tools/gbench/report.py",
    "content": "\"\"\"report.py - Utilities for reporting statistics about benchmark results\n\"\"\"\n\nimport unittest\nimport os\nimport re\nimport copy\nimport random\n\nfrom scipy.stats import mannwhitneyu, gmean\nfrom numpy import array\n\n\nclass BenchmarkColor(object):\n    def __init__(self, name, code):\n        self.name = name\n        self.code = code\n\n    def __repr__(self):\n        return '%s%r' % (self.__class__.__name__,\n                         (self.name, self.code))\n\n    def __format__(self, format):\n        return self.code\n\n\n# Benchmark Colors Enumeration\nBC_NONE = BenchmarkColor('NONE', '')\nBC_MAGENTA = BenchmarkColor('MAGENTA', '\\033[95m')\nBC_CYAN = BenchmarkColor('CYAN', '\\033[96m')\nBC_OKBLUE = BenchmarkColor('OKBLUE', '\\033[94m')\nBC_OKGREEN = BenchmarkColor('OKGREEN', '\\033[32m')\nBC_HEADER = BenchmarkColor('HEADER', '\\033[92m')\nBC_WARNING = BenchmarkColor('WARNING', '\\033[93m')\nBC_WHITE = BenchmarkColor('WHITE', '\\033[97m')\nBC_FAIL = BenchmarkColor('FAIL', '\\033[91m')\nBC_ENDC = BenchmarkColor('ENDC', '\\033[0m')\nBC_BOLD = BenchmarkColor('BOLD', '\\033[1m')\nBC_UNDERLINE = BenchmarkColor('UNDERLINE', '\\033[4m')\n\nUTEST_MIN_REPETITIONS = 2\nUTEST_OPTIMAL_REPETITIONS = 9  # Lowest reasonable number, More is better.\nUTEST_COL_NAME = \"_pvalue\"\n\n_TIME_UNIT_TO_SECONDS_MULTIPLIER = {\n    \"s\": 1.0,\n    \"ms\": 1e-3,\n    \"us\": 1e-6,\n    \"ns\": 1e-9,\n}\n\n\ndef color_format(use_color, fmt_str, *args, **kwargs):\n    \"\"\"\n    Return the result of 'fmt_str.format(*args, **kwargs)' after transforming\n    'args' and 'kwargs' according to the value of 'use_color'. If 'use_color'\n    is False then all color codes in 'args' and 'kwargs' are replaced with\n    the empty string.\n    \"\"\"\n    assert use_color is True or use_color is False\n    if not use_color:\n        args = [arg if not isinstance(arg, BenchmarkColor) else BC_NONE\n                for arg in args]\n        kwargs = {key: arg if not isinstance(arg, BenchmarkColor) else BC_NONE\n                  for key, arg in kwargs.items()}\n    return fmt_str.format(*args, **kwargs)\n\n\ndef find_longest_name(benchmark_list):\n    \"\"\"\n    Return the length of the longest benchmark name in a given list of\n    benchmark JSON objects\n    \"\"\"\n    longest_name = 1\n    for bc in benchmark_list:\n        if len(bc['name']) > longest_name:\n            longest_name = len(bc['name'])\n    return longest_name\n\n\ndef calculate_change(old_val, new_val):\n    \"\"\"\n    Return a float representing the decimal change between old_val and new_val.\n    \"\"\"\n    if old_val == 0 and new_val == 0:\n        return 0.0\n    if old_val == 0:\n        return float(new_val - old_val) / (float(old_val + new_val) / 2)\n    return float(new_val - old_val) / abs(old_val)\n\n\ndef filter_benchmark(json_orig, family, replacement=\"\"):\n    \"\"\"\n    Apply a filter to the json, and only leave the 'family' of benchmarks.\n    \"\"\"\n    regex = re.compile(family)\n    filtered = {}\n    filtered['benchmarks'] = []\n    for be in json_orig['benchmarks']:\n        if not regex.search(be['name']):\n            continue\n        filteredbench = copy.deepcopy(be)  # Do NOT modify the old name!\n        filteredbench['name'] = regex.sub(replacement, filteredbench['name'])\n        filtered['benchmarks'].append(filteredbench)\n    return filtered\n\n\ndef get_unique_benchmark_names(json):\n    \"\"\"\n    While *keeping* the order, give all the unique 'names' used for benchmarks.\n    \"\"\"\n    seen = set()\n    uniqued = [x['name'] for x in json['benchmarks']\n               if x['name'] not in seen and\n               (seen.add(x['name']) or True)]\n    return uniqued\n\n\ndef intersect(list1, list2):\n    \"\"\"\n    Given two lists, get a new list consisting of the elements only contained\n    in *both of the input lists*, while preserving the ordering.\n    \"\"\"\n    return [x for x in list1 if x in list2]\n\n\ndef is_potentially_comparable_benchmark(x):\n    return ('time_unit' in x and 'real_time' in x and 'cpu_time' in x)\n\n\ndef partition_benchmarks(json1, json2):\n    \"\"\"\n    While preserving the ordering, find benchmarks with the same names in\n    both of the inputs, and group them.\n    (i.e. partition/filter into groups with common name)\n    \"\"\"\n    json1_unique_names = get_unique_benchmark_names(json1)\n    json2_unique_names = get_unique_benchmark_names(json2)\n    names = intersect(json1_unique_names, json2_unique_names)\n    partitions = []\n    for name in names:\n        time_unit = None\n        # Pick the time unit from the first entry of the lhs benchmark.\n        # We should be careful not to crash with unexpected input.\n        for x in json1['benchmarks']:\n            if (x['name'] == name and is_potentially_comparable_benchmark(x)):\n                time_unit = x['time_unit']\n                break\n        if time_unit is None:\n            continue\n        # Filter by name and time unit.\n        # All the repetitions are assumed to be comparable.\n        lhs = [x for x in json1['benchmarks'] if x['name'] == name and\n               x['time_unit'] == time_unit]\n        rhs = [x for x in json2['benchmarks'] if x['name'] == name and\n               x['time_unit'] == time_unit]\n        partitions.append([lhs, rhs])\n    return partitions\n\n\ndef get_timedelta_field_as_seconds(benchmark, field_name):\n    \"\"\"\n    Get value of field_name field of benchmark, which is time with time unit\n    time_unit, as time in seconds.\n    \"\"\"\n    timedelta = benchmark[field_name]\n    time_unit = benchmark.get('time_unit', 's')\n    return timedelta * _TIME_UNIT_TO_SECONDS_MULTIPLIER.get(time_unit)\n\n\ndef calculate_geomean(json):\n    \"\"\"\n    Extract all real/cpu times from all the benchmarks as seconds,\n    and calculate their geomean.\n    \"\"\"\n    times = []\n    for benchmark in json['benchmarks']:\n        if 'run_type' in benchmark and benchmark['run_type'] == 'aggregate':\n            continue\n        times.append([get_timedelta_field_as_seconds(benchmark, 'real_time'),\n                      get_timedelta_field_as_seconds(benchmark, 'cpu_time')])\n    return gmean(times) if times else array([])\n\n\ndef extract_field(partition, field_name):\n    # The count of elements may be different. We want *all* of them.\n    lhs = [x[field_name] for x in partition[0]]\n    rhs = [x[field_name] for x in partition[1]]\n    return [lhs, rhs]\n\n\ndef calc_utest(timings_cpu, timings_time):\n    min_rep_cnt = min(len(timings_time[0]),\n                      len(timings_time[1]),\n                      len(timings_cpu[0]),\n                      len(timings_cpu[1]))\n\n    # Does *everything* has at least UTEST_MIN_REPETITIONS repetitions?\n    if min_rep_cnt < UTEST_MIN_REPETITIONS:\n        return False, None, None\n\n    time_pvalue = mannwhitneyu(\n        timings_time[0], timings_time[1], alternative='two-sided').pvalue\n    cpu_pvalue = mannwhitneyu(\n        timings_cpu[0], timings_cpu[1], alternative='two-sided').pvalue\n\n    return (min_rep_cnt >= UTEST_OPTIMAL_REPETITIONS), cpu_pvalue, time_pvalue\n\n\ndef print_utest(bc_name, utest, utest_alpha, first_col_width, use_color=True):\n    def get_utest_color(pval):\n        return BC_FAIL if pval >= utest_alpha else BC_OKGREEN\n\n    # Check if we failed miserably with minimum required repetitions for utest\n    if not utest['have_optimal_repetitions'] and utest['cpu_pvalue'] is None and utest['time_pvalue'] is None:\n        return []\n\n    dsc = \"U Test, Repetitions: {} vs {}\".format(\n        utest['nr_of_repetitions'], utest['nr_of_repetitions_other'])\n    dsc_color = BC_OKGREEN\n\n    # We still got some results to show but issue a warning about it.\n    if not utest['have_optimal_repetitions']:\n        dsc_color = BC_WARNING\n        dsc += \". WARNING: Results unreliable! {}+ repetitions recommended.\".format(\n            UTEST_OPTIMAL_REPETITIONS)\n\n    special_str = \"{}{:<{}s}{endc}{}{:16.4f}{endc}{}{:16.4f}{endc}{}      {}\"\n\n    return [color_format(use_color,\n                         special_str,\n                         BC_HEADER,\n                         \"{}{}\".format(bc_name, UTEST_COL_NAME),\n                         first_col_width,\n                         get_utest_color(\n                             utest['time_pvalue']), utest['time_pvalue'],\n                         get_utest_color(\n                             utest['cpu_pvalue']), utest['cpu_pvalue'],\n                         dsc_color, dsc,\n                         endc=BC_ENDC)]\n\n\ndef get_difference_report(\n        json1,\n        json2,\n        utest=False):\n    \"\"\"\n    Calculate and report the difference between each test of two benchmarks\n    runs specified as 'json1' and 'json2'. Output is another json containing\n    relevant details for each test run.\n    \"\"\"\n    assert utest is True or utest is False\n\n    diff_report = []\n    partitions = partition_benchmarks(json1, json2)\n    for partition in partitions:\n        benchmark_name = partition[0][0]['name']\n        label = partition[0][0]['label'] if 'label' in partition[0][0] else ''\n        time_unit = partition[0][0]['time_unit']\n        measurements = []\n        utest_results = {}\n        # Careful, we may have different repetition count.\n        for i in range(min(len(partition[0]), len(partition[1]))):\n            bn = partition[0][i]\n            other_bench = partition[1][i]\n            measurements.append({\n                'real_time': bn['real_time'],\n                'cpu_time': bn['cpu_time'],\n                'real_time_other': other_bench['real_time'],\n                'cpu_time_other': other_bench['cpu_time'],\n                'time': calculate_change(bn['real_time'], other_bench['real_time']),\n                'cpu': calculate_change(bn['cpu_time'], other_bench['cpu_time'])\n            })\n\n        # After processing the whole partition, if requested, do the U test.\n        if utest:\n            timings_cpu = extract_field(partition, 'cpu_time')\n            timings_time = extract_field(partition, 'real_time')\n            have_optimal_repetitions, cpu_pvalue, time_pvalue = calc_utest(\n                timings_cpu, timings_time)\n            if cpu_pvalue and time_pvalue:\n                utest_results = {\n                    'have_optimal_repetitions': have_optimal_repetitions,\n                    'cpu_pvalue': cpu_pvalue,\n                    'time_pvalue': time_pvalue,\n                    'nr_of_repetitions': len(timings_cpu[0]),\n                    'nr_of_repetitions_other': len(timings_cpu[1])\n                }\n\n        # Store only if we had any measurements for given benchmark.\n        # E.g. partition_benchmarks will filter out the benchmarks having\n        # time units which are not compatible with other time units in the\n        # benchmark suite.\n        if measurements:\n            run_type = partition[0][0]['run_type'] if 'run_type' in partition[0][0] else ''\n            aggregate_name = partition[0][0]['aggregate_name'] if run_type == 'aggregate' and 'aggregate_name' in partition[0][0] else ''\n            diff_report.append({\n                'name': benchmark_name,\n                'label': label,\n                'measurements': measurements,\n                'time_unit': time_unit,\n                'run_type': run_type,\n                'aggregate_name': aggregate_name,\n                'utest': utest_results\n            })\n\n    lhs_gmean = calculate_geomean(json1)\n    rhs_gmean = calculate_geomean(json2)\n    if lhs_gmean.any() and rhs_gmean.any():\n        diff_report.append({\n            'name': 'OVERALL_GEOMEAN',\n            'label': '',\n            'measurements': [{\n                'real_time': lhs_gmean[0],\n                'cpu_time': lhs_gmean[1],\n                'real_time_other': rhs_gmean[0],\n                'cpu_time_other': rhs_gmean[1],\n                'time': calculate_change(lhs_gmean[0], rhs_gmean[0]),\n                'cpu': calculate_change(lhs_gmean[1], rhs_gmean[1])\n            }],\n            'time_unit': 's',\n            'run_type': 'aggregate',\n            'aggregate_name': 'geomean',\n            'utest': {}\n        })\n\n    return diff_report\n\n\ndef print_difference_report(\n        json_diff_report,\n        include_aggregates_only=False,\n        utest=False,\n        utest_alpha=0.05,\n        use_color=True):\n    \"\"\"\n    Calculate and report the difference between each test of two benchmarks\n    runs specified as 'json1' and 'json2'.\n    \"\"\"\n    assert utest is True or utest is False\n\n    def get_color(res):\n        if res > 0.05:\n            return BC_FAIL\n        elif res > -0.07:\n            return BC_WHITE\n        else:\n            return BC_CYAN\n\n    first_col_width = find_longest_name(json_diff_report)\n    first_col_width = max(\n        first_col_width,\n        len('Benchmark'))\n    first_col_width += len(UTEST_COL_NAME)\n    first_line = \"{:<{}s}Time             CPU      Time Old      Time New       CPU Old       CPU New\".format(\n        'Benchmark', 12 + first_col_width)\n    output_strs = [first_line, '-' * len(first_line)]\n\n    fmt_str = \"{}{:<{}s}{endc}{}{:+16.4f}{endc}{}{:+16.4f}{endc}{:14.0f}{:14.0f}{endc}{:14.0f}{:14.0f}\"\n    for benchmark in json_diff_report:\n        # *If* we were asked to only include aggregates,\n        # and if it is non-aggregate, then don't print it.\n        if not include_aggregates_only or not 'run_type' in benchmark or benchmark['run_type'] == 'aggregate':\n            for measurement in benchmark['measurements']:\n                output_strs += [color_format(use_color,\n                                             fmt_str,\n                                             BC_HEADER,\n                                             benchmark['name'],\n                                             first_col_width,\n                                             get_color(measurement['time']),\n                                             measurement['time'],\n                                             get_color(measurement['cpu']),\n                                             measurement['cpu'],\n                                             measurement['real_time'],\n                                             measurement['real_time_other'],\n                                             measurement['cpu_time'],\n                                             measurement['cpu_time_other'],\n                                             endc=BC_ENDC)]\n\n        # After processing the measurements, if requested and\n        # if applicable (e.g. u-test exists for given benchmark),\n        # print the U test.\n        if utest and benchmark['utest']:\n            output_strs += print_utest(benchmark['name'],\n                                       benchmark['utest'],\n                                       utest_alpha=utest_alpha,\n                                       first_col_width=first_col_width,\n                                       use_color=use_color)\n\n    return output_strs\n\n\n###############################################################################\n# Unit tests\n\n\nclass TestGetUniqueBenchmarkNames(unittest.TestCase):\n    def load_results(self):\n        import json\n        testInputs = os.path.join(\n            os.path.dirname(\n                os.path.realpath(__file__)),\n            'Inputs')\n        testOutput = os.path.join(testInputs, 'test3_run0.json')\n        with open(testOutput, 'r') as f:\n            json = json.load(f)\n        return json\n\n    def test_basic(self):\n        expect_lines = [\n            'BM_One',\n            'BM_Two',\n            'short',  # These two are not sorted\n            'medium',  # These two are not sorted\n        ]\n        json = self.load_results()\n        output_lines = get_unique_benchmark_names(json)\n        print(\"\\n\")\n        print(\"\\n\".join(output_lines))\n        self.assertEqual(len(output_lines), len(expect_lines))\n        for i in range(0, len(output_lines)):\n            self.assertEqual(expect_lines[i], output_lines[i])\n\n\nclass TestReportDifference(unittest.TestCase):\n    @classmethod\n    def setUpClass(cls):\n        def load_results():\n            import json\n            testInputs = os.path.join(\n                os.path.dirname(\n                    os.path.realpath(__file__)),\n                'Inputs')\n            testOutput1 = os.path.join(testInputs, 'test1_run1.json')\n            testOutput2 = os.path.join(testInputs, 'test1_run2.json')\n            with open(testOutput1, 'r') as f:\n                json1 = json.load(f)\n            with open(testOutput2, 'r') as f:\n                json2 = json.load(f)\n            return json1, json2\n\n        json1, json2 = load_results()\n        cls.json_diff_report = get_difference_report(json1, json2)\n\n    def test_json_diff_report_pretty_printing(self):\n        expect_lines = [\n            ['BM_SameTimes', '+0.0000', '+0.0000', '10', '10', '10', '10'],\n            ['BM_2xFaster', '-0.5000', '-0.5000', '50', '25', '50', '25'],\n            ['BM_2xSlower', '+1.0000', '+1.0000', '50', '100', '50', '100'],\n            ['BM_1PercentFaster', '-0.0100', '-0.0100', '100', '99', '100', '99'],\n            ['BM_1PercentSlower', '+0.0100', '+0.0100', '100', '101', '100', '101'],\n            ['BM_10PercentFaster', '-0.1000', '-0.1000', '100', '90', '100', '90'],\n            ['BM_10PercentSlower', '+0.1000', '+0.1000', '100', '110', '100', '110'],\n            ['BM_100xSlower', '+99.0000', '+99.0000',\n                '100', '10000', '100', '10000'],\n            ['BM_100xFaster', '-0.9900', '-0.9900',\n                '10000', '100', '10000', '100'],\n            ['BM_10PercentCPUToTime', '+0.1000',\n                '-0.1000', '100', '110', '100', '90'],\n            ['BM_ThirdFaster', '-0.3333', '-0.3334', '100', '67', '100', '67'],\n            ['BM_NotBadTimeUnit', '-0.9000', '+0.2000', '0', '0', '0', '1'],\n            ['BM_hasLabel', '+0.0000', '+0.0000', '1', '1', '1', '1'],\n            ['OVERALL_GEOMEAN', '-0.8113', '-0.7779', '0', '0', '0', '0']\n        ]\n        output_lines_with_header = print_difference_report(\n            self.json_diff_report, use_color=False)\n        output_lines = output_lines_with_header[2:]\n        print(\"\\n\")\n        print(\"\\n\".join(output_lines_with_header))\n        self.assertEqual(len(output_lines), len(expect_lines))\n        for i in range(0, len(output_lines)):\n            parts = [x for x in output_lines[i].split(' ') if x]\n            self.assertEqual(len(parts), 7)\n            self.assertEqual(expect_lines[i], parts)\n\n    def test_json_diff_report_output(self):\n        expected_output = [\n            {\n                'name': 'BM_SameTimes',\n                'label': '',\n                'measurements': [{'time': 0.0000, 'cpu': 0.0000,\n                                  'real_time': 10, 'real_time_other': 10,\n                                  'cpu_time': 10, 'cpu_time_other': 10}],\n                'time_unit': 'ns',\n                'utest': {}\n            },\n            {\n                'name': 'BM_2xFaster',\n                'label': '',\n                'measurements': [{'time': -0.5000, 'cpu': -0.5000,\n                                  'real_time': 50, 'real_time_other': 25,\n                                  'cpu_time': 50, 'cpu_time_other': 25}],\n                'time_unit': 'ns',\n                'utest': {}\n            },\n            {\n                'name': 'BM_2xSlower',\n                'label': '',\n                'measurements': [{'time': 1.0000, 'cpu': 1.0000,\n                                  'real_time': 50, 'real_time_other': 100,\n                                  'cpu_time': 50, 'cpu_time_other': 100}],\n                'time_unit': 'ns',\n                'utest': {}\n            },\n            {\n                'name': 'BM_1PercentFaster',\n                'label': '',\n                'measurements': [{'time': -0.0100, 'cpu': -0.0100,\n                                  'real_time': 100, 'real_time_other': 98.9999999,\n                                  'cpu_time': 100, 'cpu_time_other': 98.9999999}],\n                'time_unit': 'ns',\n                'utest': {}\n            },\n            {\n                'name': 'BM_1PercentSlower',\n                'label': '',\n                'measurements': [{'time': 0.0100, 'cpu': 0.0100,\n                                  'real_time': 100, 'real_time_other': 101,\n                                  'cpu_time': 100, 'cpu_time_other': 101}],\n                'time_unit': 'ns',\n                'utest': {}\n            },\n            {\n                'name': 'BM_10PercentFaster',\n                'label': '',\n                'measurements': [{'time': -0.1000, 'cpu': -0.1000,\n                                  'real_time': 100, 'real_time_other': 90,\n                                  'cpu_time': 100, 'cpu_time_other': 90}],\n                'time_unit': 'ns',\n                'utest': {}\n            },\n            {\n                'name': 'BM_10PercentSlower',\n                'label': '',\n                'measurements': [{'time': 0.1000, 'cpu': 0.1000,\n                                  'real_time': 100, 'real_time_other': 110,\n                                  'cpu_time': 100, 'cpu_time_other': 110}],\n                'time_unit': 'ns',\n                'utest': {}\n            },\n            {\n                'name': 'BM_100xSlower',\n                'label': '',\n                'measurements': [{'time': 99.0000, 'cpu': 99.0000,\n                                  'real_time': 100, 'real_time_other': 10000,\n                                  'cpu_time': 100, 'cpu_time_other': 10000}],\n                'time_unit': 'ns',\n                'utest': {}\n            },\n            {\n                'name': 'BM_100xFaster',\n                'label': '',\n                'measurements': [{'time': -0.9900, 'cpu': -0.9900,\n                                  'real_time': 10000, 'real_time_other': 100,\n                                  'cpu_time': 10000, 'cpu_time_other': 100}],\n                'time_unit': 'ns',\n                'utest': {}\n            },\n            {\n                'name': 'BM_10PercentCPUToTime',\n                'label': '',\n                'measurements': [{'time': 0.1000, 'cpu': -0.1000,\n                                  'real_time': 100, 'real_time_other': 110,\n                                  'cpu_time': 100, 'cpu_time_other': 90}],\n                'time_unit': 'ns',\n                'utest': {}\n            },\n            {\n                'name': 'BM_ThirdFaster',\n                'label': '',\n                'measurements': [{'time': -0.3333, 'cpu': -0.3334,\n                                  'real_time': 100, 'real_time_other': 67,\n                                  'cpu_time': 100, 'cpu_time_other': 67}],\n                'time_unit': 'ns',\n                'utest': {}\n            },\n            {\n                'name': 'BM_NotBadTimeUnit',\n                'label': '',\n                'measurements': [{'time': -0.9000, 'cpu': 0.2000,\n                                  'real_time': 0.4, 'real_time_other': 0.04,\n                                  'cpu_time': 0.5, 'cpu_time_other': 0.6}],\n                'time_unit': 's',\n                'utest': {}\n            },\n            {\n                'name': 'BM_hasLabel',\n                'label': 'a label',\n                'measurements': [{'time': 0.0000, 'cpu': 0.0000,\n                                  'real_time': 1, 'real_time_other': 1,\n                                  'cpu_time': 1, 'cpu_time_other': 1}],\n                'time_unit': 's',\n                'utest': {}\n            },\n            {\n                'name': 'OVERALL_GEOMEAN',\n                'label': '',\n                'measurements': [{'real_time': 3.1622776601683826e-06, 'cpu_time': 3.2130844755623912e-06,\n                                  'real_time_other': 1.9768988699420897e-07, 'cpu_time_other': 2.397447755209533e-07,\n                                  'time': -0.8112976497120911, 'cpu': -0.7778551721181174}],\n                'time_unit': 's',\n                'run_type': 'aggregate',\n                'aggregate_name': 'geomean', 'utest': {}\n            },\n        ]\n        self.assertEqual(len(self.json_diff_report), len(expected_output))\n        for out, expected in zip(\n                self.json_diff_report, expected_output):\n            self.assertEqual(out['name'], expected['name'])\n            self.assertEqual(out['label'], expected['label'])\n            self.assertEqual(out['time_unit'], expected['time_unit'])\n            assert_utest(self, out, expected)\n            assert_measurements(self, out, expected)\n\n\nclass TestReportDifferenceBetweenFamilies(unittest.TestCase):\n    @classmethod\n    def setUpClass(cls):\n        def load_result():\n            import json\n            testInputs = os.path.join(\n                os.path.dirname(\n                    os.path.realpath(__file__)),\n                'Inputs')\n            testOutput = os.path.join(testInputs, 'test2_run.json')\n            with open(testOutput, 'r') as f:\n                json = json.load(f)\n            return json\n\n        json = load_result()\n        json1 = filter_benchmark(json, \"BM_Z.ro\", \".\")\n        json2 = filter_benchmark(json, \"BM_O.e\", \".\")\n        cls.json_diff_report = get_difference_report(json1, json2)\n\n    def test_json_diff_report_pretty_printing(self):\n        expect_lines = [\n            ['.', '-0.5000', '-0.5000', '10', '5', '10', '5'],\n            ['./4', '-0.5000', '-0.5000', '40', '20', '40', '20'],\n            ['Prefix/.', '-0.5000', '-0.5000', '20', '10', '20', '10'],\n            ['Prefix/./3', '-0.5000', '-0.5000', '30', '15', '30', '15'],\n            ['OVERALL_GEOMEAN', '-0.5000', '-0.5000', '0', '0', '0', '0']\n        ]\n        output_lines_with_header = print_difference_report(\n            self.json_diff_report, use_color=False)\n        output_lines = output_lines_with_header[2:]\n        print(\"\\n\")\n        print(\"\\n\".join(output_lines_with_header))\n        self.assertEqual(len(output_lines), len(expect_lines))\n        for i in range(0, len(output_lines)):\n            parts = [x for x in output_lines[i].split(' ') if x]\n            self.assertEqual(len(parts), 7)\n            self.assertEqual(expect_lines[i], parts)\n\n    def test_json_diff_report(self):\n        expected_output = [\n            {\n                'name': u'.',\n                'measurements': [{'time': -0.5, 'cpu': -0.5, 'real_time': 10, 'real_time_other': 5, 'cpu_time': 10, 'cpu_time_other': 5}],\n                'time_unit': 'ns',\n                'utest': {}\n            },\n            {\n                'name': u'./4',\n                'measurements': [{'time': -0.5, 'cpu': -0.5, 'real_time': 40, 'real_time_other': 20, 'cpu_time': 40, 'cpu_time_other': 20}],\n                'time_unit': 'ns',\n                'utest': {},\n            },\n            {\n                'name': u'Prefix/.',\n                'measurements': [{'time': -0.5, 'cpu': -0.5, 'real_time': 20, 'real_time_other': 10, 'cpu_time': 20, 'cpu_time_other': 10}],\n                'time_unit': 'ns',\n                'utest': {}\n            },\n            {\n                'name': u'Prefix/./3',\n                'measurements': [{'time': -0.5, 'cpu': -0.5, 'real_time': 30, 'real_time_other': 15, 'cpu_time': 30, 'cpu_time_other': 15}],\n                'time_unit': 'ns',\n                'utest': {}\n            },\n            {\n                'name': 'OVERALL_GEOMEAN',\n                'measurements': [{'real_time': 2.213363839400641e-08, 'cpu_time': 2.213363839400641e-08,\n                                  'real_time_other': 1.1066819197003185e-08, 'cpu_time_other': 1.1066819197003185e-08,\n                                  'time': -0.5000000000000009, 'cpu': -0.5000000000000009}],\n                'time_unit': 's',\n                'run_type': 'aggregate',\n                'aggregate_name': 'geomean',\n                'utest': {}\n            }\n        ]\n        self.assertEqual(len(self.json_diff_report), len(expected_output))\n        for out, expected in zip(\n                self.json_diff_report, expected_output):\n            self.assertEqual(out['name'], expected['name'])\n            self.assertEqual(out['time_unit'], expected['time_unit'])\n            assert_utest(self, out, expected)\n            assert_measurements(self, out, expected)\n\n\nclass TestReportDifferenceWithUTest(unittest.TestCase):\n    @classmethod\n    def setUpClass(cls):\n        def load_results():\n            import json\n            testInputs = os.path.join(\n                os.path.dirname(\n                    os.path.realpath(__file__)),\n                'Inputs')\n            testOutput1 = os.path.join(testInputs, 'test3_run0.json')\n            testOutput2 = os.path.join(testInputs, 'test3_run1.json')\n            with open(testOutput1, 'r') as f:\n                json1 = json.load(f)\n            with open(testOutput2, 'r') as f:\n                json2 = json.load(f)\n            return json1, json2\n\n        json1, json2 = load_results()\n        cls.json_diff_report = get_difference_report(\n            json1, json2, utest=True)\n\n    def test_json_diff_report_pretty_printing(self):\n        expect_lines = [\n            ['BM_One', '-0.1000', '+0.1000', '10', '9', '100', '110'],\n            ['BM_Two', '+0.1111', '-0.0111', '9', '10', '90', '89'],\n            ['BM_Two', '-0.1250', '-0.1628', '8', '7', '86', '72'],\n            ['BM_Two_pvalue',\n             '1.0000',\n             '0.6667',\n             'U',\n             'Test,',\n             'Repetitions:',\n             '2',\n             'vs',\n             '2.',\n             'WARNING:',\n             'Results',\n             'unreliable!',\n             '9+',\n             'repetitions',\n             'recommended.'],\n            ['short', '-0.1250', '-0.0625', '8', '7', '80', '75'],\n            ['short', '-0.4325', '-0.1351', '8', '5', '77', '67'],\n            ['short_pvalue',\n             '0.7671',\n             '0.2000',\n             'U',\n             'Test,',\n             'Repetitions:',\n             '2',\n             'vs',\n             '3.',\n             'WARNING:',\n             'Results',\n             'unreliable!',\n             '9+',\n             'repetitions',\n             'recommended.'],\n            ['medium', '-0.3750', '-0.3375', '8', '5', '80', '53'],\n            ['OVERALL_GEOMEAN', '+1.6405', '-0.6985', '0', '0', '0', '0']\n        ]\n        output_lines_with_header = print_difference_report(\n            self.json_diff_report, utest=True, utest_alpha=0.05, use_color=False)\n        output_lines = output_lines_with_header[2:]\n        print(\"\\n\")\n        print(\"\\n\".join(output_lines_with_header))\n        self.assertEqual(len(output_lines), len(expect_lines))\n        for i in range(0, len(output_lines)):\n            parts = [x for x in output_lines[i].split(' ') if x]\n            self.assertEqual(expect_lines[i], parts)\n\n    def test_json_diff_report_pretty_printing_aggregates_only(self):\n        expect_lines = [\n            ['BM_One', '-0.1000', '+0.1000', '10', '9', '100', '110'],\n            ['BM_Two_pvalue',\n             '1.0000',\n             '0.6667',\n             'U',\n             'Test,',\n             'Repetitions:',\n             '2',\n             'vs',\n             '2.',\n             'WARNING:',\n             'Results',\n             'unreliable!',\n             '9+',\n             'repetitions',\n             'recommended.'],\n            ['short', '-0.1250', '-0.0625', '8', '7', '80', '75'],\n            ['short', '-0.4325', '-0.1351', '8', '5', '77', '67'],\n            ['short_pvalue',\n             '0.7671',\n             '0.2000',\n             'U',\n             'Test,',\n             'Repetitions:',\n             '2',\n             'vs',\n             '3.',\n             'WARNING:',\n             'Results',\n             'unreliable!',\n             '9+',\n             'repetitions',\n             'recommended.'],\n            ['OVERALL_GEOMEAN', '+1.6405', '-0.6985', '0', '0', '0', '0']\n        ]\n        output_lines_with_header = print_difference_report(\n            self.json_diff_report, include_aggregates_only=True, utest=True, utest_alpha=0.05, use_color=False)\n        output_lines = output_lines_with_header[2:]\n        print(\"\\n\")\n        print(\"\\n\".join(output_lines_with_header))\n        self.assertEqual(len(output_lines), len(expect_lines))\n        for i in range(0, len(output_lines)):\n            parts = [x for x in output_lines[i].split(' ') if x]\n            self.assertEqual(expect_lines[i], parts)\n\n    def test_json_diff_report(self):\n        expected_output = [\n            {\n                'name': u'BM_One',\n                'measurements': [\n                    {'time': -0.1,\n                     'cpu': 0.1,\n                     'real_time': 10,\n                     'real_time_other': 9,\n                     'cpu_time': 100,\n                     'cpu_time_other': 110}\n                ],\n                'time_unit': 'ns',\n                'utest': {}\n            },\n            {\n                'name': u'BM_Two',\n                'measurements': [\n                    {'time': 0.1111111111111111,\n                     'cpu': -0.011111111111111112,\n                     'real_time': 9,\n                     'real_time_other': 10,\n                     'cpu_time': 90,\n                     'cpu_time_other': 89},\n                    {'time': -0.125, 'cpu': -0.16279069767441862, 'real_time': 8,\n                        'real_time_other': 7, 'cpu_time': 86, 'cpu_time_other': 72}\n                ],\n                'time_unit': 'ns',\n                'utest': {\n                    'have_optimal_repetitions': False, 'cpu_pvalue': 0.6666666666666666, 'time_pvalue': 1.0\n                }\n            },\n            {\n                'name': u'short',\n                'measurements': [\n                    {'time': -0.125,\n                     'cpu': -0.0625,\n                     'real_time': 8,\n                     'real_time_other': 7,\n                     'cpu_time': 80,\n                     'cpu_time_other': 75},\n                    {'time': -0.4325,\n                     'cpu': -0.13506493506493514,\n                     'real_time': 8,\n                     'real_time_other': 4.54,\n                     'cpu_time': 77,\n                     'cpu_time_other': 66.6}\n                ],\n                'time_unit': 'ns',\n                'utest': {\n                    'have_optimal_repetitions': False, 'cpu_pvalue': 0.2, 'time_pvalue': 0.7670968684102772\n                }\n            },\n            {\n                'name': u'medium',\n                'measurements': [\n                    {'time': -0.375,\n                     'cpu': -0.3375,\n                     'real_time': 8,\n                     'real_time_other': 5,\n                     'cpu_time': 80,\n                     'cpu_time_other': 53}\n                ],\n                'time_unit': 'ns',\n                'utest': {}\n            },\n            {\n                'name': 'OVERALL_GEOMEAN',\n                'measurements': [{'real_time': 8.48528137423858e-09, 'cpu_time': 8.441336246629233e-08,\n                                  'real_time_other': 2.2405267593145244e-08, 'cpu_time_other': 2.5453661413660466e-08,\n                                  'time': 1.6404861082353634, 'cpu': -0.6984640740519662}],\n                'time_unit': 's',\n                'run_type': 'aggregate',\n                'aggregate_name': 'geomean',\n                'utest': {}\n            }\n        ]\n        self.assertEqual(len(self.json_diff_report), len(expected_output))\n        for out, expected in zip(\n                self.json_diff_report, expected_output):\n            self.assertEqual(out['name'], expected['name'])\n            self.assertEqual(out['time_unit'], expected['time_unit'])\n            assert_utest(self, out, expected)\n            assert_measurements(self, out, expected)\n\n\nclass TestReportDifferenceWithUTestWhileDisplayingAggregatesOnly(\n        unittest.TestCase):\n    @classmethod\n    def setUpClass(cls):\n        def load_results():\n            import json\n            testInputs = os.path.join(\n                os.path.dirname(\n                    os.path.realpath(__file__)),\n                'Inputs')\n            testOutput1 = os.path.join(testInputs, 'test3_run0.json')\n            testOutput2 = os.path.join(testInputs, 'test3_run1.json')\n            with open(testOutput1, 'r') as f:\n                json1 = json.load(f)\n            with open(testOutput2, 'r') as f:\n                json2 = json.load(f)\n            return json1, json2\n\n        json1, json2 = load_results()\n        cls.json_diff_report = get_difference_report(\n            json1, json2, utest=True)\n\n    def test_json_diff_report_pretty_printing(self):\n        expect_lines = [\n            ['BM_One', '-0.1000', '+0.1000', '10', '9', '100', '110'],\n            ['BM_Two', '+0.1111', '-0.0111', '9', '10', '90', '89'],\n            ['BM_Two', '-0.1250', '-0.1628', '8', '7', '86', '72'],\n            ['BM_Two_pvalue',\n             '1.0000',\n             '0.6667',\n             'U',\n             'Test,',\n             'Repetitions:',\n             '2',\n             'vs',\n             '2.',\n             'WARNING:',\n             'Results',\n             'unreliable!',\n             '9+',\n             'repetitions',\n             'recommended.'],\n            ['short', '-0.1250', '-0.0625', '8', '7', '80', '75'],\n            ['short', '-0.4325', '-0.1351', '8', '5', '77', '67'],\n            ['short_pvalue',\n             '0.7671',\n             '0.2000',\n             'U',\n             'Test,',\n             'Repetitions:',\n             '2',\n             'vs',\n             '3.',\n             'WARNING:',\n             'Results',\n             'unreliable!',\n             '9+',\n             'repetitions',\n             'recommended.'],\n            ['medium', '-0.3750', '-0.3375', '8', '5', '80', '53'],\n            ['OVERALL_GEOMEAN', '+1.6405', '-0.6985', '0', '0', '0', '0']\n        ]\n        output_lines_with_header = print_difference_report(\n            self.json_diff_report,\n            utest=True, utest_alpha=0.05, use_color=False)\n        output_lines = output_lines_with_header[2:]\n        print(\"\\n\")\n        print(\"\\n\".join(output_lines_with_header))\n        self.assertEqual(len(output_lines), len(expect_lines))\n        for i in range(0, len(output_lines)):\n            parts = [x for x in output_lines[i].split(' ') if x]\n            self.assertEqual(expect_lines[i], parts)\n\n    def test_json_diff_report(self):\n        expected_output = [\n            {\n                'name': u'BM_One',\n                'measurements': [\n                    {'time': -0.1,\n                     'cpu': 0.1,\n                     'real_time': 10,\n                     'real_time_other': 9,\n                     'cpu_time': 100,\n                     'cpu_time_other': 110}\n                ],\n                'time_unit': 'ns',\n                'utest': {}\n            },\n            {\n                'name': u'BM_Two',\n                'measurements': [\n                    {'time': 0.1111111111111111,\n                     'cpu': -0.011111111111111112,\n                     'real_time': 9,\n                     'real_time_other': 10,\n                     'cpu_time': 90,\n                     'cpu_time_other': 89},\n                    {'time': -0.125, 'cpu': -0.16279069767441862, 'real_time': 8,\n                        'real_time_other': 7, 'cpu_time': 86, 'cpu_time_other': 72}\n                ],\n                'time_unit': 'ns',\n                'utest': {\n                    'have_optimal_repetitions': False, 'cpu_pvalue': 0.6666666666666666, 'time_pvalue': 1.0\n                }\n            },\n            {\n                'name': u'short',\n                'measurements': [\n                    {'time': -0.125,\n                     'cpu': -0.0625,\n                     'real_time': 8,\n                     'real_time_other': 7,\n                     'cpu_time': 80,\n                     'cpu_time_other': 75},\n                    {'time': -0.4325,\n                     'cpu': -0.13506493506493514,\n                     'real_time': 8,\n                     'real_time_other': 4.54,\n                     'cpu_time': 77,\n                     'cpu_time_other': 66.6}\n                ],\n                'time_unit': 'ns',\n                'utest': {\n                    'have_optimal_repetitions': False, 'cpu_pvalue': 0.2, 'time_pvalue': 0.7670968684102772\n                }\n            },\n            {\n                'name': u'medium',\n                'measurements': [\n                    {'real_time_other': 5,\n                     'cpu_time': 80,\n                     'time': -0.375,\n                     'real_time': 8,\n                     'cpu_time_other': 53,\n                     'cpu': -0.3375\n                     }\n                ],\n                'utest': {},\n                'time_unit': u'ns',\n                'aggregate_name': ''\n            },\n            {\n                'name': 'OVERALL_GEOMEAN',\n                'measurements': [{'real_time': 8.48528137423858e-09, 'cpu_time': 8.441336246629233e-08,\n                                  'real_time_other': 2.2405267593145244e-08, 'cpu_time_other': 2.5453661413660466e-08,\n                                  'time': 1.6404861082353634, 'cpu': -0.6984640740519662}],\n                'time_unit': 's',\n                'run_type': 'aggregate',\n                'aggregate_name': 'geomean',\n                'utest': {}\n            }\n        ]\n        self.assertEqual(len(self.json_diff_report), len(expected_output))\n        for out, expected in zip(\n                self.json_diff_report, expected_output):\n            self.assertEqual(out['name'], expected['name'])\n            self.assertEqual(out['time_unit'], expected['time_unit'])\n            assert_utest(self, out, expected)\n            assert_measurements(self, out, expected)\n\n\nclass TestReportDifferenceForPercentageAggregates(\n        unittest.TestCase):\n    @classmethod\n    def setUpClass(cls):\n        def load_results():\n            import json\n            testInputs = os.path.join(\n                os.path.dirname(\n                    os.path.realpath(__file__)),\n                'Inputs')\n            testOutput1 = os.path.join(testInputs, 'test4_run0.json')\n            testOutput2 = os.path.join(testInputs, 'test4_run1.json')\n            with open(testOutput1, 'r') as f:\n                json1 = json.load(f)\n            with open(testOutput2, 'r') as f:\n                json2 = json.load(f)\n            return json1, json2\n\n        json1, json2 = load_results()\n        cls.json_diff_report = get_difference_report(\n            json1, json2, utest=True)\n\n    def test_json_diff_report_pretty_printing(self):\n        expect_lines = [\n            ['whocares', '-0.5000', '+0.5000', '0', '0', '0', '0']\n        ]\n        output_lines_with_header = print_difference_report(\n            self.json_diff_report,\n            utest=True, utest_alpha=0.05, use_color=False)\n        output_lines = output_lines_with_header[2:]\n        print(\"\\n\")\n        print(\"\\n\".join(output_lines_with_header))\n        self.assertEqual(len(output_lines), len(expect_lines))\n        for i in range(0, len(output_lines)):\n            parts = [x for x in output_lines[i].split(' ') if x]\n            self.assertEqual(expect_lines[i], parts)\n\n    def test_json_diff_report(self):\n        expected_output = [\n            {\n                'name': u'whocares',\n                'measurements': [\n                    {'time': -0.5,\n                     'cpu': 0.5,\n                     'real_time': 0.01,\n                     'real_time_other': 0.005,\n                     'cpu_time': 0.10,\n                     'cpu_time_other': 0.15}\n                ],\n                'time_unit': 'ns',\n                'utest': {}\n            }\n        ]\n        self.assertEqual(len(self.json_diff_report), len(expected_output))\n        for out, expected in zip(\n                self.json_diff_report, expected_output):\n            self.assertEqual(out['name'], expected['name'])\n            self.assertEqual(out['time_unit'], expected['time_unit'])\n            assert_utest(self, out, expected)\n            assert_measurements(self, out, expected)\n\n\nclass TestReportSorting(unittest.TestCase):\n    @classmethod\n    def setUpClass(cls):\n        def load_result():\n            import json\n            testInputs = os.path.join(\n                os.path.dirname(\n                    os.path.realpath(__file__)),\n                'Inputs')\n            testOutput = os.path.join(testInputs, 'test4_run.json')\n            with open(testOutput, 'r') as f:\n                json = json.load(f)\n            return json\n\n        cls.json = load_result()\n\n    def test_json_diff_report_pretty_printing(self):\n        import util\n\n        expected_names = [\n            \"99 family 0 instance 0 repetition 0\",\n            \"98 family 0 instance 0 repetition 1\",\n            \"97 family 0 instance 0 aggregate\",\n            \"96 family 0 instance 1 repetition 0\",\n            \"95 family 0 instance 1 repetition 1\",\n            \"94 family 0 instance 1 aggregate\",\n            \"93 family 1 instance 0 repetition 0\",\n            \"92 family 1 instance 0 repetition 1\",\n            \"91 family 1 instance 0 aggregate\",\n            \"90 family 1 instance 1 repetition 0\",\n            \"89 family 1 instance 1 repetition 1\",\n            \"88 family 1 instance 1 aggregate\"\n        ]\n\n        for n in range(len(self.json['benchmarks']) ** 2):\n            random.shuffle(self.json['benchmarks'])\n            sorted_benchmarks = util.sort_benchmark_results(self.json)[\n                'benchmarks']\n            self.assertEqual(len(expected_names), len(sorted_benchmarks))\n            for out, expected in zip(sorted_benchmarks, expected_names):\n                self.assertEqual(out['name'], expected)\n\n\ndef assert_utest(unittest_instance, lhs, rhs):\n    if lhs['utest']:\n        unittest_instance.assertAlmostEqual(\n            lhs['utest']['cpu_pvalue'],\n            rhs['utest']['cpu_pvalue'])\n        unittest_instance.assertAlmostEqual(\n            lhs['utest']['time_pvalue'],\n            rhs['utest']['time_pvalue'])\n        unittest_instance.assertEqual(\n            lhs['utest']['have_optimal_repetitions'],\n            rhs['utest']['have_optimal_repetitions'])\n    else:\n        # lhs is empty. assert if rhs is not.\n        unittest_instance.assertEqual(lhs['utest'], rhs['utest'])\n\n\ndef assert_measurements(unittest_instance, lhs, rhs):\n    for m1, m2 in zip(lhs['measurements'], rhs['measurements']):\n        unittest_instance.assertEqual(m1['real_time'], m2['real_time'])\n        unittest_instance.assertEqual(m1['cpu_time'], m2['cpu_time'])\n        # m1['time'] and m1['cpu'] hold values which are being calculated,\n        # and therefore we must use almost-equal pattern.\n        unittest_instance.assertAlmostEqual(m1['time'], m2['time'], places=4)\n        unittest_instance.assertAlmostEqual(m1['cpu'], m2['cpu'], places=4)\n\n\nif __name__ == '__main__':\n    unittest.main()\n\n# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4\n# kate: tab-width: 4; replace-tabs on; indent-width 4; tab-indents: off;\n# kate: indent-mode python; remove-trailing-spaces modified;\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/tools/gbench/util.py",
    "content": "\"\"\"util.py - General utilities for running, loading, and processing benchmarks\n\"\"\"\nimport json\nimport os\nimport re\nimport subprocess\nimport sys\nimport tempfile\n\n\n# Input file type enumeration\nIT_Invalid = 0\nIT_JSON = 1\nIT_Executable = 2\n\n_num_magic_bytes = 2 if sys.platform.startswith('win') else 4\n\n\ndef is_executable_file(filename):\n    \"\"\"\n    Return 'True' if 'filename' names a valid file which is likely\n    an executable. A file is considered an executable if it starts with the\n    magic bytes for a EXE, Mach O, or ELF file.\n    \"\"\"\n    if not os.path.isfile(filename):\n        return False\n    with open(filename, mode='rb') as f:\n        magic_bytes = f.read(_num_magic_bytes)\n    if sys.platform == 'darwin':\n        return magic_bytes in [\n            b'\\xfe\\xed\\xfa\\xce',  # MH_MAGIC\n            b'\\xce\\xfa\\xed\\xfe',  # MH_CIGAM\n            b'\\xfe\\xed\\xfa\\xcf',  # MH_MAGIC_64\n            b'\\xcf\\xfa\\xed\\xfe',  # MH_CIGAM_64\n            b'\\xca\\xfe\\xba\\xbe',  # FAT_MAGIC\n            b'\\xbe\\xba\\xfe\\xca'   # FAT_CIGAM\n        ]\n    elif sys.platform.startswith('win'):\n        return magic_bytes == b'MZ'\n    else:\n        return magic_bytes == b'\\x7FELF'\n\n\ndef is_json_file(filename):\n    \"\"\"\n    Returns 'True' if 'filename' names a valid JSON output file.\n    'False' otherwise.\n    \"\"\"\n    try:\n        with open(filename, 'r') as f:\n            json.load(f)\n        return True\n    except BaseException:\n        pass\n    return False\n\n\ndef classify_input_file(filename):\n    \"\"\"\n    Return a tuple (type, msg) where 'type' specifies the classified type\n    of 'filename'. If 'type' is 'IT_Invalid' then 'msg' is a human readable\n    string representing the error.\n    \"\"\"\n    ftype = IT_Invalid\n    err_msg = None\n    if not os.path.exists(filename):\n        err_msg = \"'%s' does not exist\" % filename\n    elif not os.path.isfile(filename):\n        err_msg = \"'%s' does not name a file\" % filename\n    elif is_executable_file(filename):\n        ftype = IT_Executable\n    elif is_json_file(filename):\n        ftype = IT_JSON\n    else:\n        err_msg = \"'%s' does not name a valid benchmark executable or JSON file\" % filename\n    return ftype, err_msg\n\n\ndef check_input_file(filename):\n    \"\"\"\n    Classify the file named by 'filename' and return the classification.\n    If the file is classified as 'IT_Invalid' print an error message and exit\n    the program.\n    \"\"\"\n    ftype, msg = classify_input_file(filename)\n    if ftype == IT_Invalid:\n        print(\"Invalid input file: %s\" % msg)\n        sys.exit(1)\n    return ftype\n\n\ndef find_benchmark_flag(prefix, benchmark_flags):\n    \"\"\"\n    Search the specified list of flags for a flag matching `<prefix><arg>` and\n    if it is found return the arg it specifies. If specified more than once the\n    last value is returned. If the flag is not found None is returned.\n    \"\"\"\n    assert prefix.startswith('--') and prefix.endswith('=')\n    result = None\n    for f in benchmark_flags:\n        if f.startswith(prefix):\n            result = f[len(prefix):]\n    return result\n\n\ndef remove_benchmark_flags(prefix, benchmark_flags):\n    \"\"\"\n    Return a new list containing the specified benchmark_flags except those\n    with the specified prefix.\n    \"\"\"\n    assert prefix.startswith('--') and prefix.endswith('=')\n    return [f for f in benchmark_flags if not f.startswith(prefix)]\n\n\ndef load_benchmark_results(fname, benchmark_filter):\n    \"\"\"\n    Read benchmark output from a file and return the JSON object.\n\n    Apply benchmark_filter, a regular expression, with nearly the same\n    semantics of the --benchmark_filter argument.  May be None.\n    Note: the Python regular expression engine is used instead of the\n    one used by the C++ code, which may produce different results\n    in complex cases.\n\n    REQUIRES: 'fname' names a file containing JSON benchmark output.\n    \"\"\"\n    def benchmark_wanted(benchmark):\n        if benchmark_filter is None:\n            return True\n        name = benchmark.get('run_name', None) or benchmark['name']\n        if re.search(benchmark_filter, name):\n            return True\n        return False\n\n    with open(fname, 'r') as f:\n        results = json.load(f)\n        if 'benchmarks' in results:\n            results['benchmarks'] = list(filter(benchmark_wanted,\n                                                results['benchmarks']))\n        return results\n\n\ndef sort_benchmark_results(result):\n    benchmarks = result['benchmarks']\n\n    # From inner key to the outer key!\n    benchmarks = sorted(\n        benchmarks, key=lambda benchmark: benchmark['repetition_index'] if 'repetition_index' in benchmark else -1)\n    benchmarks = sorted(\n        benchmarks, key=lambda benchmark: 1 if 'run_type' in benchmark and benchmark['run_type'] == \"aggregate\" else 0)\n    benchmarks = sorted(\n        benchmarks, key=lambda benchmark: benchmark['per_family_instance_index'] if 'per_family_instance_index' in benchmark else -1)\n    benchmarks = sorted(\n        benchmarks, key=lambda benchmark: benchmark['family_index'] if 'family_index' in benchmark else -1)\n\n    result['benchmarks'] = benchmarks\n    return result\n\n\ndef run_benchmark(exe_name, benchmark_flags):\n    \"\"\"\n    Run a benchmark specified by 'exe_name' with the specified\n    'benchmark_flags'. The benchmark is run directly as a subprocess to preserve\n    real time console output.\n    RETURNS: A JSON object representing the benchmark output\n    \"\"\"\n    output_name = find_benchmark_flag('--benchmark_out=',\n                                      benchmark_flags)\n    is_temp_output = False\n    if output_name is None:\n        is_temp_output = True\n        thandle, output_name = tempfile.mkstemp()\n        os.close(thandle)\n        benchmark_flags = list(benchmark_flags) + \\\n            ['--benchmark_out=%s' % output_name]\n\n    cmd = [exe_name] + benchmark_flags\n    print(\"RUNNING: %s\" % ' '.join(cmd))\n    exitCode = subprocess.call(cmd)\n    if exitCode != 0:\n        print('TEST FAILED...')\n        sys.exit(exitCode)\n    json_res = load_benchmark_results(output_name, None)\n    if is_temp_output:\n        os.unlink(output_name)\n    return json_res\n\n\ndef run_or_load_benchmark(filename, benchmark_flags):\n    \"\"\"\n    Get the results for a specified benchmark. If 'filename' specifies\n    an executable benchmark then the results are generated by running the\n    benchmark. Otherwise 'filename' must name a valid JSON output file,\n    which is loaded and the result returned.\n    \"\"\"\n    ftype = check_input_file(filename)\n    if ftype == IT_JSON:\n        benchmark_filter = find_benchmark_flag('--benchmark_filter=',\n                                               benchmark_flags)\n        return load_benchmark_results(filename, benchmark_filter)\n    if ftype == IT_Executable:\n        return run_benchmark(filename, benchmark_flags)\n    raise ValueError('Unknown file type %s' % ftype)\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/tools/libpfm.BUILD.bazel",
    "content": "# Build rule for libpfm, which is required to collect performance counters for\n# BENCHMARK_ENABLE_LIBPFM builds.\n\nload(\"@rules_foreign_cc//foreign_cc:defs.bzl\", \"make\")\n\nfilegroup(\n    name = \"pfm_srcs\",\n    srcs = glob([\"**\"]),\n)\n\nmake(\n    name = \"libpfm\",\n    lib_source = \":pfm_srcs\",\n    lib_name = \"libpfm\",\n    copts = [\n        \"-Wno-format-truncation\",\n        \"-Wno-use-after-free\",\n    ],\n    visibility = [\n        \"//visibility:public\",\n    ],\n)\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/tools/requirements.txt",
    "content": "numpy == 1.25\nscipy == 1.5.4\n"
  },
  {
    "path": "3rd/benchmark-1.8.2/tools/strip_asm.py",
    "content": "#!/usr/bin/env python3\n\n\"\"\"\nstrip_asm.py - Cleanup ASM output for the specified file\n\"\"\"\n\nfrom argparse import ArgumentParser\nimport sys\nimport os\nimport re\n\ndef find_used_labels(asm):\n    found = set()\n    label_re = re.compile(\"\\s*j[a-z]+\\s+\\.L([a-zA-Z0-9][a-zA-Z0-9_]*)\")\n    for l in asm.splitlines():\n        m = label_re.match(l)\n        if m:\n            found.add('.L%s' % m.group(1))\n    return found\n\n\ndef normalize_labels(asm):\n    decls = set()\n    label_decl = re.compile(\"^[.]{0,1}L([a-zA-Z0-9][a-zA-Z0-9_]*)(?=:)\")\n    for l in asm.splitlines():\n        m = label_decl.match(l)\n        if m:\n            decls.add(m.group(0))\n    if len(decls) == 0:\n        return asm\n    needs_dot = next(iter(decls))[0] != '.'\n    if not needs_dot:\n        return asm\n    for ld in decls:\n        asm = re.sub(\"(^|\\s+)\" + ld + \"(?=:|\\s)\", '\\\\1.' + ld, asm)\n    return asm\n\n\ndef transform_labels(asm):\n    asm = normalize_labels(asm)\n    used_decls = find_used_labels(asm)\n    new_asm = ''\n    label_decl = re.compile(\"^\\.L([a-zA-Z0-9][a-zA-Z0-9_]*)(?=:)\")\n    for l in asm.splitlines():\n        m = label_decl.match(l)\n        if not m or m.group(0) in used_decls:\n            new_asm += l\n            new_asm += '\\n'\n    return new_asm\n\n\ndef is_identifier(tk):\n    if len(tk) == 0:\n        return False\n    first = tk[0]\n    if not first.isalpha() and first != '_':\n        return False\n    for i in range(1, len(tk)):\n        c = tk[i]\n        if not c.isalnum() and c != '_':\n            return False\n    return True\n\ndef process_identifiers(l):\n    \"\"\"\n    process_identifiers - process all identifiers and modify them to have\n    consistent names across all platforms; specifically across ELF and MachO.\n    For example, MachO inserts an additional understore at the beginning of\n    names. This function removes that.\n    \"\"\"\n    parts = re.split(r'([a-zA-Z0-9_]+)', l)\n    new_line = ''\n    for tk in parts:\n        if is_identifier(tk):\n            if tk.startswith('__Z'):\n                tk = tk[1:]\n            elif tk.startswith('_') and len(tk) > 1 and \\\n                    tk[1].isalpha() and tk[1] != 'Z':\n                tk = tk[1:]\n        new_line += tk\n    return new_line\n\n\ndef process_asm(asm):\n    \"\"\"\n    Strip the ASM of unwanted directives and lines\n    \"\"\"\n    new_contents = ''\n    asm = transform_labels(asm)\n\n    # TODO: Add more things we want to remove\n    discard_regexes = [\n        re.compile(\"\\s+\\..*$\"), # directive\n        re.compile(\"\\s*#(NO_APP|APP)$\"), #inline ASM\n        re.compile(\"\\s*#.*$\"), # comment line\n        re.compile(\"\\s*\\.globa?l\\s*([.a-zA-Z_][a-zA-Z0-9$_.]*)\"), #global directive\n        re.compile(\"\\s*\\.(string|asciz|ascii|[1248]?byte|short|word|long|quad|value|zero)\"),\n    ]\n    keep_regexes = [\n\n    ]\n    fn_label_def = re.compile(\"^[a-zA-Z_][a-zA-Z0-9_.]*:\")\n    for l in asm.splitlines():\n        # Remove Mach-O attribute\n        l = l.replace('@GOTPCREL', '')\n        add_line = True\n        for reg in discard_regexes:\n            if reg.match(l) is not None:\n                add_line = False\n                break\n        for reg in keep_regexes:\n            if reg.match(l) is not None:\n                add_line = True\n                break\n        if add_line:\n            if fn_label_def.match(l) and len(new_contents) != 0:\n                new_contents += '\\n'\n            l = process_identifiers(l)\n            new_contents += l\n            new_contents += '\\n'\n    return new_contents\n\ndef main():\n    parser = ArgumentParser(\n        description='generate a stripped assembly file')\n    parser.add_argument(\n        'input', metavar='input', type=str, nargs=1,\n        help='An input assembly file')\n    parser.add_argument(\n        'out', metavar='output', type=str, nargs=1,\n        help='The output file')\n    args, unknown_args = parser.parse_known_args()\n    input = args.input[0]\n    output = args.out[0]\n    if not os.path.isfile(input):\n        print((\"ERROR: input file '%s' does not exist\") % input)\n        sys.exit(1)\n    contents = None\n    with open(input, 'r') as f:\n        contents = f.read()\n    new_contents = process_asm(contents)\n    with open(output, 'w') as f:\n        f.write(new_contents)\n\n\nif __name__ == '__main__':\n    main()\n\n# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4\n# kate: tab-width: 4; replace-tabs on; indent-width 4; tab-indents: off;\n# kate: indent-mode python; remove-trailing-spaces modified;\n"
  },
  {
    "path": "3rd/googletest-1.12.1/.clang-format",
    "content": "# Run manually to reformat a file:\n# clang-format -i --style=file <file>\nLanguage:        Cpp\nBasedOnStyle:  Google\n"
  },
  {
    "path": "3rd/googletest-1.12.1/.github/ISSUE_TEMPLATE/00-bug_report.md",
    "content": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: ''\nlabels: 'bug'\nassignees: ''\n---\n\n**Describe the bug**\n\nInclude a clear and concise description of what the problem is, including what\nyou expected to happen, and what actually happened.\n\n**Steps to reproduce the bug**\n\nIt's important that we are able to reproduce the problem that you are\nexperiencing. Please provide all code and relevant steps to reproduce the\nproblem, including your `BUILD`/`CMakeLists.txt` file and build commands. Links\nto a GitHub branch or [godbolt.org](https://godbolt.org/) that demonstrate the\nproblem are also helpful.\n\n**Does the bug persist in the most recent commit?**\n\nWe recommend using the latest commit in the master branch in your projects.\n\n**What operating system and version are you using?**\n\nIf you are using a Linux distribution please include the name and version of the\ndistribution as well.\n\n**What compiler and version are you using?**\n\nPlease include the output of `gcc -v` or `clang -v`, or the equivalent for your\ncompiler.\n\n**What build system are you using?**\n\nPlease include the output of `bazel --version` or `cmake --version`, or the\nequivalent for your build system.\n\n**Additional context**\n\nAdd any other context about the problem here.\n"
  },
  {
    "path": "3rd/googletest-1.12.1/.github/ISSUE_TEMPLATE/10-feature_request.md",
    "content": "---\nname: Feature request\nabout: Propose a new feature\ntitle: ''\nlabels: 'enhancement'\nassignees: ''\n---\n\n**Does the feature exist in the most recent commit?**\n\nWe recommend using the latest commit from GitHub in your projects.\n\n**Why do we need this feature?**\n\nIdeally, explain why a combination of existing features cannot be used instead.\n\n**Describe the proposal**\n\nInclude a detailed description of the feature, with usage examples.\n\n**Is the feature specific to an operating system, compiler, or build system version?**\n\nIf it is, please specify which versions.\n\n"
  },
  {
    "path": "3rd/googletest-1.12.1/.github/ISSUE_TEMPLATE/config.yml",
    "content": "blank_issues_enabled: false\n"
  },
  {
    "path": "3rd/googletest-1.12.1/.github/workflows/gtest-ci.yml",
    "content": "name: ci\n\non:\n  push:\n  pull_request:\n\njobs:\n  Linux:\n    runs-on: ubuntu-latest\n    steps:\n\n    - uses: actions/checkout@v2\n      with:\n        fetch-depth: 0\n\n    - name: Tests\n      run: bazel test --test_output=errors //...\n\n  MacOs:\n    runs-on: macos-latest\n    steps:\n\n    - uses: actions/checkout@v2\n      with:\n        fetch-depth: 0\n\n    - name: Tests\n      run: bazel test --test_output=errors //...\n\n\n  Windows:\n    runs-on: windows-latest\n    steps:\n\n    - uses: actions/checkout@v2\n      with:\n        fetch-depth: 0\n\n    - name: Tests\n      run: bazel test --test_output=errors //...\n"
  },
  {
    "path": "3rd/googletest-1.12.1/.gitignore",
    "content": "# Ignore CI build directory\nbuild/\nxcuserdata\ncmake-build-debug/\n.idea/\nbazel-bin\nbazel-genfiles\nbazel-googletest\nbazel-out\nbazel-testlogs\n# python\n*.pyc\n\n# Visual Studio files\n.vs\n*.sdf\n*.opensdf\n*.VC.opendb\n*.suo\n*.user\n_ReSharper.Caches/\nWin32-Debug/\nWin32-Release/\nx64-Debug/\nx64-Release/\n\n# Ignore autoconf / automake files\nMakefile.in\naclocal.m4\nconfigure\nbuild-aux/\nautom4te.cache/\ngoogletest/m4/libtool.m4\ngoogletest/m4/ltoptions.m4\ngoogletest/m4/ltsugar.m4\ngoogletest/m4/ltversion.m4\ngoogletest/m4/lt~obsolete.m4\ngooglemock/m4\n\n# Ignore generated directories.\ngooglemock/fused-src/\ngoogletest/fused-src/\n\n# macOS files\n.DS_Store\ngoogletest/.DS_Store\ngoogletest/xcode/.DS_Store\n\n# Ignore cmake generated directories and files.\nCMakeFiles\nCTestTestfile.cmake\nMakefile\ncmake_install.cmake\ngooglemock/CMakeFiles\ngooglemock/CTestTestfile.cmake\ngooglemock/Makefile\ngooglemock/cmake_install.cmake\ngooglemock/gtest\n/bin\n/googlemock/gmock.dir\n/googlemock/gmock_main.dir\n/googlemock/RUN_TESTS.vcxproj.filters\n/googlemock/RUN_TESTS.vcxproj\n/googlemock/INSTALL.vcxproj.filters\n/googlemock/INSTALL.vcxproj\n/googlemock/gmock_main.vcxproj.filters\n/googlemock/gmock_main.vcxproj\n/googlemock/gmock.vcxproj.filters\n/googlemock/gmock.vcxproj\n/googlemock/gmock.sln\n/googlemock/ALL_BUILD.vcxproj.filters\n/googlemock/ALL_BUILD.vcxproj\n/lib\n/Win32\n/ZERO_CHECK.vcxproj.filters\n/ZERO_CHECK.vcxproj\n/RUN_TESTS.vcxproj.filters\n/RUN_TESTS.vcxproj\n/INSTALL.vcxproj.filters\n/INSTALL.vcxproj\n/googletest-distribution.sln\n/CMakeCache.txt\n/ALL_BUILD.vcxproj.filters\n/ALL_BUILD.vcxproj\n"
  },
  {
    "path": "3rd/googletest-1.12.1/BUILD.bazel",
    "content": "# Copyright 2017 Google Inc.\n# All Rights Reserved.\n#\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n#   Bazel Build for Google C++ Testing Framework(Google Test)\n\npackage(default_visibility = [\"//visibility:public\"])\n\nlicenses([\"notice\"])\n\nexports_files([\"LICENSE\"])\n\nconfig_setting(\n    name = \"qnx\",\n    constraint_values = [\"@platforms//os:qnx\"],\n)\n\nconfig_setting(\n    name = \"windows\",\n    constraint_values = [\"@platforms//os:windows\"],\n)\n\nconfig_setting(\n    name = \"freebsd\",\n    constraint_values = [\"@platforms//os:freebsd\"],\n)\n\nconfig_setting(\n    name = \"openbsd\",\n    constraint_values = [\"@platforms//os:openbsd\"],\n)\n\nconfig_setting(\n    name = \"msvc_compiler\",\n    flag_values = {\n        \"@bazel_tools//tools/cpp:compiler\": \"msvc-cl\",\n    },\n    visibility = [\":__subpackages__\"],\n)\n\nconfig_setting(\n    name = \"has_absl\",\n    values = {\"define\": \"absl=1\"},\n)\n\n# Library that defines the FRIEND_TEST macro.\ncc_library(\n    name = \"gtest_prod\",\n    hdrs = [\"googletest/include/gtest/gtest_prod.h\"],\n    includes = [\"googletest/include\"],\n)\n\n# Google Test including Google Mock\ncc_library(\n    name = \"gtest\",\n    srcs = glob(\n        include = [\n            \"googletest/src/*.cc\",\n            \"googletest/src/*.h\",\n            \"googletest/include/gtest/**/*.h\",\n            \"googlemock/src/*.cc\",\n            \"googlemock/include/gmock/**/*.h\",\n        ],\n        exclude = [\n            \"googletest/src/gtest-all.cc\",\n            \"googletest/src/gtest_main.cc\",\n            \"googlemock/src/gmock-all.cc\",\n            \"googlemock/src/gmock_main.cc\",\n        ],\n    ),\n    hdrs = glob([\n        \"googletest/include/gtest/*.h\",\n        \"googlemock/include/gmock/*.h\",\n    ]),\n    copts = select({\n        \":qnx\": [],\n        \":windows\": [],\n        \"//conditions:default\": [\"-pthread\"],\n    }),\n    defines = select({\n        \":has_absl\": [\"GTEST_HAS_ABSL=1\"],\n        \"//conditions:default\": [],\n    }),\n    features = select({\n        \":windows\": [\"windows_export_all_symbols\"],\n        \"//conditions:default\": [],\n    }),\n    includes = [\n        \"googlemock\",\n        \"googlemock/include\",\n        \"googletest\",\n        \"googletest/include\",\n    ],\n    linkopts = select({\n        \":qnx\": [\"-lregex\"],\n        \":windows\": [],\n        \":freebsd\": [\n            \"-lm\",\n            \"-pthread\",\n        ],\n        \":openbsd\": [\n            \"-lm\",\n            \"-pthread\",\n        ],\n        \"//conditions:default\": [\"-pthread\"],\n    }),\n    deps = select({\n        \":has_absl\": [\n            \"@com_google_absl//absl/debugging:failure_signal_handler\",\n            \"@com_google_absl//absl/debugging:stacktrace\",\n            \"@com_google_absl//absl/debugging:symbolize\",\n            \"@com_google_absl//absl/flags:flag\",\n            \"@com_google_absl//absl/flags:parse\",\n            \"@com_google_absl//absl/flags:reflection\",\n            \"@com_google_absl//absl/flags:usage\",\n            \"@com_google_absl//absl/strings\",\n            \"@com_google_absl//absl/types:any\",\n            \"@com_google_absl//absl/types:optional\",\n            \"@com_google_absl//absl/types:variant\",\n            \"@com_googlesource_code_re2//:re2\",\n        ],\n        \"//conditions:default\": [],\n    }),\n)\n\ncc_library(\n    name = \"gtest_main\",\n    srcs = [\"googlemock/src/gmock_main.cc\"],\n    features = select({\n        \":windows\": [\"windows_export_all_symbols\"],\n        \"//conditions:default\": [],\n    }),\n    deps = [\":gtest\"],\n)\n\n# The following rules build samples of how to use gTest.\ncc_library(\n    name = \"gtest_sample_lib\",\n    srcs = [\n        \"googletest/samples/sample1.cc\",\n        \"googletest/samples/sample2.cc\",\n        \"googletest/samples/sample4.cc\",\n    ],\n    hdrs = [\n        \"googletest/samples/prime_tables.h\",\n        \"googletest/samples/sample1.h\",\n        \"googletest/samples/sample2.h\",\n        \"googletest/samples/sample3-inl.h\",\n        \"googletest/samples/sample4.h\",\n    ],\n    features = select({\n        \":windows\": [\"windows_export_all_symbols\"],\n        \"//conditions:default\": [],\n    }),\n)\n\ncc_test(\n    name = \"gtest_samples\",\n    size = \"small\",\n    # All Samples except:\n    #   sample9 (main)\n    #   sample10 (main and takes a command line option and needs to be separate)\n    srcs = [\n        \"googletest/samples/sample1_unittest.cc\",\n        \"googletest/samples/sample2_unittest.cc\",\n        \"googletest/samples/sample3_unittest.cc\",\n        \"googletest/samples/sample4_unittest.cc\",\n        \"googletest/samples/sample5_unittest.cc\",\n        \"googletest/samples/sample6_unittest.cc\",\n        \"googletest/samples/sample7_unittest.cc\",\n        \"googletest/samples/sample8_unittest.cc\",\n    ],\n    linkstatic = 0,\n    deps = [\n        \"gtest_sample_lib\",\n        \":gtest_main\",\n    ],\n)\n\ncc_test(\n    name = \"sample9_unittest\",\n    size = \"small\",\n    srcs = [\"googletest/samples/sample9_unittest.cc\"],\n    deps = [\":gtest\"],\n)\n\ncc_test(\n    name = \"sample10_unittest\",\n    size = \"small\",\n    srcs = [\"googletest/samples/sample10_unittest.cc\"],\n    deps = [\":gtest\"],\n)\n"
  },
  {
    "path": "3rd/googletest-1.12.1/CMakeLists.txt",
    "content": "# Note: CMake support is community-based. The maintainers do not use CMake\n# internally.\n\ncmake_minimum_required(VERSION 3.5)\n\nif (POLICY CMP0048)\n  cmake_policy(SET CMP0048 NEW)\nendif (POLICY CMP0048)\n\nif (POLICY CMP0077)\n  cmake_policy(SET CMP0077 NEW)\nendif (POLICY CMP0077)\n\nproject(googletest-distribution)\nset(GOOGLETEST_VERSION 1.12.1)\n\nif(NOT CYGWIN AND NOT MSYS AND NOT ${CMAKE_SYSTEM_NAME} STREQUAL QNX)\n  set(CMAKE_CXX_EXTENSIONS OFF)\nendif()\n\nenable_testing()\n\ninclude(CMakeDependentOption)\ninclude(GNUInstallDirs)\n\n#Note that googlemock target already builds googletest\noption(BUILD_GMOCK \"Builds the googlemock subproject\" ON)\noption(INSTALL_GTEST \"Enable installation of googletest. (Projects embedding googletest may want to turn this OFF.)\" ON)\n\nif(BUILD_GMOCK)\n  add_subdirectory( googlemock )\nelse()\n  add_subdirectory( googletest )\nendif()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/CONTRIBUTING.md",
    "content": "# How to become a contributor and submit your own code\n\n## Contributor License Agreements\n\nWe'd love to accept your patches! Before we can take them, we have to jump a\ncouple of legal hurdles.\n\nPlease fill out either the individual or corporate Contributor License Agreement\n(CLA).\n\n*   If you are an individual writing original source code and you're sure you\n    own the intellectual property, then you'll need to sign an\n    [individual CLA](https://developers.google.com/open-source/cla/individual).\n*   If you work for a company that wants to allow you to contribute your work,\n    then you'll need to sign a\n    [corporate CLA](https://developers.google.com/open-source/cla/corporate).\n\nFollow either of the two links above to access the appropriate CLA and\ninstructions for how to sign and return it. Once we receive it, we'll be able to\naccept your pull requests.\n\n## Are you a Googler?\n\nIf you are a Googler, please make an attempt to submit an internal contribution\nrather than a GitHub Pull Request. If you are not able to submit internally, a\nPR is acceptable as an alternative.\n\n## Contributing A Patch\n\n1.  Submit an issue describing your proposed change to the\n    [issue tracker](https://github.com/google/googletest/issues).\n2.  Please don't mix more than one logical change per submittal, because it\n    makes the history hard to follow. If you want to make a change that doesn't\n    have a corresponding issue in the issue tracker, please create one.\n3.  Also, coordinate with team members that are listed on the issue in question.\n    This ensures that work isn't being duplicated and communicating your plan\n    early also generally leads to better patches.\n4.  If your proposed change is accepted, and you haven't already done so, sign a\n    Contributor License Agreement\n    ([see details above](#contributor-license-agreements)).\n5.  Fork the desired repo, develop and test your code changes.\n6.  Ensure that your code adheres to the existing style in the sample to which\n    you are contributing.\n7.  Ensure that your code has an appropriate set of unit tests which all pass.\n8.  Submit a pull request.\n\n## The Google Test and Google Mock Communities\n\nThe Google Test community exists primarily through the\n[discussion group](http://groups.google.com/group/googletestframework) and the\nGitHub repository. Likewise, the Google Mock community exists primarily through\ntheir own [discussion group](http://groups.google.com/group/googlemock). You are\ndefinitely encouraged to contribute to the discussion and you can also help us\nto keep the effectiveness of the group high by following and promoting the\nguidelines listed here.\n\n### Please Be Friendly\n\nShowing courtesy and respect to others is a vital part of the Google culture,\nand we strongly encourage everyone participating in Google Test development to\njoin us in accepting nothing less. Of course, being courteous is not the same as\nfailing to constructively disagree with each other, but it does mean that we\nshould be respectful of each other when enumerating the 42 technical reasons\nthat a particular proposal may not be the best choice. There's never a reason to\nbe antagonistic or dismissive toward anyone who is sincerely trying to\ncontribute to a discussion.\n\nSure, C++ testing is serious business and all that, but it's also a lot of fun.\nLet's keep it that way. Let's strive to be one of the friendliest communities in\nall of open source.\n\nAs always, discuss Google Test in the official GoogleTest discussion group. You\ndon't have to actually submit code in order to sign up. Your participation\nitself is a valuable contribution.\n\n## Style\n\nTo keep the source consistent, readable, diffable and easy to merge, we use a\nfairly rigid coding style, as defined by the\n[google-styleguide](https://github.com/google/styleguide) project. All patches\nwill be expected to conform to the style outlined\n[here](https://google.github.io/styleguide/cppguide.html). Use\n[.clang-format](https://github.com/google/googletest/blob/master/.clang-format)\nto check your formatting.\n\n## Requirements for Contributors\n\nIf you plan to contribute a patch, you need to build Google Test, Google Mock,\nand their own tests from a git checkout, which has further requirements:\n\n*   [Python](https://www.python.org/) v2.3 or newer (for running some of the\n    tests and re-generating certain source files from templates)\n*   [CMake](https://cmake.org/) v2.8.12 or newer\n\n## Developing Google Test and Google Mock\n\nThis section discusses how to make your own changes to the Google Test project.\n\n### Testing Google Test and Google Mock Themselves\n\nTo make sure your changes work as intended and don't break existing\nfunctionality, you'll want to compile and run Google Test and GoogleMock's own\ntests. For that you can use CMake:\n\n    mkdir mybuild\n    cd mybuild\n    cmake -Dgtest_build_tests=ON -Dgmock_build_tests=ON ${GTEST_REPO_DIR}\n\nTo choose between building only Google Test or Google Mock, you may modify your\ncmake command to be one of each\n\n    cmake -Dgtest_build_tests=ON ${GTEST_DIR} # sets up Google Test tests\n    cmake -Dgmock_build_tests=ON ${GMOCK_DIR} # sets up Google Mock tests\n\nMake sure you have Python installed, as some of Google Test's tests are written\nin Python. If the cmake command complains about not being able to find Python\n(`Could NOT find PythonInterp (missing: PYTHON_EXECUTABLE)`), try telling it\nexplicitly where your Python executable can be found:\n\n    cmake -DPYTHON_EXECUTABLE=path/to/python ...\n\nNext, you can build Google Test and / or Google Mock and all desired tests. On\n\\*nix, this is usually done by\n\n    make\n\nTo run the tests, do\n\n    make test\n\nAll tests should pass.\n"
  },
  {
    "path": "3rd/googletest-1.12.1/CONTRIBUTORS",
    "content": "# This file contains a list of people who've made non-trivial\n# contribution to the Google C++ Testing Framework project.  People\n# who commit code to the project are encouraged to add their names\n# here.  Please keep the list sorted by first names.\n\nAjay Joshi <jaj@google.com>\nBalázs Dán <balazs.dan@gmail.com>\nBenoit Sigoure <tsuna@google.com>\nBharat Mediratta <bharat@menalto.com>\nBogdan Piloca <boo@google.com>\nChandler Carruth <chandlerc@google.com>\nChris Prince <cprince@google.com>\nChris Taylor <taylorc@google.com>\nDan Egnor <egnor@google.com>\nDave MacLachlan <dmaclach@gmail.com>\nDavid Anderson <danderson@google.com>\nDean Sturtevant\nEric Roman <eroman@chromium.org>\nGene Volovich <gv@cite.com>\nHady Zalek <hady.zalek@gmail.com>\nHal Burch <gmock@hburch.com>\nJeffrey Yasskin <jyasskin@google.com>\nJim Keller <jimkeller@google.com>\nJoe Walnes <joe@truemesh.com>\nJon Wray <jwray@google.com>\nJói Sigurðsson <joi@google.com>\nKeir Mierle <mierle@gmail.com>\nKeith Ray <keith.ray@gmail.com>\nKenton Varda <kenton@google.com>\nKostya Serebryany <kcc@google.com>\nKrystian Kuzniarek <krystian.kuzniarek@gmail.com>\nLev Makhlis\nManuel Klimek <klimek@google.com>\nMario Tanev <radix@google.com>\nMark Paskin\nMarkus Heule <markus.heule@gmail.com>\nMartijn Vels <mvels@google.com>\nMatthew Simmons <simmonmt@acm.org>\nMika Raento <mikie@iki.fi>\nMike Bland <mbland@google.com>\nMiklós Fazekas <mfazekas@szemafor.com>\nNeal Norwitz <nnorwitz@gmail.com>\nNermin Ozkiranartli <nermin@google.com>\nOwen Carlsen <ocarlsen@google.com>\nPaneendra Ba <paneendra@google.com>\nPasi Valminen <pasi.valminen@gmail.com>\nPatrick Hanna <phanna@google.com>\nPatrick Riley <pfr@google.com>\nPaul Menage <menage@google.com>\nPeter Kaminski <piotrk@google.com>\nPiotr Kaminski <piotrk@google.com>\nPreston Jackson <preston.a.jackson@gmail.com>\nRainer Klaffenboeck <rainer.klaffenboeck@dynatrace.com>\nRuss Cox <rsc@google.com>\nRuss Rufer <russ@pentad.com>\nSean Mcafee <eefacm@gmail.com>\nSigurður Ásgeirsson <siggi@google.com>\nSverre Sundsdal <sundsdal@gmail.com>\nSzymon Sobik <sobik.szymon@gmail.com>\nTakeshi Yoshino <tyoshino@google.com>\nTracy Bialik <tracy@pentad.com>\nVadim Berman <vadimb@google.com>\nVlad Losev <vladl@google.com>\nWolfgang Klier <wklier@google.com>\nZhanyong Wan <wan@google.com>\n"
  },
  {
    "path": "3rd/googletest-1.12.1/LICENSE",
    "content": "Copyright 2008, Google Inc.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n    * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n    * Neither the name of Google Inc. nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
  },
  {
    "path": "3rd/googletest-1.12.1/README.md",
    "content": "# GoogleTest\n\n### Announcements\n\n#### Live at Head\n\nGoogleTest now follows the\n[Abseil Live at Head philosophy](https://abseil.io/about/philosophy#upgrade-support).\nWe recommend\n[updating to the latest commit in the `main` branch as often as possible](https://github.com/abseil/abseil-cpp/blob/master/FAQ.md#what-is-live-at-head-and-how-do-i-do-it).\n\n#### Documentation Updates\n\nOur documentation is now live on GitHub Pages at\nhttps://google.github.io/googletest/. We recommend browsing the documentation on\nGitHub Pages rather than directly in the repository.\n\n#### Release 1.11.0\n\n[Release 1.11.0](https://github.com/google/googletest/releases/tag/release-1.11.0)\nis now available.\n\n#### Coming Soon\n\n*   We are planning to take a dependency on\n    [Abseil](https://github.com/abseil/abseil-cpp).\n*   More documentation improvements are planned.\n\n## Welcome to **GoogleTest**, Google's C++ test framework!\n\nThis repository is a merger of the formerly separate GoogleTest and GoogleMock\nprojects. These were so closely related that it makes sense to maintain and\nrelease them together.\n\n### Getting Started\n\nSee the [GoogleTest User's Guide](https://google.github.io/googletest/) for\ndocumentation. We recommend starting with the\n[GoogleTest Primer](https://google.github.io/googletest/primer.html).\n\nMore information about building GoogleTest can be found at\n[googletest/README.md](googletest/README.md).\n\n## Features\n\n*   An [xUnit](https://en.wikipedia.org/wiki/XUnit) test framework.\n*   Test discovery.\n*   A rich set of assertions.\n*   User-defined assertions.\n*   Death tests.\n*   Fatal and non-fatal failures.\n*   Value-parameterized tests.\n*   Type-parameterized tests.\n*   Various options for running the tests.\n*   XML test report generation.\n\n## Supported Platforms\n\nGoogleTest requires a codebase and compiler compliant with the C++11 standard or\nnewer.\n\nThe GoogleTest code is officially supported on the following platforms.\nOperating systems or tools not listed below are community-supported. For\ncommunity-supported platforms, patches that do not complicate the code may be\nconsidered.\n\nIf you notice any problems on your platform, please file an issue on the\n[GoogleTest GitHub Issue Tracker](https://github.com/google/googletest/issues).\nPull requests containing fixes are welcome!\n\n### Operating Systems\n\n*   Linux\n*   macOS\n*   Windows\n\n### Compilers\n\n*   gcc 5.0+\n*   clang 5.0+\n*   MSVC 2015+\n\n**macOS users:** Xcode 9.3+ provides clang 5.0+.\n\n### Build Systems\n\n*   [Bazel](https://bazel.build/)\n*   [CMake](https://cmake.org/)\n\n**Note:** Bazel is the build system used by the team internally and in tests.\nCMake is supported on a best-effort basis and by the community.\n\n## Who Is Using GoogleTest?\n\nIn addition to many internal projects at Google, GoogleTest is also used by the\nfollowing notable projects:\n\n*   The [Chromium projects](http://www.chromium.org/) (behind the Chrome browser\n    and Chrome OS).\n*   The [LLVM](http://llvm.org/) compiler.\n*   [Protocol Buffers](https://github.com/google/protobuf), Google's data\n    interchange format.\n*   The [OpenCV](http://opencv.org/) computer vision library.\n\n## Related Open Source Projects\n\n[GTest Runner](https://github.com/nholthaus/gtest-runner) is a Qt5 based\nautomated test-runner and Graphical User Interface with powerful features for\nWindows and Linux platforms.\n\n[GoogleTest UI](https://github.com/ospector/gtest-gbar) is a test runner that\nruns your test binary, allows you to track its progress via a progress bar, and\ndisplays a list of test failures. Clicking on one shows failure text. GoogleTest\nUI is written in C#.\n\n[GTest TAP Listener](https://github.com/kinow/gtest-tap-listener) is an event\nlistener for GoogleTest that implements the\n[TAP protocol](https://en.wikipedia.org/wiki/Test_Anything_Protocol) for test\nresult output. If your test runner understands TAP, you may find it useful.\n\n[gtest-parallel](https://github.com/google/gtest-parallel) is a test runner that\nruns tests from your binary in parallel to provide significant speed-up.\n\n[GoogleTest Adapter](https://marketplace.visualstudio.com/items?itemName=DavidSchuldenfrei.gtest-adapter)\nis a VS Code extension allowing to view GoogleTest in a tree view and run/debug\nyour tests.\n\n[C++ TestMate](https://github.com/matepek/vscode-catch2-test-adapter) is a VS\nCode extension allowing to view GoogleTest in a tree view and run/debug your\ntests.\n\n[Cornichon](https://pypi.org/project/cornichon/) is a small Gherkin DSL parser\nthat generates stub code for GoogleTest.\n\n## Contributing Changes\n\nPlease read\n[`CONTRIBUTING.md`](https://github.com/google/googletest/blob/master/CONTRIBUTING.md)\nfor details on how to contribute to this project.\n\nHappy testing!\n"
  },
  {
    "path": "3rd/googletest-1.12.1/WORKSPACE",
    "content": "workspace(name = \"com_google_googletest\")\n\nload(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\n\nhttp_archive(\n    name = \"com_google_absl\",\n    sha256 = \"1a1745b5ee81392f5ea4371a4ca41e55d446eeaee122903b2eaffbd8a3b67a2b\",\n    strip_prefix = \"abseil-cpp-01cc6567cff77738e416a7ddc17de2d435a780ce\",\n    urls = [\"https://github.com/abseil/abseil-cpp/archive/01cc6567cff77738e416a7ddc17de2d435a780ce.zip\"],  # 2022-06-21T19:28:27Z\n)\n\n# Note this must use a commit from the `abseil` branch of the RE2 project.\n# https://github.com/google/re2/tree/abseil\nhttp_archive(\n    name = \"com_googlesource_code_re2\",\n    sha256 = \"0a890c2aa0bb05b2ce906a15efb520d0f5ad4c7d37b8db959c43772802991887\",\n    strip_prefix = \"re2-a427f10b9fb4622dd6d8643032600aa1b50fbd12\",\n    urls = [\"https://github.com/google/re2/archive/a427f10b9fb4622dd6d8643032600aa1b50fbd12.zip\"],  # 2022-06-09\n)\n\nhttp_archive(\n    name = \"rules_python\",\n    sha256 = \"0b460f17771258341528753b1679335b629d1d25e3af28eda47d009c103a6e15\",\n    strip_prefix = \"rules_python-aef17ad72919d184e5edb7abf61509eb78e57eda\",\n    urls = [\"https://github.com/bazelbuild/rules_python/archive/aef17ad72919d184e5edb7abf61509eb78e57eda.zip\"],  # 2022-06-21T23:44:47Z\n)\n\nhttp_archive(\n    name = \"bazel_skylib\",\n    urls = [\"https://github.com/bazelbuild/bazel-skylib/releases/download/1.2.1/bazel-skylib-1.2.1.tar.gz\"],\n    sha256 = \"f7be3474d42aae265405a592bb7da8e171919d74c16f082a5457840f06054728\",\n)\n\nhttp_archive(\n    name = \"platforms\",\n    sha256 = \"a879ea428c6d56ab0ec18224f976515948822451473a80d06c2e50af0bbe5121\",\n    strip_prefix = \"platforms-da5541f26b7de1dc8e04c075c99df5351742a4a2\",\n    urls = [\"https://github.com/bazelbuild/platforms/archive/da5541f26b7de1dc8e04c075c99df5351742a4a2.zip\"],  # 2022-05-27\n)\n"
  },
  {
    "path": "3rd/googletest-1.12.1/ci/linux-presubmit.sh",
    "content": "#!/bin/bash\n#\n# Copyright 2020, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nset -euox pipefail\n\nreadonly LINUX_LATEST_CONTAINER=\"gcr.io/google.com/absl-177019/linux_hybrid-latest:20220217\"\nreadonly LINUX_GCC_FLOOR_CONTAINER=\"gcr.io/google.com/absl-177019/linux_gcc-floor:20220621\"\n\nif [[ -z ${GTEST_ROOT:-} ]]; then\n  GTEST_ROOT=\"$(realpath $(dirname ${0})/..)\"\nfi\n\nif [[ -z ${STD:-} ]]; then\n  STD=\"c++11 c++14 c++17 c++20\"\nfi\n\n# Test the CMake build\nfor cc in /usr/local/bin/gcc /opt/llvm/clang/bin/clang; do\n  for cmake_off_on in OFF ON; do\n    time docker run \\\n      --volume=\"${GTEST_ROOT}:/src:ro\" \\\n      --tmpfs=\"/build:exec\" \\\n      --workdir=\"/build\" \\\n      --rm \\\n      --env=\"CC=${cc}\" \\\n      --env=\"CXX_FLAGS=\\\"-Werror -Wdeprecated\\\"\" \\\n      ${LINUX_LATEST_CONTAINER} \\\n      /bin/bash -c \"\n        cmake /src \\\n          -DCMAKE_CXX_STANDARD=11 \\\n          -Dgtest_build_samples=ON \\\n          -Dgtest_build_tests=ON \\\n          -Dgmock_build_tests=ON \\\n          -Dcxx_no_exception=${cmake_off_on} \\\n          -Dcxx_no_rtti=${cmake_off_on} && \\\n        make -j$(nproc) && \\\n        ctest -j$(nproc) --output-on-failure\"\n  done\ndone\n\n# Do one test with an older version of GCC\ntime docker run \\\n  --volume=\"${GTEST_ROOT}:/src:ro\" \\\n  --workdir=\"/src\" \\\n  --rm \\\n  --env=\"CC=/usr/local/bin/gcc\" \\\n  ${LINUX_GCC_FLOOR_CONTAINER} \\\n    /usr/local/bin/bazel test ... \\\n      --copt=\"-Wall\" \\\n      --copt=\"-Werror\" \\\n      --copt=\"-Wuninitialized\" \\\n      --copt=\"-Wno-error=pragmas\" \\\n      --distdir=\"/bazel-distdir\" \\\n      --keep_going \\\n      --show_timestamps \\\n      --test_output=errors\n\n# Test GCC\nfor std in ${STD}; do\n  for absl in 0 1; do\n    time docker run \\\n      --volume=\"${GTEST_ROOT}:/src:ro\" \\\n      --workdir=\"/src\" \\\n      --rm \\\n      --env=\"CC=/usr/local/bin/gcc\" \\\n      --env=\"BAZEL_CXXOPTS=-std=${std}\" \\\n      ${LINUX_LATEST_CONTAINER} \\\n      /usr/local/bin/bazel test ... \\\n        --copt=\"-Wall\" \\\n        --copt=\"-Werror\" \\\n        --copt=\"-Wuninitialized\" \\\n        --define=\"absl=${absl}\" \\\n        --distdir=\"/bazel-distdir\" \\\n        --keep_going \\\n        --show_timestamps \\\n        --test_output=errors\n  done\ndone\n\n# Test Clang\nfor std in ${STD}; do\n  for absl in 0 1; do\n    time docker run \\\n      --volume=\"${GTEST_ROOT}:/src:ro\" \\\n      --workdir=\"/src\" \\\n      --rm \\\n      --env=\"CC=/opt/llvm/clang/bin/clang\" \\\n      --env=\"BAZEL_CXXOPTS=-std=${std}\" \\\n      ${LINUX_LATEST_CONTAINER} \\\n      /usr/local/bin/bazel test ... \\\n        --copt=\"--gcc-toolchain=/usr/local\" \\\n        --copt=\"-Wall\" \\\n        --copt=\"-Werror\" \\\n        --copt=\"-Wuninitialized\" \\\n        --define=\"absl=${absl}\" \\\n        --distdir=\"/bazel-distdir\" \\\n        --keep_going \\\n        --linkopt=\"--gcc-toolchain=/usr/local\" \\\n        --show_timestamps \\\n        --test_output=errors\n  done\ndone\n"
  },
  {
    "path": "3rd/googletest-1.12.1/ci/macos-presubmit.sh",
    "content": "#!/bin/bash\n#\n# Copyright 2020, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nset -euox pipefail\n\nif [[ -z ${GTEST_ROOT:-} ]]; then\n  GTEST_ROOT=\"$(realpath $(dirname ${0})/..)\"\nfi\n\n# Test the CMake build\nfor cmake_off_on in OFF ON; do\n  BUILD_DIR=$(mktemp -d build_dir.XXXXXXXX)\n  cd ${BUILD_DIR}\n  time cmake ${GTEST_ROOT} \\\n    -DCMAKE_CXX_STANDARD=11 \\\n    -Dgtest_build_samples=ON \\\n    -Dgtest_build_tests=ON \\\n    -Dgmock_build_tests=ON \\\n    -Dcxx_no_exception=${cmake_off_on} \\\n    -Dcxx_no_rtti=${cmake_off_on}\n  time make\n  time ctest -j$(nproc) --output-on-failure\ndone\n\n# Test the Bazel build\n\n# If we are running on Kokoro, check for a versioned Bazel binary.\nKOKORO_GFILE_BAZEL_BIN=\"bazel-3.7.0-darwin-x86_64\"\nif [[ ${KOKORO_GFILE_DIR:-} ]] && [[ -f ${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN} ]]; then\n  BAZEL_BIN=\"${KOKORO_GFILE_DIR}/${KOKORO_GFILE_BAZEL_BIN}\"\n  chmod +x ${BAZEL_BIN}\nelse\n  BAZEL_BIN=\"bazel\"\nfi\n\ncd ${GTEST_ROOT}\nfor absl in 0 1; do\n  ${BAZEL_BIN} test ... \\\n    --copt=\"-Wall\" \\\n    --copt=\"-Werror\" \\\n    --define=\"absl=${absl}\" \\\n    --keep_going \\\n    --show_timestamps \\\n    --test_output=errors\ndone\n"
  },
  {
    "path": "3rd/googletest-1.12.1/docs/_config.yml",
    "content": "title: GoogleTest\n"
  },
  {
    "path": "3rd/googletest-1.12.1/docs/_data/navigation.yml",
    "content": "nav:\n- section: \"Get Started\"\n  items:\n  - title: \"Supported Platforms\"\n    url: \"/platforms.html\"\n  - title: \"Quickstart: Bazel\"\n    url: \"/quickstart-bazel.html\"\n  - title: \"Quickstart: CMake\"\n    url: \"/quickstart-cmake.html\"\n- section: \"Guides\"\n  items:\n  - title: \"GoogleTest Primer\"\n    url: \"/primer.html\"\n  - title: \"Advanced Topics\"\n    url: \"/advanced.html\"\n  - title: \"Mocking for Dummies\"\n    url: \"/gmock_for_dummies.html\"\n  - title: \"Mocking Cookbook\"\n    url: \"/gmock_cook_book.html\"\n  - title: \"Mocking Cheat Sheet\"\n    url: \"/gmock_cheat_sheet.html\"\n- section: \"References\"\n  items:\n  - title: \"Testing Reference\"\n    url: \"/reference/testing.html\"\n  - title: \"Mocking Reference\"\n    url: \"/reference/mocking.html\"\n  - title: \"Assertions\"\n    url: \"/reference/assertions.html\"\n  - title: \"Matchers\"\n    url: \"/reference/matchers.html\"\n  - title: \"Actions\"\n    url: \"/reference/actions.html\"\n  - title: \"Testing FAQ\"\n    url: \"/faq.html\"\n  - title: \"Mocking FAQ\"\n    url: \"/gmock_faq.html\"\n  - title: \"Code Samples\"\n    url: \"/samples.html\"\n  - title: \"Using pkg-config\"\n    url: \"/pkgconfig.html\"\n  - title: \"Community Documentation\"\n    url: \"/community_created_documentation.html\"\n"
  },
  {
    "path": "3rd/googletest-1.12.1/docs/_layouts/default.html",
    "content": "<!DOCTYPE html>\n<html lang=\"{{ site.lang | default: \"en-US\" }}\">\n  <head>\n    <meta charset=\"UTF-8\">\n    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\n{% seo %}\n    <link rel=\"stylesheet\" href=\"{{ \"/assets/css/style.css?v=\" | append: site.github.build_revision | relative_url }}\">\n    <script>\n      window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;\n      ga('create', 'UA-197576187-1', { 'storage': 'none' });\n      ga('set', 'referrer', document.referrer.split('?')[0]);\n      ga('set', 'location', window.location.href.split('?')[0]);\n      ga('set', 'anonymizeIp', true);\n      ga('send', 'pageview');\n    </script>\n    <script async src='https://www.google-analytics.com/analytics.js'></script>\n  </head>\n  <body>\n    <div class=\"sidebar\">\n      <div class=\"header\">\n        <h1><a href=\"{{ \"/\" | relative_url }}\">{{ site.title | default: \"Documentation\" }}</a></h1>\n      </div>\n      <input type=\"checkbox\" id=\"nav-toggle\" class=\"nav-toggle\">\n      <label for=\"nav-toggle\" class=\"expander\">\n        <span class=\"arrow\"></span>\n      </label>\n      <nav>\n        {% for item in site.data.navigation.nav %}\n        <h2>{{ item.section }}</h2>\n        <ul>\n          {% for subitem in item.items %}\n          <a href=\"{{subitem.url | relative_url }}\">\n            <li class=\"{% if subitem.url == page.url %}active{% endif %}\">\n              {{ subitem.title }}\n            </li>\n          </a>\n          {% endfor %}\n        </ul>\n        {% endfor %}\n      </nav>\n    </div>\n    <div class=\"main markdown-body\">\n      <div class=\"main-inner\">\n        {{ content }}\n      </div>\n      <div class=\"footer\">\n        GoogleTest &middot;\n        <a href=\"https://github.com/google/googletest\">GitHub Repository</a> &middot;\n        <a href=\"https://github.com/google/googletest/blob/master/LICENSE\">License</a> &middot;\n        <a href=\"https://policies.google.com/privacy\">Privacy Policy</a>\n      </div>\n    </div>\n    <script src=\"https://cdnjs.cloudflare.com/ajax/libs/anchor-js/4.1.0/anchor.min.js\" integrity=\"sha256-lZaRhKri35AyJSypXXs4o6OPFTbTmUoltBbDCbdzegg=\" crossorigin=\"anonymous\"></script>\n    <script>anchors.add('.main h2, .main h3, .main h4, .main h5, .main h6');</script>\n  </body>\n</html>\n"
  },
  {
    "path": "3rd/googletest-1.12.1/docs/_sass/main.scss",
    "content": "// Styles for GoogleTest docs website on GitHub Pages.\n// Color variables are defined in\n// https://github.com/pages-themes/primer/tree/master/_sass/primer-support/lib/variables\n\n$sidebar-width: 260px;\n\nbody {\n  display: flex;\n  margin: 0;\n}\n\n.sidebar {\n  background: $black;\n  color: $text-white;\n  flex-shrink: 0;\n  height: 100vh;\n  overflow: auto;\n  position: sticky;\n  top: 0;\n  width: $sidebar-width;\n}\n\n.sidebar h1 {\n  font-size: 1.5em;\n}\n\n.sidebar h2 {\n  color: $gray-light;\n  font-size: 0.8em;\n  font-weight: normal;\n  margin-bottom: 0.8em;\n  padding-left: 2.5em;\n  text-transform: uppercase;\n}\n\n.sidebar .header {\n  background: $black;\n  padding: 2em;\n  position: sticky;\n  top: 0;\n  width: 100%;\n}\n\n.sidebar .header a {\n  color: $text-white;\n  text-decoration: none;\n}\n\n.sidebar .nav-toggle {\n  display: none;\n}\n\n.sidebar .expander {\n  cursor: pointer;\n  display: none;\n  height: 3em;\n  position: absolute;\n  right: 1em;\n  top: 1.5em;\n  width: 3em;\n}\n\n.sidebar .expander .arrow {\n  border: solid $white;\n  border-width: 0 3px 3px 0;\n  display: block;\n  height: 0.7em;\n  margin: 1em auto;\n  transform: rotate(45deg);\n  transition: transform 0.5s;\n  width: 0.7em;\n}\n\n.sidebar nav {\n  width: 100%;\n}\n\n.sidebar nav ul {\n  list-style-type: none;\n  margin-bottom: 1em;\n  padding: 0;\n\n  &:last-child {\n    margin-bottom: 2em;\n  }\n\n  a {\n   text-decoration: none;\n  }\n\n  li {\n    color: $text-white;\n    padding-left: 2em;\n    text-decoration: none;\n  }\n\n  li.active {\n    background: $border-gray-darker;\n    font-weight: bold;\n  }\n\n  li:hover {\n    background: $border-gray-darker;\n  }\n}\n\n.main {\n  background-color: $bg-gray;\n  width: calc(100% - #{$sidebar-width});\n}\n\n.main .main-inner {\n  background-color: $white;\n  padding: 2em;\n}\n\n.main .footer {\n  margin: 0;\n  padding: 2em;\n}\n\n.main table th {\n  text-align: left;\n}\n\n.main .callout {\n  border-left: 0.25em solid $white;\n  padding: 1em;\n\n  a {\n    text-decoration: underline;\n  }\n\n  &.important {\n    background-color: $bg-yellow-light;\n    border-color: $bg-yellow;\n    color: $black;\n  }\n\n  &.note {\n    background-color: $bg-blue-light;\n    border-color: $text-blue;\n    color: $text-blue;\n  }\n\n  &.tip {\n    background-color: $green-000;\n    border-color: $green-700;\n    color: $green-700;\n  }\n\n  &.warning {\n    background-color: $red-000;\n    border-color: $text-red;\n    color: $text-red;\n  }\n}\n\n.main .good pre {\n  background-color: $bg-green-light;\n}\n\n.main .bad pre {\n  background-color: $red-000;\n}\n\n@media all and (max-width: 768px) {\n  body {\n    flex-direction: column;\n  }\n\n  .sidebar {\n    height: auto;\n    position: relative;\n    width: 100%;\n  }\n\n  .sidebar .expander {\n    display: block;\n  }\n\n  .sidebar nav {\n    height: 0;\n    overflow: hidden;\n  }\n\n  .sidebar .nav-toggle:checked {\n    & ~ nav {\n      height: auto;\n    }\n\n    & + .expander .arrow {\n      transform: rotate(-135deg);\n    }\n  }\n\n  .main {\n    width: 100%;\n  }\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/docs/advanced.md",
    "content": "# Advanced googletest Topics\n\n## Introduction\n\nNow that you have read the [googletest Primer](primer.md) and learned how to\nwrite tests using googletest, it's time to learn some new tricks. This document\nwill show you more assertions as well as how to construct complex failure\nmessages, propagate fatal failures, reuse and speed up your test fixtures, and\nuse various flags with your tests.\n\n## More Assertions\n\nThis section covers some less frequently used, but still significant,\nassertions.\n\n### Explicit Success and Failure\n\nSee [Explicit Success and Failure](reference/assertions.md#success-failure) in\nthe Assertions Reference.\n\n### Exception Assertions\n\nSee [Exception Assertions](reference/assertions.md#exceptions) in the Assertions\nReference.\n\n### Predicate Assertions for Better Error Messages\n\nEven though googletest has a rich set of assertions, they can never be complete,\nas it's impossible (nor a good idea) to anticipate all scenarios a user might\nrun into. Therefore, sometimes a user has to use `EXPECT_TRUE()` to check a\ncomplex expression, for lack of a better macro. This has the problem of not\nshowing you the values of the parts of the expression, making it hard to\nunderstand what went wrong. As a workaround, some users choose to construct the\nfailure message by themselves, streaming it into `EXPECT_TRUE()`. However, this\nis awkward especially when the expression has side-effects or is expensive to\nevaluate.\n\ngoogletest gives you three different options to solve this problem:\n\n#### Using an Existing Boolean Function\n\nIf you already have a function or functor that returns `bool` (or a type that\ncan be implicitly converted to `bool`), you can use it in a *predicate\nassertion* to get the function arguments printed for free. See\n[`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) in the Assertions\nReference for details.\n\n#### Using a Function That Returns an AssertionResult\n\nWhile `EXPECT_PRED*()` and friends are handy for a quick job, the syntax is not\nsatisfactory: you have to use different macros for different arities, and it\nfeels more like Lisp than C++. The `::testing::AssertionResult` class solves\nthis problem.\n\nAn `AssertionResult` object represents the result of an assertion (whether it's\na success or a failure, and an associated message). You can create an\n`AssertionResult` using one of these factory functions:\n\n```c++\nnamespace testing {\n\n// Returns an AssertionResult object to indicate that an assertion has\n// succeeded.\nAssertionResult AssertionSuccess();\n\n// Returns an AssertionResult object to indicate that an assertion has\n// failed.\nAssertionResult AssertionFailure();\n\n}\n```\n\nYou can then use the `<<` operator to stream messages to the `AssertionResult`\nobject.\n\nTo provide more readable messages in Boolean assertions (e.g. `EXPECT_TRUE()`),\nwrite a predicate function that returns `AssertionResult` instead of `bool`. For\nexample, if you define `IsEven()` as:\n\n```c++\ntesting::AssertionResult IsEven(int n) {\n  if ((n % 2) == 0)\n    return testing::AssertionSuccess();\n  else\n    return testing::AssertionFailure() << n << \" is odd\";\n}\n```\n\ninstead of:\n\n```c++\nbool IsEven(int n) {\n  return (n % 2) == 0;\n}\n```\n\nthe failed assertion `EXPECT_TRUE(IsEven(Fib(4)))` will print:\n\n```none\nValue of: IsEven(Fib(4))\n  Actual: false (3 is odd)\nExpected: true\n```\n\ninstead of a more opaque\n\n```none\nValue of: IsEven(Fib(4))\n  Actual: false\nExpected: true\n```\n\nIf you want informative messages in `EXPECT_FALSE` and `ASSERT_FALSE` as well\n(one third of Boolean assertions in the Google code base are negative ones), and\nare fine with making the predicate slower in the success case, you can supply a\nsuccess message:\n\n```c++\ntesting::AssertionResult IsEven(int n) {\n  if ((n % 2) == 0)\n    return testing::AssertionSuccess() << n << \" is even\";\n  else\n    return testing::AssertionFailure() << n << \" is odd\";\n}\n```\n\nThen the statement `EXPECT_FALSE(IsEven(Fib(6)))` will print\n\n```none\n  Value of: IsEven(Fib(6))\n     Actual: true (8 is even)\n  Expected: false\n```\n\n#### Using a Predicate-Formatter\n\nIf you find the default message generated by\n[`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) and\n[`EXPECT_TRUE`](reference/assertions.md#EXPECT_TRUE) unsatisfactory, or some\narguments to your predicate do not support streaming to `ostream`, you can\ninstead use *predicate-formatter assertions* to *fully* customize how the\nmessage is formatted. See\n[`EXPECT_PRED_FORMAT*`](reference/assertions.md#EXPECT_PRED_FORMAT) in the\nAssertions Reference for details.\n\n### Floating-Point Comparison\n\nSee [Floating-Point Comparison](reference/assertions.md#floating-point) in the\nAssertions Reference.\n\n#### Floating-Point Predicate-Format Functions\n\nSome floating-point operations are useful, but not that often used. In order to\navoid an explosion of new macros, we provide them as predicate-format functions\nthat can be used in the predicate assertion macro\n[`EXPECT_PRED_FORMAT2`](reference/assertions.md#EXPECT_PRED_FORMAT), for\nexample:\n\n```c++\nusing ::testing::FloatLE;\nusing ::testing::DoubleLE;\n...\nEXPECT_PRED_FORMAT2(FloatLE, val1, val2);\nEXPECT_PRED_FORMAT2(DoubleLE, val1, val2);\n```\n\nThe above code verifies that `val1` is less than, or approximately equal to,\n`val2`.\n\n### Asserting Using gMock Matchers\n\nSee [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) in the Assertions\nReference.\n\n### More String Assertions\n\n(Please read the [previous](#asserting-using-gmock-matchers) section first if\nyou haven't.)\n\nYou can use the gMock [string matchers](reference/matchers.md#string-matchers)\nwith [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) to do more string\ncomparison tricks (sub-string, prefix, suffix, regular expression, and etc). For\nexample,\n\n```c++\nusing ::testing::HasSubstr;\nusing ::testing::MatchesRegex;\n...\n  ASSERT_THAT(foo_string, HasSubstr(\"needle\"));\n  EXPECT_THAT(bar_string, MatchesRegex(\"\\\\w*\\\\d+\"));\n```\n\n### Windows HRESULT assertions\n\nSee [Windows HRESULT Assertions](reference/assertions.md#HRESULT) in the\nAssertions Reference.\n\n### Type Assertions\n\nYou can call the function\n\n```c++\n::testing::StaticAssertTypeEq<T1, T2>();\n```\n\nto assert that types `T1` and `T2` are the same. The function does nothing if\nthe assertion is satisfied. If the types are different, the function call will\nfail to compile, the compiler error message will say that `T1 and T2 are not the\nsame type` and most likely (depending on the compiler) show you the actual\nvalues of `T1` and `T2`. This is mainly useful inside template code.\n\n**Caveat**: When used inside a member function of a class template or a function\ntemplate, `StaticAssertTypeEq<T1, T2>()` is effective only if the function is\ninstantiated. For example, given:\n\n```c++\ntemplate <typename T> class Foo {\n public:\n  void Bar() { testing::StaticAssertTypeEq<int, T>(); }\n};\n```\n\nthe code:\n\n```c++\nvoid Test1() { Foo<bool> foo; }\n```\n\nwill not generate a compiler error, as `Foo<bool>::Bar()` is never actually\ninstantiated. Instead, you need:\n\n```c++\nvoid Test2() { Foo<bool> foo; foo.Bar(); }\n```\n\nto cause a compiler error.\n\n### Assertion Placement\n\nYou can use assertions in any C++ function. In particular, it doesn't have to be\na method of the test fixture class. The one constraint is that assertions that\ngenerate a fatal failure (`FAIL*` and `ASSERT_*`) can only be used in\nvoid-returning functions. This is a consequence of Google's not using\nexceptions. By placing it in a non-void function you'll get a confusing compile\nerror like `\"error: void value not ignored as it ought to be\"` or `\"cannot\ninitialize return object of type 'bool' with an rvalue of type 'void'\"` or\n`\"error: no viable conversion from 'void' to 'string'\"`.\n\nIf you need to use fatal assertions in a function that returns non-void, one\noption is to make the function return the value in an out parameter instead. For\nexample, you can rewrite `T2 Foo(T1 x)` to `void Foo(T1 x, T2* result)`. You\nneed to make sure that `*result` contains some sensible value even when the\nfunction returns prematurely. As the function now returns `void`, you can use\nany assertion inside of it.\n\nIf changing the function's type is not an option, you should just use assertions\nthat generate non-fatal failures, such as `ADD_FAILURE*` and `EXPECT_*`.\n\n{: .callout .note}\nNOTE: Constructors and destructors are not considered void-returning functions,\naccording to the C++ language specification, and so you may not use fatal\nassertions in them; you'll get a compilation error if you try. Instead, either\ncall `abort` and crash the entire test executable, or put the fatal assertion in\na `SetUp`/`TearDown` function; see\n[constructor/destructor vs. `SetUp`/`TearDown`](faq.md#CtorVsSetUp)\n\n{: .callout .warning}\nWARNING: A fatal assertion in a helper function (private void-returning method)\ncalled from a constructor or destructor does not terminate the current test, as\nyour intuition might suggest: it merely returns from the constructor or\ndestructor early, possibly leaving your object in a partially-constructed or\npartially-destructed state! You almost certainly want to `abort` or use\n`SetUp`/`TearDown` instead.\n\n## Skipping test execution\n\nRelated to the assertions `SUCCEED()` and `FAIL()`, you can prevent further test\nexecution at runtime with the `GTEST_SKIP()` macro. This is useful when you need\nto check for preconditions of the system under test during runtime and skip\ntests in a meaningful way.\n\n`GTEST_SKIP()` can be used in individual test cases or in the `SetUp()` methods\nof classes derived from either `::testing::Environment` or `::testing::Test`.\nFor example:\n\n```c++\nTEST(SkipTest, DoesSkip) {\n  GTEST_SKIP() << \"Skipping single test\";\n  EXPECT_EQ(0, 1);  // Won't fail; it won't be executed\n}\n\nclass SkipFixture : public ::testing::Test {\n protected:\n  void SetUp() override {\n    GTEST_SKIP() << \"Skipping all tests for this fixture\";\n  }\n};\n\n// Tests for SkipFixture won't be executed.\nTEST_F(SkipFixture, SkipsOneTest) {\n  EXPECT_EQ(5, 7);  // Won't fail\n}\n```\n\nAs with assertion macros, you can stream a custom message into `GTEST_SKIP()`.\n\n## Teaching googletest How to Print Your Values\n\nWhen a test assertion such as `EXPECT_EQ` fails, googletest prints the argument\nvalues to help you debug. It does this using a user-extensible value printer.\n\nThis printer knows how to print built-in C++ types, native arrays, STL\ncontainers, and any type that supports the `<<` operator. For other types, it\nprints the raw bytes in the value and hopes that you the user can figure it out.\n\nAs mentioned earlier, the printer is *extensible*. That means you can teach it\nto do a better job at printing your particular type than to dump the bytes. To\ndo that, define `<<` for your type:\n\n```c++\n#include <ostream>\n\nnamespace foo {\n\nclass Bar {  // We want googletest to be able to print instances of this.\n...\n  // Create a free inline friend function.\n  friend std::ostream& operator<<(std::ostream& os, const Bar& bar) {\n    return os << bar.DebugString();  // whatever needed to print bar to os\n  }\n};\n\n// If you can't declare the function in the class it's important that the\n// << operator is defined in the SAME namespace that defines Bar.  C++'s look-up\n// rules rely on that.\nstd::ostream& operator<<(std::ostream& os, const Bar& bar) {\n  return os << bar.DebugString();  // whatever needed to print bar to os\n}\n\n}  // namespace foo\n```\n\nSometimes, this might not be an option: your team may consider it bad style to\nhave a `<<` operator for `Bar`, or `Bar` may already have a `<<` operator that\ndoesn't do what you want (and you cannot change it). If so, you can instead\ndefine a `PrintTo()` function like this:\n\n```c++\n#include <ostream>\n\nnamespace foo {\n\nclass Bar {\n  ...\n  friend void PrintTo(const Bar& bar, std::ostream* os) {\n    *os << bar.DebugString();  // whatever needed to print bar to os\n  }\n};\n\n// If you can't declare the function in the class it's important that PrintTo()\n// is defined in the SAME namespace that defines Bar.  C++'s look-up rules rely\n// on that.\nvoid PrintTo(const Bar& bar, std::ostream* os) {\n  *os << bar.DebugString();  // whatever needed to print bar to os\n}\n\n}  // namespace foo\n```\n\nIf you have defined both `<<` and `PrintTo()`, the latter will be used when\ngoogletest is concerned. This allows you to customize how the value appears in\ngoogletest's output without affecting code that relies on the behavior of its\n`<<` operator.\n\nIf you want to print a value `x` using googletest's value printer yourself, just\ncall `::testing::PrintToString(x)`, which returns an `std::string`:\n\n```c++\nvector<pair<Bar, int> > bar_ints = GetBarIntVector();\n\nEXPECT_TRUE(IsCorrectBarIntVector(bar_ints))\n    << \"bar_ints = \" << testing::PrintToString(bar_ints);\n```\n\n## Death Tests\n\nIn many applications, there are assertions that can cause application failure if\na condition is not met. These consistency checks, which ensure that the program\nis in a known good state, are there to fail at the earliest possible time after\nsome program state is corrupted. If the assertion checks the wrong condition,\nthen the program may proceed in an erroneous state, which could lead to memory\ncorruption, security holes, or worse. Hence it is vitally important to test that\nsuch assertion statements work as expected.\n\nSince these precondition checks cause the processes to die, we call such tests\n_death tests_. More generally, any test that checks that a program terminates\n(except by throwing an exception) in an expected fashion is also a death test.\n\nNote that if a piece of code throws an exception, we don't consider it \"death\"\nfor the purpose of death tests, as the caller of the code could catch the\nexception and avoid the crash. If you want to verify exceptions thrown by your\ncode, see [Exception Assertions](#ExceptionAssertions).\n\nIf you want to test `EXPECT_*()/ASSERT_*()` failures in your test code, see\n[\"Catching\" Failures](#catching-failures).\n\n### How to Write a Death Test\n\nGoogleTest provides assertion macros to support death tests. See\n[Death Assertions](reference/assertions.md#death) in the Assertions Reference\nfor details.\n\nTo write a death test, simply use one of the macros inside your test function.\nFor example,\n\n```c++\nTEST(MyDeathTest, Foo) {\n  // This death test uses a compound statement.\n  ASSERT_DEATH({\n    int n = 5;\n    Foo(&n);\n  }, \"Error on line .* of Foo()\");\n}\n\nTEST(MyDeathTest, NormalExit) {\n  EXPECT_EXIT(NormalExit(), testing::ExitedWithCode(0), \"Success\");\n}\n\nTEST(MyDeathTest, KillProcess) {\n  EXPECT_EXIT(KillProcess(), testing::KilledBySignal(SIGKILL),\n              \"Sending myself unblockable signal\");\n}\n```\n\nverifies that:\n\n*   calling `Foo(5)` causes the process to die with the given error message,\n*   calling `NormalExit()` causes the process to print `\"Success\"` to stderr and\n    exit with exit code 0, and\n*   calling `KillProcess()` kills the process with signal `SIGKILL`.\n\nThe test function body may contain other assertions and statements as well, if\nnecessary.\n\nNote that a death test only cares about three things:\n\n1.  does `statement` abort or exit the process?\n2.  (in the case of `ASSERT_EXIT` and `EXPECT_EXIT`) does the exit status\n    satisfy `predicate`? Or (in the case of `ASSERT_DEATH` and `EXPECT_DEATH`)\n    is the exit status non-zero? And\n3.  does the stderr output match `matcher`?\n\nIn particular, if `statement` generates an `ASSERT_*` or `EXPECT_*` failure, it\nwill **not** cause the death test to fail, as googletest assertions don't abort\nthe process.\n\n### Death Test Naming\n\n{: .callout .important}\nIMPORTANT: We strongly recommend you to follow the convention of naming your\n**test suite** (not test) `*DeathTest` when it contains a death test, as\ndemonstrated in the above example. The\n[Death Tests And Threads](#death-tests-and-threads) section below explains why.\n\nIf a test fixture class is shared by normal tests and death tests, you can use\n`using` or `typedef` to introduce an alias for the fixture class and avoid\nduplicating its code:\n\n```c++\nclass FooTest : public testing::Test { ... };\n\nusing FooDeathTest = FooTest;\n\nTEST_F(FooTest, DoesThis) {\n  // normal test\n}\n\nTEST_F(FooDeathTest, DoesThat) {\n  // death test\n}\n```\n\n### Regular Expression Syntax\n\nWhen built with Bazel and using Abseil, googletest uses the\n[RE2](https://github.com/google/re2/wiki/Syntax) syntax. Otherwise, for POSIX\nsystems (Linux, Cygwin, Mac), googletest uses the\n[POSIX extended regular expression](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html#tag_09_04)\nsyntax. To learn about POSIX syntax, you may want to read this\n[Wikipedia entry](http://en.wikipedia.org/wiki/Regular_expression#POSIX_Extended_Regular_Expressions).\n\nOn Windows, googletest uses its own simple regular expression implementation. It\nlacks many features. For example, we don't support union (`\"x|y\"`), grouping\n(`\"(xy)\"`), brackets (`\"[xy]\"`), and repetition count (`\"x{5,7}\"`), among\nothers. Below is what we do support (`A` denotes a literal character, period\n(`.`), or a single `\\\\ ` escape sequence; `x` and `y` denote regular\nexpressions.):\n\nExpression | Meaning\n---------- | --------------------------------------------------------------\n`c`        | matches any literal character `c`\n`\\\\d`      | matches any decimal digit\n`\\\\D`      | matches any character that's not a decimal digit\n`\\\\f`      | matches `\\f`\n`\\\\n`      | matches `\\n`\n`\\\\r`      | matches `\\r`\n`\\\\s`      | matches any ASCII whitespace, including `\\n`\n`\\\\S`      | matches any character that's not a whitespace\n`\\\\t`      | matches `\\t`\n`\\\\v`      | matches `\\v`\n`\\\\w`      | matches any letter, `_`, or decimal digit\n`\\\\W`      | matches any character that `\\\\w` doesn't match\n`\\\\c`      | matches any literal character `c`, which must be a punctuation\n`.`        | matches any single character except `\\n`\n`A?`       | matches 0 or 1 occurrences of `A`\n`A*`       | matches 0 or many occurrences of `A`\n`A+`       | matches 1 or many occurrences of `A`\n`^`        | matches the beginning of a string (not that of each line)\n`$`        | matches the end of a string (not that of each line)\n`xy`       | matches `x` followed by `y`\n\nTo help you determine which capability is available on your system, googletest\ndefines macros to govern which regular expression it is using. The macros are:\n`GTEST_USES_SIMPLE_RE=1` or `GTEST_USES_POSIX_RE=1`. If you want your death\ntests to work in all cases, you can either `#if` on these macros or use the more\nlimited syntax only.\n\n### How It Works\n\nSee [Death Assertions](reference/assertions.md#death) in the Assertions\nReference.\n\n### Death Tests And Threads\n\nThe reason for the two death test styles has to do with thread safety. Due to\nwell-known problems with forking in the presence of threads, death tests should\nbe run in a single-threaded context. Sometimes, however, it isn't feasible to\narrange that kind of environment. For example, statically-initialized modules\nmay start threads before main is ever reached. Once threads have been created,\nit may be difficult or impossible to clean them up.\n\ngoogletest has three features intended to raise awareness of threading issues.\n\n1.  A warning is emitted if multiple threads are running when a death test is\n    encountered.\n2.  Test suites with a name ending in \"DeathTest\" are run before all other\n    tests.\n3.  It uses `clone()` instead of `fork()` to spawn the child process on Linux\n    (`clone()` is not available on Cygwin and Mac), as `fork()` is more likely\n    to cause the child to hang when the parent process has multiple threads.\n\nIt's perfectly fine to create threads inside a death test statement; they are\nexecuted in a separate process and cannot affect the parent.\n\n### Death Test Styles\n\nThe \"threadsafe\" death test style was introduced in order to help mitigate the\nrisks of testing in a possibly multithreaded environment. It trades increased\ntest execution time (potentially dramatically so) for improved thread safety.\n\nThe automated testing framework does not set the style flag. You can choose a\nparticular style of death tests by setting the flag programmatically:\n\n```c++\nGTEST_FLAG_SET(death_test_style, \"threadsafe\")\n```\n\nYou can do this in `main()` to set the style for all death tests in the binary,\nor in individual tests. Recall that flags are saved before running each test and\nrestored afterwards, so you need not do that yourself. For example:\n\n```c++\nint main(int argc, char** argv) {\n  testing::InitGoogleTest(&argc, argv);\n  GTEST_FLAG_SET(death_test_style, \"fast\");\n  return RUN_ALL_TESTS();\n}\n\nTEST(MyDeathTest, TestOne) {\n  GTEST_FLAG_SET(death_test_style, \"threadsafe\");\n  // This test is run in the \"threadsafe\" style:\n  ASSERT_DEATH(ThisShouldDie(), \"\");\n}\n\nTEST(MyDeathTest, TestTwo) {\n  // This test is run in the \"fast\" style:\n  ASSERT_DEATH(ThisShouldDie(), \"\");\n}\n```\n\n### Caveats\n\nThe `statement` argument of `ASSERT_EXIT()` can be any valid C++ statement. If\nit leaves the current function via a `return` statement or by throwing an\nexception, the death test is considered to have failed. Some googletest macros\nmay return from the current function (e.g. `ASSERT_TRUE()`), so be sure to avoid\nthem in `statement`.\n\nSince `statement` runs in the child process, any in-memory side effect (e.g.\nmodifying a variable, releasing memory, etc) it causes will *not* be observable\nin the parent process. In particular, if you release memory in a death test,\nyour program will fail the heap check as the parent process will never see the\nmemory reclaimed. To solve this problem, you can\n\n1.  try not to free memory in a death test;\n2.  free the memory again in the parent process; or\n3.  do not use the heap checker in your program.\n\nDue to an implementation detail, you cannot place multiple death test assertions\non the same line; otherwise, compilation will fail with an unobvious error\nmessage.\n\nDespite the improved thread safety afforded by the \"threadsafe\" style of death\ntest, thread problems such as deadlock are still possible in the presence of\nhandlers registered with `pthread_atfork(3)`.\n\n## Using Assertions in Sub-routines\n\n{: .callout .note}\nNote: If you want to put a series of test assertions in a subroutine to check\nfor a complex condition, consider using\n[a custom GMock matcher](gmock_cook_book.md#NewMatchers) instead. This lets you\nprovide a more readable error message in case of failure and avoid all of the\nissues described below.\n\n### Adding Traces to Assertions\n\nIf a test sub-routine is called from several places, when an assertion inside it\nfails, it can be hard to tell which invocation of the sub-routine the failure is\nfrom. You can alleviate this problem using extra logging or custom failure\nmessages, but that usually clutters up your tests. A better solution is to use\nthe `SCOPED_TRACE` macro or the `ScopedTrace` utility:\n\n```c++\nSCOPED_TRACE(message);\n```\n\n```c++\nScopedTrace trace(\"file_path\", line_number, message);\n```\n\nwhere `message` can be anything streamable to `std::ostream`. `SCOPED_TRACE`\nmacro will cause the current file name, line number, and the given message to be\nadded in every failure message. `ScopedTrace` accepts explicit file name and\nline number in arguments, which is useful for writing test helpers. The effect\nwill be undone when the control leaves the current lexical scope.\n\nFor example,\n\n```c++\n10: void Sub1(int n) {\n11:   EXPECT_EQ(Bar(n), 1);\n12:   EXPECT_EQ(Bar(n + 1), 2);\n13: }\n14:\n15: TEST(FooTest, Bar) {\n16:   {\n17:     SCOPED_TRACE(\"A\");  // This trace point will be included in\n18:                         // every failure in this scope.\n19:     Sub1(1);\n20:   }\n21:   // Now it won't.\n22:   Sub1(9);\n23: }\n```\n\ncould result in messages like these:\n\n```none\npath/to/foo_test.cc:11: Failure\nValue of: Bar(n)\nExpected: 1\n  Actual: 2\nGoogle Test trace:\npath/to/foo_test.cc:17: A\n\npath/to/foo_test.cc:12: Failure\nValue of: Bar(n + 1)\nExpected: 2\n  Actual: 3\n```\n\nWithout the trace, it would've been difficult to know which invocation of\n`Sub1()` the two failures come from respectively. (You could add an extra\nmessage to each assertion in `Sub1()` to indicate the value of `n`, but that's\ntedious.)\n\nSome tips on using `SCOPED_TRACE`:\n\n1.  With a suitable message, it's often enough to use `SCOPED_TRACE` at the\n    beginning of a sub-routine, instead of at each call site.\n2.  When calling sub-routines inside a loop, make the loop iterator part of the\n    message in `SCOPED_TRACE` such that you can know which iteration the failure\n    is from.\n3.  Sometimes the line number of the trace point is enough for identifying the\n    particular invocation of a sub-routine. In this case, you don't have to\n    choose a unique message for `SCOPED_TRACE`. You can simply use `\"\"`.\n4.  You can use `SCOPED_TRACE` in an inner scope when there is one in the outer\n    scope. In this case, all active trace points will be included in the failure\n    messages, in reverse order they are encountered.\n5.  The trace dump is clickable in Emacs - hit `return` on a line number and\n    you'll be taken to that line in the source file!\n\n### Propagating Fatal Failures\n\nA common pitfall when using `ASSERT_*` and `FAIL*` is not understanding that\nwhen they fail they only abort the _current function_, not the entire test. For\nexample, the following test will segfault:\n\n```c++\nvoid Subroutine() {\n  // Generates a fatal failure and aborts the current function.\n  ASSERT_EQ(1, 2);\n\n  // The following won't be executed.\n  ...\n}\n\nTEST(FooTest, Bar) {\n  Subroutine();  // The intended behavior is for the fatal failure\n                 // in Subroutine() to abort the entire test.\n\n  // The actual behavior: the function goes on after Subroutine() returns.\n  int* p = nullptr;\n  *p = 3;  // Segfault!\n}\n```\n\nTo alleviate this, googletest provides three different solutions. You could use\neither exceptions, the `(ASSERT|EXPECT)_NO_FATAL_FAILURE` assertions or the\n`HasFatalFailure()` function. They are described in the following two\nsubsections.\n\n#### Asserting on Subroutines with an exception\n\nThe following code can turn ASSERT-failure into an exception:\n\n```c++\nclass ThrowListener : public testing::EmptyTestEventListener {\n  void OnTestPartResult(const testing::TestPartResult& result) override {\n    if (result.type() == testing::TestPartResult::kFatalFailure) {\n      throw testing::AssertionException(result);\n    }\n  }\n};\nint main(int argc, char** argv) {\n  ...\n  testing::UnitTest::GetInstance()->listeners().Append(new ThrowListener);\n  return RUN_ALL_TESTS();\n}\n```\n\nThis listener should be added after other listeners if you have any, otherwise\nthey won't see failed `OnTestPartResult`.\n\n#### Asserting on Subroutines\n\nAs shown above, if your test calls a subroutine that has an `ASSERT_*` failure\nin it, the test will continue after the subroutine returns. This may not be what\nyou want.\n\nOften people want fatal failures to propagate like exceptions. For that\ngoogletest offers the following macros:\n\nFatal assertion                       | Nonfatal assertion                    | Verifies\n------------------------------------- | ------------------------------------- | --------\n`ASSERT_NO_FATAL_FAILURE(statement);` | `EXPECT_NO_FATAL_FAILURE(statement);` | `statement` doesn't generate any new fatal failures in the current thread.\n\nOnly failures in the thread that executes the assertion are checked to determine\nthe result of this type of assertions. If `statement` creates new threads,\nfailures in these threads are ignored.\n\nExamples:\n\n```c++\nASSERT_NO_FATAL_FAILURE(Foo());\n\nint i;\nEXPECT_NO_FATAL_FAILURE({\n  i = Bar();\n});\n```\n\nAssertions from multiple threads are currently not supported on Windows.\n\n#### Checking for Failures in the Current Test\n\n`HasFatalFailure()` in the `::testing::Test` class returns `true` if an\nassertion in the current test has suffered a fatal failure. This allows\nfunctions to catch fatal failures in a sub-routine and return early.\n\n```c++\nclass Test {\n public:\n  ...\n  static bool HasFatalFailure();\n};\n```\n\nThe typical usage, which basically simulates the behavior of a thrown exception,\nis:\n\n```c++\nTEST(FooTest, Bar) {\n  Subroutine();\n  // Aborts if Subroutine() had a fatal failure.\n  if (HasFatalFailure()) return;\n\n  // The following won't be executed.\n  ...\n}\n```\n\nIf `HasFatalFailure()` is used outside of `TEST()` , `TEST_F()` , or a test\nfixture, you must add the `::testing::Test::` prefix, as in:\n\n```c++\nif (testing::Test::HasFatalFailure()) return;\n```\n\nSimilarly, `HasNonfatalFailure()` returns `true` if the current test has at\nleast one non-fatal failure, and `HasFailure()` returns `true` if the current\ntest has at least one failure of either kind.\n\n## Logging Additional Information\n\nIn your test code, you can call `RecordProperty(\"key\", value)` to log additional\ninformation, where `value` can be either a string or an `int`. The *last* value\nrecorded for a key will be emitted to the\n[XML output](#generating-an-xml-report) if you specify one. For example, the\ntest\n\n```c++\nTEST_F(WidgetUsageTest, MinAndMaxWidgets) {\n  RecordProperty(\"MaximumWidgets\", ComputeMaxUsage());\n  RecordProperty(\"MinimumWidgets\", ComputeMinUsage());\n}\n```\n\nwill output XML like this:\n\n```xml\n  ...\n    <testcase name=\"MinAndMaxWidgets\" file=\"test.cpp\" line=\"1\" status=\"run\" time=\"0.006\" classname=\"WidgetUsageTest\" MaximumWidgets=\"12\" MinimumWidgets=\"9\" />\n  ...\n```\n\n{: .callout .note}\n> NOTE:\n>\n> *   `RecordProperty()` is a static member of the `Test` class. Therefore it\n>     needs to be prefixed with `::testing::Test::` if used outside of the\n>     `TEST` body and the test fixture class.\n> *   *`key`* must be a valid XML attribute name, and cannot conflict with the\n>     ones already used by googletest (`name`, `status`, `time`, `classname`,\n>     `type_param`, and `value_param`).\n> *   Calling `RecordProperty()` outside of the lifespan of a test is allowed.\n>     If it's called outside of a test but between a test suite's\n>     `SetUpTestSuite()` and `TearDownTestSuite()` methods, it will be\n>     attributed to the XML element for the test suite. If it's called outside\n>     of all test suites (e.g. in a test environment), it will be attributed to\n>     the top-level XML element.\n\n## Sharing Resources Between Tests in the Same Test Suite\n\ngoogletest creates a new test fixture object for each test in order to make\ntests independent and easier to debug. However, sometimes tests use resources\nthat are expensive to set up, making the one-copy-per-test model prohibitively\nexpensive.\n\nIf the tests don't change the resource, there's no harm in their sharing a\nsingle resource copy. So, in addition to per-test set-up/tear-down, googletest\nalso supports per-test-suite set-up/tear-down. To use it:\n\n1.  In your test fixture class (say `FooTest` ), declare as `static` some member\n    variables to hold the shared resources.\n2.  Outside your test fixture class (typically just below it), define those\n    member variables, optionally giving them initial values.\n3.  In the same test fixture class, define a `static void SetUpTestSuite()`\n    function (remember not to spell it as **`SetupTestSuite`** with a small\n    `u`!) to set up the shared resources and a `static void TearDownTestSuite()`\n    function to tear them down.\n\nThat's it! googletest automatically calls `SetUpTestSuite()` before running the\n*first test* in the `FooTest` test suite (i.e. before creating the first\n`FooTest` object), and calls `TearDownTestSuite()` after running the *last test*\nin it (i.e. after deleting the last `FooTest` object). In between, the tests can\nuse the shared resources.\n\nRemember that the test order is undefined, so your code can't depend on a test\npreceding or following another. Also, the tests must either not modify the state\nof any shared resource, or, if they do modify the state, they must restore the\nstate to its original value before passing control to the next test.\n\nNote that `SetUpTestSuite()` may be called multiple times for a test fixture\nclass that has derived classes, so you should not expect code in the function\nbody to be run only once. Also, derived classes still have access to shared\nresources defined as static members, so careful consideration is needed when\nmanaging shared resources to avoid memory leaks.\n\nHere's an example of per-test-suite set-up and tear-down:\n\n```c++\nclass FooTest : public testing::Test {\n protected:\n  // Per-test-suite set-up.\n  // Called before the first test in this test suite.\n  // Can be omitted if not needed.\n  static void SetUpTestSuite() {\n    // Avoid reallocating static objects if called in subclasses of FooTest.\n    if (shared_resource_ == nullptr) {\n      shared_resource_ = new ...;\n    }\n  }\n\n  // Per-test-suite tear-down.\n  // Called after the last test in this test suite.\n  // Can be omitted if not needed.\n  static void TearDownTestSuite() {\n    delete shared_resource_;\n    shared_resource_ = nullptr;\n  }\n\n  // You can define per-test set-up logic as usual.\n  void SetUp() override { ... }\n\n  // You can define per-test tear-down logic as usual.\n  void TearDown() override { ... }\n\n  // Some expensive resource shared by all tests.\n  static T* shared_resource_;\n};\n\nT* FooTest::shared_resource_ = nullptr;\n\nTEST_F(FooTest, Test1) {\n  ... you can refer to shared_resource_ here ...\n}\n\nTEST_F(FooTest, Test2) {\n  ... you can refer to shared_resource_ here ...\n}\n```\n\n{: .callout .note}\nNOTE: Though the above code declares `SetUpTestSuite()` protected, it may\nsometimes be necessary to declare it public, such as when using it with\n`TEST_P`.\n\n## Global Set-Up and Tear-Down\n\nJust as you can do set-up and tear-down at the test level and the test suite\nlevel, you can also do it at the test program level. Here's how.\n\nFirst, you subclass the `::testing::Environment` class to define a test\nenvironment, which knows how to set-up and tear-down:\n\n```c++\nclass Environment : public ::testing::Environment {\n public:\n  ~Environment() override {}\n\n  // Override this to define how to set up the environment.\n  void SetUp() override {}\n\n  // Override this to define how to tear down the environment.\n  void TearDown() override {}\n};\n```\n\nThen, you register an instance of your environment class with googletest by\ncalling the `::testing::AddGlobalTestEnvironment()` function:\n\n```c++\nEnvironment* AddGlobalTestEnvironment(Environment* env);\n```\n\nNow, when `RUN_ALL_TESTS()` is called, it first calls the `SetUp()` method of\neach environment object, then runs the tests if none of the environments\nreported fatal failures and `GTEST_SKIP()` was not called. `RUN_ALL_TESTS()`\nalways calls `TearDown()` with each environment object, regardless of whether or\nnot the tests were run.\n\nIt's OK to register multiple environment objects. In this suite, their `SetUp()`\nwill be called in the order they are registered, and their `TearDown()` will be\ncalled in the reverse order.\n\nNote that googletest takes ownership of the registered environment objects.\nTherefore **do not delete them** by yourself.\n\nYou should call `AddGlobalTestEnvironment()` before `RUN_ALL_TESTS()` is called,\nprobably in `main()`. If you use `gtest_main`, you need to call this before\n`main()` starts for it to take effect. One way to do this is to define a global\nvariable like this:\n\n```c++\ntesting::Environment* const foo_env =\n    testing::AddGlobalTestEnvironment(new FooEnvironment);\n```\n\nHowever, we strongly recommend you to write your own `main()` and call\n`AddGlobalTestEnvironment()` there, as relying on initialization of global\nvariables makes the code harder to read and may cause problems when you register\nmultiple environments from different translation units and the environments have\ndependencies among them (remember that the compiler doesn't guarantee the order\nin which global variables from different translation units are initialized).\n\n## Value-Parameterized Tests\n\n*Value-parameterized tests* allow you to test your code with different\nparameters without writing multiple copies of the same test. This is useful in a\nnumber of situations, for example:\n\n*   You have a piece of code whose behavior is affected by one or more\n    command-line flags. You want to make sure your code performs correctly for\n    various values of those flags.\n*   You want to test different implementations of an OO interface.\n*   You want to test your code over various inputs (a.k.a. data-driven testing).\n    This feature is easy to abuse, so please exercise your good sense when doing\n    it!\n\n### How to Write Value-Parameterized Tests\n\nTo write value-parameterized tests, first you should define a fixture class. It\nmust be derived from both `testing::Test` and `testing::WithParamInterface<T>`\n(the latter is a pure interface), where `T` is the type of your parameter\nvalues. For convenience, you can just derive the fixture class from\n`testing::TestWithParam<T>`, which itself is derived from both `testing::Test`\nand `testing::WithParamInterface<T>`. `T` can be any copyable type. If it's a\nraw pointer, you are responsible for managing the lifespan of the pointed\nvalues.\n\n{: .callout .note}\nNOTE: If your test fixture defines `SetUpTestSuite()` or `TearDownTestSuite()`\nthey must be declared **public** rather than **protected** in order to use\n`TEST_P`.\n\n```c++\nclass FooTest :\n    public testing::TestWithParam<const char*> {\n  // You can implement all the usual fixture class members here.\n  // To access the test parameter, call GetParam() from class\n  // TestWithParam<T>.\n};\n\n// Or, when you want to add parameters to a pre-existing fixture class:\nclass BaseTest : public testing::Test {\n  ...\n};\nclass BarTest : public BaseTest,\n                public testing::WithParamInterface<const char*> {\n  ...\n};\n```\n\nThen, use the `TEST_P` macro to define as many test patterns using this fixture\nas you want. The `_P` suffix is for \"parameterized\" or \"pattern\", whichever you\nprefer to think.\n\n```c++\nTEST_P(FooTest, DoesBlah) {\n  // Inside a test, access the test parameter with the GetParam() method\n  // of the TestWithParam<T> class:\n  EXPECT_TRUE(foo.Blah(GetParam()));\n  ...\n}\n\nTEST_P(FooTest, HasBlahBlah) {\n  ...\n}\n```\n\nFinally, you can use the `INSTANTIATE_TEST_SUITE_P` macro to instantiate the\ntest suite with any set of parameters you want. GoogleTest defines a number of\nfunctions for generating test parameters—see details at\n[`INSTANTIATE_TEST_SUITE_P`](reference/testing.md#INSTANTIATE_TEST_SUITE_P) in\nthe Testing Reference.\n\nFor example, the following statement will instantiate tests from the `FooTest`\ntest suite each with parameter values `\"meeny\"`, `\"miny\"`, and `\"moe\"` using the\n[`Values`](reference/testing.md#param-generators) parameter generator:\n\n```c++\nINSTANTIATE_TEST_SUITE_P(MeenyMinyMoe,\n                         FooTest,\n                         testing::Values(\"meeny\", \"miny\", \"moe\"));\n```\n\n{: .callout .note}\nNOTE: The code above must be placed at global or namespace scope, not at\nfunction scope.\n\nThe first argument to `INSTANTIATE_TEST_SUITE_P` is a unique name for the\ninstantiation of the test suite. The next argument is the name of the test\npattern, and the last is the\n[parameter generator](reference/testing.md#param-generators).\n\nYou can instantiate a test pattern more than once, so to distinguish different\ninstances of the pattern, the instantiation name is added as a prefix to the\nactual test suite name. Remember to pick unique prefixes for different\ninstantiations. The tests from the instantiation above will have these names:\n\n*   `MeenyMinyMoe/FooTest.DoesBlah/0` for `\"meeny\"`\n*   `MeenyMinyMoe/FooTest.DoesBlah/1` for `\"miny\"`\n*   `MeenyMinyMoe/FooTest.DoesBlah/2` for `\"moe\"`\n*   `MeenyMinyMoe/FooTest.HasBlahBlah/0` for `\"meeny\"`\n*   `MeenyMinyMoe/FooTest.HasBlahBlah/1` for `\"miny\"`\n*   `MeenyMinyMoe/FooTest.HasBlahBlah/2` for `\"moe\"`\n\nYou can use these names in [`--gtest_filter`](#running-a-subset-of-the-tests).\n\nThe following statement will instantiate all tests from `FooTest` again, each\nwith parameter values `\"cat\"` and `\"dog\"` using the\n[`ValuesIn`](reference/testing.md#param-generators) parameter generator:\n\n```c++\nconst char* pets[] = {\"cat\", \"dog\"};\nINSTANTIATE_TEST_SUITE_P(Pets, FooTest, testing::ValuesIn(pets));\n```\n\nThe tests from the instantiation above will have these names:\n\n*   `Pets/FooTest.DoesBlah/0` for `\"cat\"`\n*   `Pets/FooTest.DoesBlah/1` for `\"dog\"`\n*   `Pets/FooTest.HasBlahBlah/0` for `\"cat\"`\n*   `Pets/FooTest.HasBlahBlah/1` for `\"dog\"`\n\nPlease note that `INSTANTIATE_TEST_SUITE_P` will instantiate *all* tests in the\ngiven test suite, whether their definitions come before or *after* the\n`INSTANTIATE_TEST_SUITE_P` statement.\n\nAdditionally, by default, every `TEST_P` without a corresponding\n`INSTANTIATE_TEST_SUITE_P` causes a failing test in test suite\n`GoogleTestVerification`. If you have a test suite where that omission is not an\nerror, for example it is in a library that may be linked in for other reasons or\nwhere the list of test cases is dynamic and may be empty, then this check can be\nsuppressed by tagging the test suite:\n\n```c++\nGTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(FooTest);\n```\n\nYou can see [sample7_unittest.cc] and [sample8_unittest.cc] for more examples.\n\n[sample7_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample7_unittest.cc \"Parameterized Test example\"\n[sample8_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample8_unittest.cc \"Parameterized Test example with multiple parameters\"\n\n### Creating Value-Parameterized Abstract Tests\n\nIn the above, we define and instantiate `FooTest` in the *same* source file.\nSometimes you may want to define value-parameterized tests in a library and let\nother people instantiate them later. This pattern is known as *abstract tests*.\nAs an example of its application, when you are designing an interface you can\nwrite a standard suite of abstract tests (perhaps using a factory function as\nthe test parameter) that all implementations of the interface are expected to\npass. When someone implements the interface, they can instantiate your suite to\nget all the interface-conformance tests for free.\n\nTo define abstract tests, you should organize your code like this:\n\n1.  Put the definition of the parameterized test fixture class (e.g. `FooTest`)\n    in a header file, say `foo_param_test.h`. Think of this as *declaring* your\n    abstract tests.\n2.  Put the `TEST_P` definitions in `foo_param_test.cc`, which includes\n    `foo_param_test.h`. Think of this as *implementing* your abstract tests.\n\nOnce they are defined, you can instantiate them by including `foo_param_test.h`,\ninvoking `INSTANTIATE_TEST_SUITE_P()`, and depending on the library target that\ncontains `foo_param_test.cc`. You can instantiate the same abstract test suite\nmultiple times, possibly in different source files.\n\n### Specifying Names for Value-Parameterized Test Parameters\n\nThe optional last argument to `INSTANTIATE_TEST_SUITE_P()` allows the user to\nspecify a function or functor that generates custom test name suffixes based on\nthe test parameters. The function should accept one argument of type\n`testing::TestParamInfo<class ParamType>`, and return `std::string`.\n\n`testing::PrintToStringParamName` is a builtin test suffix generator that\nreturns the value of `testing::PrintToString(GetParam())`. It does not work for\n`std::string` or C strings.\n\n{: .callout .note}\nNOTE: test names must be non-empty, unique, and may only contain ASCII\nalphanumeric characters. In particular, they\n[should not contain underscores](faq.md#why-should-test-suite-names-and-test-names-not-contain-underscore)\n\n```c++\nclass MyTestSuite : public testing::TestWithParam<int> {};\n\nTEST_P(MyTestSuite, MyTest)\n{\n  std::cout << \"Example Test Param: \" << GetParam() << std::endl;\n}\n\nINSTANTIATE_TEST_SUITE_P(MyGroup, MyTestSuite, testing::Range(0, 10),\n                         testing::PrintToStringParamName());\n```\n\nProviding a custom functor allows for more control over test parameter name\ngeneration, especially for types where the automatic conversion does not\ngenerate helpful parameter names (e.g. strings as demonstrated above). The\nfollowing example illustrates this for multiple parameters, an enumeration type\nand a string, and also demonstrates how to combine generators. It uses a lambda\nfor conciseness:\n\n```c++\nenum class MyType { MY_FOO = 0, MY_BAR = 1 };\n\nclass MyTestSuite : public testing::TestWithParam<std::tuple<MyType, std::string>> {\n};\n\nINSTANTIATE_TEST_SUITE_P(\n    MyGroup, MyTestSuite,\n    testing::Combine(\n        testing::Values(MyType::MY_FOO, MyType::MY_BAR),\n        testing::Values(\"A\", \"B\")),\n    [](const testing::TestParamInfo<MyTestSuite::ParamType>& info) {\n      std::string name = absl::StrCat(\n          std::get<0>(info.param) == MyType::MY_FOO ? \"Foo\" : \"Bar\",\n          std::get<1>(info.param));\n      absl::c_replace_if(name, [](char c) { return !std::isalnum(c); }, '_');\n      return name;\n    });\n```\n\n## Typed Tests\n\nSuppose you have multiple implementations of the same interface and want to make\nsure that all of them satisfy some common requirements. Or, you may have defined\nseveral types that are supposed to conform to the same \"concept\" and you want to\nverify it. In both cases, you want the same test logic repeated for different\ntypes.\n\nWhile you can write one `TEST` or `TEST_F` for each type you want to test (and\nyou may even factor the test logic into a function template that you invoke from\nthe `TEST`), it's tedious and doesn't scale: if you want `m` tests over `n`\ntypes, you'll end up writing `m*n` `TEST`s.\n\n*Typed tests* allow you to repeat the same test logic over a list of types. You\nonly need to write the test logic once, although you must know the type list\nwhen writing typed tests. Here's how you do it:\n\nFirst, define a fixture class template. It should be parameterized by a type.\nRemember to derive it from `::testing::Test`:\n\n```c++\ntemplate <typename T>\nclass FooTest : public testing::Test {\n public:\n  ...\n  using List = std::list<T>;\n  static T shared_;\n  T value_;\n};\n```\n\nNext, associate a list of types with the test suite, which will be repeated for\neach type in the list:\n\n```c++\nusing MyTypes = ::testing::Types<char, int, unsigned int>;\nTYPED_TEST_SUITE(FooTest, MyTypes);\n```\n\nThe type alias (`using` or `typedef`) is necessary for the `TYPED_TEST_SUITE`\nmacro to parse correctly. Otherwise the compiler will think that each comma in\nthe type list introduces a new macro argument.\n\nThen, use `TYPED_TEST()` instead of `TEST_F()` to define a typed test for this\ntest suite. You can repeat this as many times as you want:\n\n```c++\nTYPED_TEST(FooTest, DoesBlah) {\n  // Inside a test, refer to the special name TypeParam to get the type\n  // parameter.  Since we are inside a derived class template, C++ requires\n  // us to visit the members of FooTest via 'this'.\n  TypeParam n = this->value_;\n\n  // To visit static members of the fixture, add the 'TestFixture::'\n  // prefix.\n  n += TestFixture::shared_;\n\n  // To refer to typedefs in the fixture, add the 'typename TestFixture::'\n  // prefix.  The 'typename' is required to satisfy the compiler.\n  typename TestFixture::List values;\n\n  values.push_back(n);\n  ...\n}\n\nTYPED_TEST(FooTest, HasPropertyA) { ... }\n```\n\nYou can see [sample6_unittest.cc] for a complete example.\n\n[sample6_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample6_unittest.cc \"Typed Test example\"\n\n## Type-Parameterized Tests\n\n*Type-parameterized tests* are like typed tests, except that they don't require\nyou to know the list of types ahead of time. Instead, you can define the test\nlogic first and instantiate it with different type lists later. You can even\ninstantiate it more than once in the same program.\n\nIf you are designing an interface or concept, you can define a suite of\ntype-parameterized tests to verify properties that any valid implementation of\nthe interface/concept should have. Then, the author of each implementation can\njust instantiate the test suite with their type to verify that it conforms to\nthe requirements, without having to write similar tests repeatedly. Here's an\nexample:\n\nFirst, define a fixture class template, as we did with typed tests:\n\n```c++\ntemplate <typename T>\nclass FooTest : public testing::Test {\n  void DoSomethingInteresting();\n  ...\n};\n```\n\nNext, declare that you will define a type-parameterized test suite:\n\n```c++\nTYPED_TEST_SUITE_P(FooTest);\n```\n\nThen, use `TYPED_TEST_P()` to define a type-parameterized test. You can repeat\nthis as many times as you want:\n\n```c++\nTYPED_TEST_P(FooTest, DoesBlah) {\n  // Inside a test, refer to TypeParam to get the type parameter.\n  TypeParam n = 0;\n\n  // You will need to use `this` explicitly to refer to fixture members.\n  this->DoSomethingInteresting()\n  ...\n}\n\nTYPED_TEST_P(FooTest, HasPropertyA) { ... }\n```\n\nNow the tricky part: you need to register all test patterns using the\n`REGISTER_TYPED_TEST_SUITE_P` macro before you can instantiate them. The first\nargument of the macro is the test suite name; the rest are the names of the\ntests in this test suite:\n\n```c++\nREGISTER_TYPED_TEST_SUITE_P(FooTest,\n                            DoesBlah, HasPropertyA);\n```\n\nFinally, you are free to instantiate the pattern with the types you want. If you\nput the above code in a header file, you can `#include` it in multiple C++\nsource files and instantiate it multiple times.\n\n```c++\nusing MyTypes = ::testing::Types<char, int, unsigned int>;\nINSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);\n```\n\nTo distinguish different instances of the pattern, the first argument to the\n`INSTANTIATE_TYPED_TEST_SUITE_P` macro is a prefix that will be added to the\nactual test suite name. Remember to pick unique prefixes for different\ninstances.\n\nIn the special case where the type list contains only one type, you can write\nthat type directly without `::testing::Types<...>`, like this:\n\n```c++\nINSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, int);\n```\n\nYou can see [sample6_unittest.cc] for a complete example.\n\n## Testing Private Code\n\nIf you change your software's internal implementation, your tests should not\nbreak as long as the change is not observable by users. Therefore, **per the\nblack-box testing principle, most of the time you should test your code through\nits public interfaces.**\n\n**If you still find yourself needing to test internal implementation code,\nconsider if there's a better design.** The desire to test internal\nimplementation is often a sign that the class is doing too much. Consider\nextracting an implementation class, and testing it. Then use that implementation\nclass in the original class.\n\nIf you absolutely have to test non-public interface code though, you can. There\nare two cases to consider:\n\n*   Static functions ( *not* the same as static member functions!) or unnamed\n    namespaces, and\n*   Private or protected class members\n\nTo test them, we use the following special techniques:\n\n*   Both static functions and definitions/declarations in an unnamed namespace\n    are only visible within the same translation unit. To test them, you can\n    `#include` the entire `.cc` file being tested in your `*_test.cc` file.\n    (#including `.cc` files is not a good way to reuse code - you should not do\n    this in production code!)\n\n    However, a better approach is to move the private code into the\n    `foo::internal` namespace, where `foo` is the namespace your project\n    normally uses, and put the private declarations in a `*-internal.h` file.\n    Your production `.cc` files and your tests are allowed to include this\n    internal header, but your clients are not. This way, you can fully test your\n    internal implementation without leaking it to your clients.\n\n*   Private class members are only accessible from within the class or by\n    friends. To access a class' private members, you can declare your test\n    fixture as a friend to the class and define accessors in your fixture. Tests\n    using the fixture can then access the private members of your production\n    class via the accessors in the fixture. Note that even though your fixture\n    is a friend to your production class, your tests are not automatically\n    friends to it, as they are technically defined in sub-classes of the\n    fixture.\n\n    Another way to test private members is to refactor them into an\n    implementation class, which is then declared in a `*-internal.h` file. Your\n    clients aren't allowed to include this header but your tests can. Such is\n    called the\n    [Pimpl](https://www.gamedev.net/articles/programming/general-and-gameplay-programming/the-c-pimpl-r1794/)\n    (Private Implementation) idiom.\n\n    Or, you can declare an individual test as a friend of your class by adding\n    this line in the class body:\n\n    ```c++\n        FRIEND_TEST(TestSuiteName, TestName);\n    ```\n\n    For example,\n\n    ```c++\n    // foo.h\n    class Foo {\n      ...\n     private:\n      FRIEND_TEST(FooTest, BarReturnsZeroOnNull);\n\n      int Bar(void* x);\n    };\n\n    // foo_test.cc\n    ...\n    TEST(FooTest, BarReturnsZeroOnNull) {\n      Foo foo;\n      EXPECT_EQ(foo.Bar(NULL), 0);  // Uses Foo's private member Bar().\n    }\n    ```\n\n    Pay special attention when your class is defined in a namespace. If you want\n    your test fixtures and tests to be friends of your class, then they must be\n    defined in the exact same namespace (no anonymous or inline namespaces).\n\n    For example, if the code to be tested looks like:\n\n    ```c++\n    namespace my_namespace {\n\n    class Foo {\n      friend class FooTest;\n      FRIEND_TEST(FooTest, Bar);\n      FRIEND_TEST(FooTest, Baz);\n      ... definition of the class Foo ...\n    };\n\n    }  // namespace my_namespace\n    ```\n\n    Your test code should be something like:\n\n    ```c++\n    namespace my_namespace {\n\n    class FooTest : public testing::Test {\n     protected:\n      ...\n    };\n\n    TEST_F(FooTest, Bar) { ... }\n    TEST_F(FooTest, Baz) { ... }\n\n    }  // namespace my_namespace\n    ```\n\n## \"Catching\" Failures\n\nIf you are building a testing utility on top of googletest, you'll want to test\nyour utility. What framework would you use to test it? googletest, of course.\n\nThe challenge is to verify that your testing utility reports failures correctly.\nIn frameworks that report a failure by throwing an exception, you could catch\nthe exception and assert on it. But googletest doesn't use exceptions, so how do\nwe test that a piece of code generates an expected failure?\n\n`\"gtest/gtest-spi.h\"` contains some constructs to do this.\nAfter #including this header, you can use\n\n```c++\n  EXPECT_FATAL_FAILURE(statement, substring);\n```\n\nto assert that `statement` generates a fatal (e.g. `ASSERT_*`) failure in the\ncurrent thread whose message contains the given `substring`, or use\n\n```c++\n  EXPECT_NONFATAL_FAILURE(statement, substring);\n```\n\nif you are expecting a non-fatal (e.g. `EXPECT_*`) failure.\n\nOnly failures in the current thread are checked to determine the result of this\ntype of expectations. If `statement` creates new threads, failures in these\nthreads are also ignored. If you want to catch failures in other threads as\nwell, use one of the following macros instead:\n\n```c++\n  EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substring);\n  EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substring);\n```\n\n{: .callout .note}\nNOTE: Assertions from multiple threads are currently not supported on Windows.\n\nFor technical reasons, there are some caveats:\n\n1.  You cannot stream a failure message to either macro.\n\n2.  `statement` in `EXPECT_FATAL_FAILURE{_ON_ALL_THREADS}()` cannot reference\n    local non-static variables or non-static members of `this` object.\n\n3.  `statement` in `EXPECT_FATAL_FAILURE{_ON_ALL_THREADS}()` cannot return a\n    value.\n\n## Registering tests programmatically\n\nThe `TEST` macros handle the vast majority of all use cases, but there are few\nwhere runtime registration logic is required. For those cases, the framework\nprovides the `::testing::RegisterTest` that allows callers to register arbitrary\ntests dynamically.\n\nThis is an advanced API only to be used when the `TEST` macros are insufficient.\nThe macros should be preferred when possible, as they avoid most of the\ncomplexity of calling this function.\n\nIt provides the following signature:\n\n```c++\ntemplate <typename Factory>\nTestInfo* RegisterTest(const char* test_suite_name, const char* test_name,\n                       const char* type_param, const char* value_param,\n                       const char* file, int line, Factory factory);\n```\n\nThe `factory` argument is a factory callable (move-constructible) object or\nfunction pointer that creates a new instance of the Test object. It handles\nownership to the caller. The signature of the callable is `Fixture*()`, where\n`Fixture` is the test fixture class for the test. All tests registered with the\nsame `test_suite_name` must return the same fixture type. This is checked at\nruntime.\n\nThe framework will infer the fixture class from the factory and will call the\n`SetUpTestSuite` and `TearDownTestSuite` for it.\n\nMust be called before `RUN_ALL_TESTS()` is invoked, otherwise behavior is\nundefined.\n\nUse case example:\n\n```c++\nclass MyFixture : public testing::Test {\n public:\n  // All of these optional, just like in regular macro usage.\n  static void SetUpTestSuite() { ... }\n  static void TearDownTestSuite() { ... }\n  void SetUp() override { ... }\n  void TearDown() override { ... }\n};\n\nclass MyTest : public MyFixture {\n public:\n  explicit MyTest(int data) : data_(data) {}\n  void TestBody() override { ... }\n\n private:\n  int data_;\n};\n\nvoid RegisterMyTests(const std::vector<int>& values) {\n  for (int v : values) {\n    testing::RegisterTest(\n        \"MyFixture\", (\"Test\" + std::to_string(v)).c_str(), nullptr,\n        std::to_string(v).c_str(),\n        __FILE__, __LINE__,\n        // Important to use the fixture type as the return type here.\n        [=]() -> MyFixture* { return new MyTest(v); });\n  }\n}\n...\nint main(int argc, char** argv) {\n  testing::InitGoogleTest(&argc, argv);\n  std::vector<int> values_to_test = LoadValuesFromConfig();\n  RegisterMyTests(values_to_test);\n  ...\n  return RUN_ALL_TESTS();\n}\n```\n\n## Getting the Current Test's Name\n\nSometimes a function may need to know the name of the currently running test.\nFor example, you may be using the `SetUp()` method of your test fixture to set\nthe golden file name based on which test is running. The\n[`TestInfo`](reference/testing.md#TestInfo) class has this information.\n\nTo obtain a `TestInfo` object for the currently running test, call\n`current_test_info()` on the [`UnitTest`](reference/testing.md#UnitTest)\nsingleton object:\n\n```c++\n  // Gets information about the currently running test.\n  // Do NOT delete the returned object - it's managed by the UnitTest class.\n  const testing::TestInfo* const test_info =\n      testing::UnitTest::GetInstance()->current_test_info();\n\n  printf(\"We are in test %s of test suite %s.\\n\",\n         test_info->name(),\n         test_info->test_suite_name());\n```\n\n`current_test_info()` returns a null pointer if no test is running. In\nparticular, you cannot find the test suite name in `SetUpTestSuite()`,\n`TearDownTestSuite()` (where you know the test suite name implicitly), or\nfunctions called from them.\n\n## Extending googletest by Handling Test Events\n\ngoogletest provides an **event listener API** to let you receive notifications\nabout the progress of a test program and test failures. The events you can\nlisten to include the start and end of the test program, a test suite, or a test\nmethod, among others. You may use this API to augment or replace the standard\nconsole output, replace the XML output, or provide a completely different form\nof output, such as a GUI or a database. You can also use test events as\ncheckpoints to implement a resource leak checker, for example.\n\n### Defining Event Listeners\n\nTo define a event listener, you subclass either\n[`testing::TestEventListener`](reference/testing.md#TestEventListener) or\n[`testing::EmptyTestEventListener`](reference/testing.md#EmptyTestEventListener)\nThe former is an (abstract) interface, where *each pure virtual method can be\noverridden to handle a test event* (For example, when a test starts, the\n`OnTestStart()` method will be called.). The latter provides an empty\nimplementation of all methods in the interface, such that a subclass only needs\nto override the methods it cares about.\n\nWhen an event is fired, its context is passed to the handler function as an\nargument. The following argument types are used:\n\n*   UnitTest reflects the state of the entire test program,\n*   TestSuite has information about a test suite, which can contain one or more\n    tests,\n*   TestInfo contains the state of a test, and\n*   TestPartResult represents the result of a test assertion.\n\nAn event handler function can examine the argument it receives to find out\ninteresting information about the event and the test program's state.\n\nHere's an example:\n\n```c++\n  class MinimalistPrinter : public testing::EmptyTestEventListener {\n    // Called before a test starts.\n    void OnTestStart(const testing::TestInfo& test_info) override {\n      printf(\"*** Test %s.%s starting.\\n\",\n             test_info.test_suite_name(), test_info.name());\n    }\n\n    // Called after a failed assertion or a SUCCESS().\n    void OnTestPartResult(const testing::TestPartResult& test_part_result) override {\n      printf(\"%s in %s:%d\\n%s\\n\",\n             test_part_result.failed() ? \"*** Failure\" : \"Success\",\n             test_part_result.file_name(),\n             test_part_result.line_number(),\n             test_part_result.summary());\n    }\n\n    // Called after a test ends.\n    void OnTestEnd(const testing::TestInfo& test_info) override {\n      printf(\"*** Test %s.%s ending.\\n\",\n             test_info.test_suite_name(), test_info.name());\n    }\n  };\n```\n\n### Using Event Listeners\n\nTo use the event listener you have defined, add an instance of it to the\ngoogletest event listener list (represented by class\n[`TestEventListeners`](reference/testing.md#TestEventListeners) - note the \"s\"\nat the end of the name) in your `main()` function, before calling\n`RUN_ALL_TESTS()`:\n\n```c++\nint main(int argc, char** argv) {\n  testing::InitGoogleTest(&argc, argv);\n  // Gets hold of the event listener list.\n  testing::TestEventListeners& listeners =\n      testing::UnitTest::GetInstance()->listeners();\n  // Adds a listener to the end.  googletest takes the ownership.\n  listeners.Append(new MinimalistPrinter);\n  return RUN_ALL_TESTS();\n}\n```\n\nThere's only one problem: the default test result printer is still in effect, so\nits output will mingle with the output from your minimalist printer. To suppress\nthe default printer, just release it from the event listener list and delete it.\nYou can do so by adding one line:\n\n```c++\n  ...\n  delete listeners.Release(listeners.default_result_printer());\n  listeners.Append(new MinimalistPrinter);\n  return RUN_ALL_TESTS();\n```\n\nNow, sit back and enjoy a completely different output from your tests. For more\ndetails, see [sample9_unittest.cc].\n\n[sample9_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample9_unittest.cc \"Event listener example\"\n\nYou may append more than one listener to the list. When an `On*Start()` or\n`OnTestPartResult()` event is fired, the listeners will receive it in the order\nthey appear in the list (since new listeners are added to the end of the list,\nthe default text printer and the default XML generator will receive the event\nfirst). An `On*End()` event will be received by the listeners in the *reverse*\norder. This allows output by listeners added later to be framed by output from\nlisteners added earlier.\n\n### Generating Failures in Listeners\n\nYou may use failure-raising macros (`EXPECT_*()`, `ASSERT_*()`, `FAIL()`, etc)\nwhen processing an event. There are some restrictions:\n\n1.  You cannot generate any failure in `OnTestPartResult()` (otherwise it will\n    cause `OnTestPartResult()` to be called recursively).\n2.  A listener that handles `OnTestPartResult()` is not allowed to generate any\n    failure.\n\nWhen you add listeners to the listener list, you should put listeners that\nhandle `OnTestPartResult()` *before* listeners that can generate failures. This\nensures that failures generated by the latter are attributed to the right test\nby the former.\n\nSee [sample10_unittest.cc] for an example of a failure-raising listener.\n\n[sample10_unittest.cc]: https://github.com/google/googletest/blob/master/googletest/samples/sample10_unittest.cc \"Failure-raising listener example\"\n\n## Running Test Programs: Advanced Options\n\ngoogletest test programs are ordinary executables. Once built, you can run them\ndirectly and affect their behavior via the following environment variables\nand/or command line flags. For the flags to work, your programs must call\n`::testing::InitGoogleTest()` before calling `RUN_ALL_TESTS()`.\n\nTo see a list of supported flags and their usage, please run your test program\nwith the `--help` flag. You can also use `-h`, `-?`, or `/?` for short.\n\nIf an option is specified both by an environment variable and by a flag, the\nlatter takes precedence.\n\n### Selecting Tests\n\n#### Listing Test Names\n\nSometimes it is necessary to list the available tests in a program before\nrunning them so that a filter may be applied if needed. Including the flag\n`--gtest_list_tests` overrides all other flags and lists tests in the following\nformat:\n\n```none\nTestSuite1.\n  TestName1\n  TestName2\nTestSuite2.\n  TestName\n```\n\nNone of the tests listed are actually run if the flag is provided. There is no\ncorresponding environment variable for this flag.\n\n#### Running a Subset of the Tests\n\nBy default, a googletest program runs all tests the user has defined. Sometimes,\nyou want to run only a subset of the tests (e.g. for debugging or quickly\nverifying a change). If you set the `GTEST_FILTER` environment variable or the\n`--gtest_filter` flag to a filter string, googletest will only run the tests\nwhose full names (in the form of `TestSuiteName.TestName`) match the filter.\n\nThe format of a filter is a '`:`'-separated list of wildcard patterns (called\nthe *positive patterns*) optionally followed by a '`-`' and another\n'`:`'-separated pattern list (called the *negative patterns*). A test matches\nthe filter if and only if it matches any of the positive patterns but does not\nmatch any of the negative patterns.\n\nA pattern may contain `'*'` (matches any string) or `'?'` (matches any single\ncharacter). For convenience, the filter `'*-NegativePatterns'` can be also\nwritten as `'-NegativePatterns'`.\n\nFor example:\n\n*   `./foo_test` Has no flag, and thus runs all its tests.\n*   `./foo_test --gtest_filter=*` Also runs everything, due to the single\n    match-everything `*` value.\n*   `./foo_test --gtest_filter=FooTest.*` Runs everything in test suite\n    `FooTest` .\n*   `./foo_test --gtest_filter=*Null*:*Constructor*` Runs any test whose full\n    name contains either `\"Null\"` or `\"Constructor\"` .\n*   `./foo_test --gtest_filter=-*DeathTest.*` Runs all non-death tests.\n*   `./foo_test --gtest_filter=FooTest.*-FooTest.Bar` Runs everything in test\n    suite `FooTest` except `FooTest.Bar`.\n*   `./foo_test --gtest_filter=FooTest.*:BarTest.*-FooTest.Bar:BarTest.Foo` Runs\n    everything in test suite `FooTest` except `FooTest.Bar` and everything in\n    test suite `BarTest` except `BarTest.Foo`.\n\n#### Stop test execution upon first failure\n\nBy default, a googletest program runs all tests the user has defined. In some\ncases (e.g. iterative test development & execution) it may be desirable stop\ntest execution upon first failure (trading improved latency for completeness).\nIf `GTEST_FAIL_FAST` environment variable or `--gtest_fail_fast` flag is set,\nthe test runner will stop execution as soon as the first test failure is found.\n\n#### Temporarily Disabling Tests\n\nIf you have a broken test that you cannot fix right away, you can add the\n`DISABLED_` prefix to its name. This will exclude it from execution. This is\nbetter than commenting out the code or using `#if 0`, as disabled tests are\nstill compiled (and thus won't rot).\n\nIf you need to disable all tests in a test suite, you can either add `DISABLED_`\nto the front of the name of each test, or alternatively add it to the front of\nthe test suite name.\n\nFor example, the following tests won't be run by googletest, even though they\nwill still be compiled:\n\n```c++\n// Tests that Foo does Abc.\nTEST(FooTest, DISABLED_DoesAbc) { ... }\n\nclass DISABLED_BarTest : public testing::Test { ... };\n\n// Tests that Bar does Xyz.\nTEST_F(DISABLED_BarTest, DoesXyz) { ... }\n```\n\n{: .callout .note}\nNOTE: This feature should only be used for temporary pain-relief. You still have\nto fix the disabled tests at a later date. As a reminder, googletest will print\na banner warning you if a test program contains any disabled tests.\n\n{: .callout .tip}\nTIP: You can easily count the number of disabled tests you have using\n`grep`. This number can be used as a metric for\nimproving your test quality.\n\n#### Temporarily Enabling Disabled Tests\n\nTo include disabled tests in test execution, just invoke the test program with\nthe `--gtest_also_run_disabled_tests` flag or set the\n`GTEST_ALSO_RUN_DISABLED_TESTS` environment variable to a value other than `0`.\nYou can combine this with the `--gtest_filter` flag to further select which\ndisabled tests to run.\n\n### Repeating the Tests\n\nOnce in a while you'll run into a test whose result is hit-or-miss. Perhaps it\nwill fail only 1% of the time, making it rather hard to reproduce the bug under\na debugger. This can be a major source of frustration.\n\nThe `--gtest_repeat` flag allows you to repeat all (or selected) test methods in\na program many times. Hopefully, a flaky test will eventually fail and give you\na chance to debug. Here's how to use it:\n\n```none\n$ foo_test --gtest_repeat=1000\nRepeat foo_test 1000 times and don't stop at failures.\n\n$ foo_test --gtest_repeat=-1\nA negative count means repeating forever.\n\n$ foo_test --gtest_repeat=1000 --gtest_break_on_failure\nRepeat foo_test 1000 times, stopping at the first failure.  This\nis especially useful when running under a debugger: when the test\nfails, it will drop into the debugger and you can then inspect\nvariables and stacks.\n\n$ foo_test --gtest_repeat=1000 --gtest_filter=FooBar.*\nRepeat the tests whose name matches the filter 1000 times.\n```\n\nIf your test program contains\n[global set-up/tear-down](#global-set-up-and-tear-down) code, it will be\nrepeated in each iteration as well, as the flakiness may be in it. You can also\nspecify the repeat count by setting the `GTEST_REPEAT` environment variable.\n\n### Shuffling the Tests\n\nYou can specify the `--gtest_shuffle` flag (or set the `GTEST_SHUFFLE`\nenvironment variable to `1`) to run the tests in a program in a random order.\nThis helps to reveal bad dependencies between tests.\n\nBy default, googletest uses a random seed calculated from the current time.\nTherefore you'll get a different order every time. The console output includes\nthe random seed value, such that you can reproduce an order-related test failure\nlater. To specify the random seed explicitly, use the `--gtest_random_seed=SEED`\nflag (or set the `GTEST_RANDOM_SEED` environment variable), where `SEED` is an\ninteger in the range [0, 99999]. The seed value 0 is special: it tells\ngoogletest to do the default behavior of calculating the seed from the current\ntime.\n\nIf you combine this with `--gtest_repeat=N`, googletest will pick a different\nrandom seed and re-shuffle the tests in each iteration.\n\n### Distributing Test Functions to Multiple Machines\n\nIf you have more than one machine you can use to run a test program, you might\nwant to run the test functions in parallel and get the result faster. We call\nthis technique *sharding*, where each machine is called a *shard*.\n\nGoogleTest is compatible with test sharding. To take advantage of this feature,\nyour test runner (not part of GoogleTest) needs to do the following:\n\n1.  Allocate a number of machines (shards) to run the tests.\n1.  On each shard, set the `GTEST_TOTAL_SHARDS` environment variable to the total\n    number of shards. It must be the same for all shards.\n1.  On each shard, set the `GTEST_SHARD_INDEX` environment variable to the index\n    of the shard. Different shards must be assigned different indices, which\n    must be in the range `[0, GTEST_TOTAL_SHARDS - 1]`.\n1.  Run the same test program on all shards. When GoogleTest sees the above two\n    environment variables, it will select a subset of the test functions to run.\n    Across all shards, each test function in the program will be run exactly\n    once.\n1.  Wait for all shards to finish, then collect and report the results.\n\nYour project may have tests that were written without GoogleTest and thus don't\nunderstand this protocol. In order for your test runner to figure out which test\nsupports sharding, it can set the environment variable `GTEST_SHARD_STATUS_FILE`\nto a non-existent file path. If a test program supports sharding, it will create\nthis file to acknowledge that fact; otherwise it will not create it. The actual\ncontents of the file are not important at this time, although we may put some\nuseful information in it in the future.\n\nHere's an example to make it clear. Suppose you have a test program `foo_test`\nthat contains the following 5 test functions:\n\n```\nTEST(A, V)\nTEST(A, W)\nTEST(B, X)\nTEST(B, Y)\nTEST(B, Z)\n```\n\nSuppose you have 3 machines at your disposal. To run the test functions in\nparallel, you would set `GTEST_TOTAL_SHARDS` to 3 on all machines, and set\n`GTEST_SHARD_INDEX` to 0, 1, and 2 on the machines respectively. Then you would\nrun the same `foo_test` on each machine.\n\nGoogleTest reserves the right to change how the work is distributed across the\nshards, but here's one possible scenario:\n\n*   Machine #0 runs `A.V` and `B.X`.\n*   Machine #1 runs `A.W` and `B.Y`.\n*   Machine #2 runs `B.Z`.\n\n### Controlling Test Output\n\n#### Colored Terminal Output\n\ngoogletest can use colors in its terminal output to make it easier to spot the\nimportant information:\n\n<pre>...\n<font color=\"green\">[----------]</font> 1 test from FooTest\n<font color=\"green\">[ RUN      ]</font> FooTest.DoesAbc\n<font color=\"green\">[       OK ]</font> FooTest.DoesAbc\n<font color=\"green\">[----------]</font> 2 tests from BarTest\n<font color=\"green\">[ RUN      ]</font> BarTest.HasXyzProperty\n<font color=\"green\">[       OK ]</font> BarTest.HasXyzProperty\n<font color=\"green\">[ RUN      ]</font> BarTest.ReturnsTrueOnSuccess\n... some error messages ...\n<font color=\"red\">[   FAILED ]</font> BarTest.ReturnsTrueOnSuccess\n...\n<font color=\"green\">[==========]</font> 30 tests from 14 test suites ran.\n<font color=\"green\">[   PASSED ]</font> 28 tests.\n<font color=\"red\">[   FAILED ]</font> 2 tests, listed below:\n<font color=\"red\">[   FAILED ]</font> BarTest.ReturnsTrueOnSuccess\n<font color=\"red\">[   FAILED ]</font> AnotherTest.DoesXyz\n\n 2 FAILED TESTS\n</pre>\n\nYou can set the `GTEST_COLOR` environment variable or the `--gtest_color`\ncommand line flag to `yes`, `no`, or `auto` (the default) to enable colors,\ndisable colors, or let googletest decide. When the value is `auto`, googletest\nwill use colors if and only if the output goes to a terminal and (on non-Windows\nplatforms) the `TERM` environment variable is set to `xterm` or `xterm-color`.\n\n#### Suppressing test passes\n\nBy default, googletest prints 1 line of output for each test, indicating if it\npassed or failed. To show only test failures, run the test program with\n`--gtest_brief=1`, or set the GTEST_BRIEF environment variable to `1`.\n\n#### Suppressing the Elapsed Time\n\nBy default, googletest prints the time it takes to run each test. To disable\nthat, run the test program with the `--gtest_print_time=0` command line flag, or\nset the GTEST_PRINT_TIME environment variable to `0`.\n\n#### Suppressing UTF-8 Text Output\n\nIn case of assertion failures, googletest prints expected and actual values of\ntype `string` both as hex-encoded strings as well as in readable UTF-8 text if\nthey contain valid non-ASCII UTF-8 characters. If you want to suppress the UTF-8\ntext because, for example, you don't have an UTF-8 compatible output medium, run\nthe test program with `--gtest_print_utf8=0` or set the `GTEST_PRINT_UTF8`\nenvironment variable to `0`.\n\n#### Generating an XML Report\n\ngoogletest can emit a detailed XML report to a file in addition to its normal\ntextual output. The report contains the duration of each test, and thus can help\nyou identify slow tests.\n\nTo generate the XML report, set the `GTEST_OUTPUT` environment variable or the\n`--gtest_output` flag to the string `\"xml:path_to_output_file\"`, which will\ncreate the file at the given location. You can also just use the string `\"xml\"`,\nin which case the output can be found in the `test_detail.xml` file in the\ncurrent directory.\n\nIf you specify a directory (for example, `\"xml:output/directory/\"` on Linux or\n`\"xml:output\\directory\\\"` on Windows), googletest will create the XML file in\nthat directory, named after the test executable (e.g. `foo_test.xml` for test\nprogram `foo_test` or `foo_test.exe`). If the file already exists (perhaps left\nover from a previous run), googletest will pick a different name (e.g.\n`foo_test_1.xml`) to avoid overwriting it.\n\nThe report is based on the `junitreport` Ant task. Since that format was\noriginally intended for Java, a little interpretation is required to make it\napply to googletest tests, as shown here:\n\n```xml\n<testsuites name=\"AllTests\" ...>\n  <testsuite name=\"test_case_name\" ...>\n    <testcase    name=\"test_name\" ...>\n      <failure message=\"...\"/>\n      <failure message=\"...\"/>\n      <failure message=\"...\"/>\n    </testcase>\n  </testsuite>\n</testsuites>\n```\n\n*   The root `<testsuites>` element corresponds to the entire test program.\n*   `<testsuite>` elements correspond to googletest test suites.\n*   `<testcase>` elements correspond to googletest test functions.\n\nFor instance, the following program\n\n```c++\nTEST(MathTest, Addition) { ... }\nTEST(MathTest, Subtraction) { ... }\nTEST(LogicTest, NonContradiction) { ... }\n```\n\ncould generate this report:\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<testsuites tests=\"3\" failures=\"1\" errors=\"0\" time=\"0.035\" timestamp=\"2011-10-31T18:52:42\" name=\"AllTests\">\n  <testsuite name=\"MathTest\" tests=\"2\" failures=\"1\" errors=\"0\" time=\"0.015\">\n    <testcase name=\"Addition\" file=\"test.cpp\" line=\"1\" status=\"run\" time=\"0.007\" classname=\"\">\n      <failure message=\"Value of: add(1, 1)&#x0A;  Actual: 3&#x0A;Expected: 2\" type=\"\">...</failure>\n      <failure message=\"Value of: add(1, -1)&#x0A;  Actual: 1&#x0A;Expected: 0\" type=\"\">...</failure>\n    </testcase>\n    <testcase name=\"Subtraction\" file=\"test.cpp\" line=\"2\" status=\"run\" time=\"0.005\" classname=\"\">\n    </testcase>\n  </testsuite>\n  <testsuite name=\"LogicTest\" tests=\"1\" failures=\"0\" errors=\"0\" time=\"0.005\">\n    <testcase name=\"NonContradiction\" file=\"test.cpp\" line=\"3\" status=\"run\" time=\"0.005\" classname=\"\">\n    </testcase>\n  </testsuite>\n</testsuites>\n```\n\nThings to note:\n\n*   The `tests` attribute of a `<testsuites>` or `<testsuite>` element tells how\n    many test functions the googletest program or test suite contains, while the\n    `failures` attribute tells how many of them failed.\n\n*   The `time` attribute expresses the duration of the test, test suite, or\n    entire test program in seconds.\n\n*   The `timestamp` attribute records the local date and time of the test\n    execution.\n\n*   The `file` and `line` attributes record the source file location, where the\n    test was defined.\n\n*   Each `<failure>` element corresponds to a single failed googletest\n    assertion.\n\n#### Generating a JSON Report\n\ngoogletest can also emit a JSON report as an alternative format to XML. To\ngenerate the JSON report, set the `GTEST_OUTPUT` environment variable or the\n`--gtest_output` flag to the string `\"json:path_to_output_file\"`, which will\ncreate the file at the given location. You can also just use the string\n`\"json\"`, in which case the output can be found in the `test_detail.json` file\nin the current directory.\n\nThe report format conforms to the following JSON Schema:\n\n```json\n{\n  \"$schema\": \"http://json-schema.org/schema#\",\n  \"type\": \"object\",\n  \"definitions\": {\n    \"TestCase\": {\n      \"type\": \"object\",\n      \"properties\": {\n        \"name\": { \"type\": \"string\" },\n        \"tests\": { \"type\": \"integer\" },\n        \"failures\": { \"type\": \"integer\" },\n        \"disabled\": { \"type\": \"integer\" },\n        \"time\": { \"type\": \"string\" },\n        \"testsuite\": {\n          \"type\": \"array\",\n          \"items\": {\n            \"$ref\": \"#/definitions/TestInfo\"\n          }\n        }\n      }\n    },\n    \"TestInfo\": {\n      \"type\": \"object\",\n      \"properties\": {\n        \"name\": { \"type\": \"string\" },\n        \"file\": { \"type\": \"string\" },\n        \"line\": { \"type\": \"integer\" },\n        \"status\": {\n          \"type\": \"string\",\n          \"enum\": [\"RUN\", \"NOTRUN\"]\n        },\n        \"time\": { \"type\": \"string\" },\n        \"classname\": { \"type\": \"string\" },\n        \"failures\": {\n          \"type\": \"array\",\n          \"items\": {\n            \"$ref\": \"#/definitions/Failure\"\n          }\n        }\n      }\n    },\n    \"Failure\": {\n      \"type\": \"object\",\n      \"properties\": {\n        \"failures\": { \"type\": \"string\" },\n        \"type\": { \"type\": \"string\" }\n      }\n    }\n  },\n  \"properties\": {\n    \"tests\": { \"type\": \"integer\" },\n    \"failures\": { \"type\": \"integer\" },\n    \"disabled\": { \"type\": \"integer\" },\n    \"errors\": { \"type\": \"integer\" },\n    \"timestamp\": {\n      \"type\": \"string\",\n      \"format\": \"date-time\"\n    },\n    \"time\": { \"type\": \"string\" },\n    \"name\": { \"type\": \"string\" },\n    \"testsuites\": {\n      \"type\": \"array\",\n      \"items\": {\n        \"$ref\": \"#/definitions/TestCase\"\n      }\n    }\n  }\n}\n```\n\nThe report uses the format that conforms to the following Proto3 using the\n[JSON encoding](https://developers.google.com/protocol-buffers/docs/proto3#json):\n\n```proto\nsyntax = \"proto3\";\n\npackage googletest;\n\nimport \"google/protobuf/timestamp.proto\";\nimport \"google/protobuf/duration.proto\";\n\nmessage UnitTest {\n  int32 tests = 1;\n  int32 failures = 2;\n  int32 disabled = 3;\n  int32 errors = 4;\n  google.protobuf.Timestamp timestamp = 5;\n  google.protobuf.Duration time = 6;\n  string name = 7;\n  repeated TestCase testsuites = 8;\n}\n\nmessage TestCase {\n  string name = 1;\n  int32 tests = 2;\n  int32 failures = 3;\n  int32 disabled = 4;\n  int32 errors = 5;\n  google.protobuf.Duration time = 6;\n  repeated TestInfo testsuite = 7;\n}\n\nmessage TestInfo {\n  string name = 1;\n  string file = 6;\n  int32 line = 7;\n  enum Status {\n    RUN = 0;\n    NOTRUN = 1;\n  }\n  Status status = 2;\n  google.protobuf.Duration time = 3;\n  string classname = 4;\n  message Failure {\n    string failures = 1;\n    string type = 2;\n  }\n  repeated Failure failures = 5;\n}\n```\n\nFor instance, the following program\n\n```c++\nTEST(MathTest, Addition) { ... }\nTEST(MathTest, Subtraction) { ... }\nTEST(LogicTest, NonContradiction) { ... }\n```\n\ncould generate this report:\n\n```json\n{\n  \"tests\": 3,\n  \"failures\": 1,\n  \"errors\": 0,\n  \"time\": \"0.035s\",\n  \"timestamp\": \"2011-10-31T18:52:42Z\",\n  \"name\": \"AllTests\",\n  \"testsuites\": [\n    {\n      \"name\": \"MathTest\",\n      \"tests\": 2,\n      \"failures\": 1,\n      \"errors\": 0,\n      \"time\": \"0.015s\",\n      \"testsuite\": [\n        {\n          \"name\": \"Addition\",\n          \"file\": \"test.cpp\",\n          \"line\": 1,\n          \"status\": \"RUN\",\n          \"time\": \"0.007s\",\n          \"classname\": \"\",\n          \"failures\": [\n            {\n              \"message\": \"Value of: add(1, 1)\\n  Actual: 3\\nExpected: 2\",\n              \"type\": \"\"\n            },\n            {\n              \"message\": \"Value of: add(1, -1)\\n  Actual: 1\\nExpected: 0\",\n              \"type\": \"\"\n            }\n          ]\n        },\n        {\n          \"name\": \"Subtraction\",\n          \"file\": \"test.cpp\",\n          \"line\": 2,\n          \"status\": \"RUN\",\n          \"time\": \"0.005s\",\n          \"classname\": \"\"\n        }\n      ]\n    },\n    {\n      \"name\": \"LogicTest\",\n      \"tests\": 1,\n      \"failures\": 0,\n      \"errors\": 0,\n      \"time\": \"0.005s\",\n      \"testsuite\": [\n        {\n          \"name\": \"NonContradiction\",\n          \"file\": \"test.cpp\",\n          \"line\": 3,\n          \"status\": \"RUN\",\n          \"time\": \"0.005s\",\n          \"classname\": \"\"\n        }\n      ]\n    }\n  ]\n}\n```\n\n{: .callout .important}\nIMPORTANT: The exact format of the JSON document is subject to change.\n\n### Controlling How Failures Are Reported\n\n#### Detecting Test Premature Exit\n\nGoogle Test implements the _premature-exit-file_ protocol for test runners to\ncatch any kind of unexpected exits of test programs. Upon start, Google Test\ncreates the file which will be automatically deleted after all work has been\nfinished. Then, the test runner can check if this file exists. In case the file\nremains undeleted, the inspected test has exited prematurely.\n\nThis feature is enabled only if the `TEST_PREMATURE_EXIT_FILE` environment\nvariable has been set.\n\n#### Turning Assertion Failures into Break-Points\n\nWhen running test programs under a debugger, it's very convenient if the\ndebugger can catch an assertion failure and automatically drop into interactive\nmode. googletest's *break-on-failure* mode supports this behavior.\n\nTo enable it, set the `GTEST_BREAK_ON_FAILURE` environment variable to a value\nother than `0`. Alternatively, you can use the `--gtest_break_on_failure`\ncommand line flag.\n\n#### Disabling Catching Test-Thrown Exceptions\n\ngoogletest can be used either with or without exceptions enabled. If a test\nthrows a C++ exception or (on Windows) a structured exception (SEH), by default\ngoogletest catches it, reports it as a test failure, and continues with the next\ntest method. This maximizes the coverage of a test run. Also, on Windows an\nuncaught exception will cause a pop-up window, so catching the exceptions allows\nyou to run the tests automatically.\n\nWhen debugging the test failures, however, you may instead want the exceptions\nto be handled by the debugger, such that you can examine the call stack when an\nexception is thrown. To achieve that, set the `GTEST_CATCH_EXCEPTIONS`\nenvironment variable to `0`, or use the `--gtest_catch_exceptions=0` flag when\nrunning the tests.\n\n### Sanitizer Integration\n\nThe\n[Undefined Behavior Sanitizer](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html),\n[Address Sanitizer](https://github.com/google/sanitizers/wiki/AddressSanitizer),\nand\n[Thread Sanitizer](https://github.com/google/sanitizers/wiki/ThreadSanitizerCppManual)\nall provide weak functions that you can override to trigger explicit failures\nwhen they detect sanitizer errors, such as creating a reference from `nullptr`.\nTo override these functions, place definitions for them in a source file that\nyou compile as part of your main binary:\n\n```\nextern \"C\" {\nvoid __ubsan_on_report() {\n  FAIL() << \"Encountered an undefined behavior sanitizer error\";\n}\nvoid __asan_on_error() {\n  FAIL() << \"Encountered an address sanitizer error\";\n}\nvoid __tsan_on_report() {\n  FAIL() << \"Encountered a thread sanitizer error\";\n}\n}  // extern \"C\"\n```\n\nAfter compiling your project with one of the sanitizers enabled, if a particular\ntest triggers a sanitizer error, googletest will report that it failed.\n"
  },
  {
    "path": "3rd/googletest-1.12.1/docs/assets/css/style.scss",
    "content": "---\n---\n\n@import \"jekyll-theme-primer\";\n@import \"main\";\n"
  },
  {
    "path": "3rd/googletest-1.12.1/docs/community_created_documentation.md",
    "content": "# Community-Created Documentation\n\nThe following is a list, in no particular order, of links to documentation\ncreated by the Googletest community.\n\n*   [Googlemock Insights](https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/blob/master/googletest/insights.md),\n    by [ElectricRCAircraftGuy](https://github.com/ElectricRCAircraftGuy)\n"
  },
  {
    "path": "3rd/googletest-1.12.1/docs/faq.md",
    "content": "# GoogleTest FAQ\n\n## Why should test suite names and test names not contain underscore?\n\n{: .callout .note}\nNote: GoogleTest reserves underscore (`_`) for special purpose keywords, such as\n[the `DISABLED_` prefix](advanced.md#temporarily-disabling-tests), in addition\nto the following rationale.\n\nUnderscore (`_`) is special, as C++ reserves the following to be used by the\ncompiler and the standard library:\n\n1.  any identifier that starts with an `_` followed by an upper-case letter, and\n2.  any identifier that contains two consecutive underscores (i.e. `__`)\n    *anywhere* in its name.\n\nUser code is *prohibited* from using such identifiers.\n\nNow let's look at what this means for `TEST` and `TEST_F`.\n\nCurrently `TEST(TestSuiteName, TestName)` generates a class named\n`TestSuiteName_TestName_Test`. What happens if `TestSuiteName` or `TestName`\ncontains `_`?\n\n1.  If `TestSuiteName` starts with an `_` followed by an upper-case letter (say,\n    `_Foo`), we end up with `_Foo_TestName_Test`, which is reserved and thus\n    invalid.\n2.  If `TestSuiteName` ends with an `_` (say, `Foo_`), we get\n    `Foo__TestName_Test`, which is invalid.\n3.  If `TestName` starts with an `_` (say, `_Bar`), we get\n    `TestSuiteName__Bar_Test`, which is invalid.\n4.  If `TestName` ends with an `_` (say, `Bar_`), we get\n    `TestSuiteName_Bar__Test`, which is invalid.\n\nSo clearly `TestSuiteName` and `TestName` cannot start or end with `_`\n(Actually, `TestSuiteName` can start with `_` -- as long as the `_` isn't\nfollowed by an upper-case letter. But that's getting complicated. So for\nsimplicity we just say that it cannot start with `_`.).\n\nIt may seem fine for `TestSuiteName` and `TestName` to contain `_` in the\nmiddle. However, consider this:\n\n```c++\nTEST(Time, Flies_Like_An_Arrow) { ... }\nTEST(Time_Flies, Like_An_Arrow) { ... }\n```\n\nNow, the two `TEST`s will both generate the same class\n(`Time_Flies_Like_An_Arrow_Test`). That's not good.\n\nSo for simplicity, we just ask the users to avoid `_` in `TestSuiteName` and\n`TestName`. The rule is more constraining than necessary, but it's simple and\neasy to remember. It also gives GoogleTest some wiggle room in case its\nimplementation needs to change in the future.\n\nIf you violate the rule, there may not be immediate consequences, but your test\nmay (just may) break with a new compiler (or a new version of the compiler you\nare using) or with a new version of GoogleTest. Therefore it's best to follow\nthe rule.\n\n## Why does GoogleTest support `EXPECT_EQ(NULL, ptr)` and `ASSERT_EQ(NULL, ptr)` but not `EXPECT_NE(NULL, ptr)` and `ASSERT_NE(NULL, ptr)`?\n\nFirst of all, you can use `nullptr` with each of these macros, e.g.\n`EXPECT_EQ(ptr, nullptr)`, `EXPECT_NE(ptr, nullptr)`, `ASSERT_EQ(ptr, nullptr)`,\n`ASSERT_NE(ptr, nullptr)`. This is the preferred syntax in the style guide\nbecause `nullptr` does not have the type problems that `NULL` does.\n\nDue to some peculiarity of C++, it requires some non-trivial template meta\nprogramming tricks to support using `NULL` as an argument of the `EXPECT_XX()`\nand `ASSERT_XX()` macros. Therefore we only do it where it's most needed\n(otherwise we make the implementation of GoogleTest harder to maintain and more\nerror-prone than necessary).\n\nHistorically, the `EXPECT_EQ()` macro took the *expected* value as its first\nargument and the *actual* value as the second, though this argument order is now\ndiscouraged. It was reasonable that someone wanted\nto write `EXPECT_EQ(NULL, some_expression)`, and this indeed was requested\nseveral times. Therefore we implemented it.\n\nThe need for `EXPECT_NE(NULL, ptr)` wasn't nearly as strong. When the assertion\nfails, you already know that `ptr` must be `NULL`, so it doesn't add any\ninformation to print `ptr` in this case. That means `EXPECT_TRUE(ptr != NULL)`\nworks just as well.\n\nIf we were to support `EXPECT_NE(NULL, ptr)`, for consistency we'd have to\nsupport `EXPECT_NE(ptr, NULL)` as well. This means using the template meta\nprogramming tricks twice in the implementation, making it even harder to\nunderstand and maintain. We believe the benefit doesn't justify the cost.\n\nFinally, with the growth of the gMock matcher library, we are encouraging people\nto use the unified `EXPECT_THAT(value, matcher)` syntax more often in tests. One\nsignificant advantage of the matcher approach is that matchers can be easily\ncombined to form new matchers, while the `EXPECT_NE`, etc, macros cannot be\neasily combined. Therefore we want to invest more in the matchers than in the\n`EXPECT_XX()` macros.\n\n## I need to test that different implementations of an interface satisfy some common requirements. Should I use typed tests or value-parameterized tests?\n\nFor testing various implementations of the same interface, either typed tests or\nvalue-parameterized tests can get it done. It's really up to you the user to\ndecide which is more convenient for you, depending on your particular case. Some\nrough guidelines:\n\n*   Typed tests can be easier to write if instances of the different\n    implementations can be created the same way, modulo the type. For example,\n    if all these implementations have a public default constructor (such that\n    you can write `new TypeParam`), or if their factory functions have the same\n    form (e.g. `CreateInstance<TypeParam>()`).\n*   Value-parameterized tests can be easier to write if you need different code\n    patterns to create different implementations' instances, e.g. `new Foo` vs\n    `new Bar(5)`. To accommodate for the differences, you can write factory\n    function wrappers and pass these function pointers to the tests as their\n    parameters.\n*   When a typed test fails, the default output includes the name of the type,\n    which can help you quickly identify which implementation is wrong.\n    Value-parameterized tests only show the number of the failed iteration by\n    default. You will need to define a function that returns the iteration name\n    and pass it as the third parameter to INSTANTIATE_TEST_SUITE_P to have more\n    useful output.\n*   When using typed tests, you need to make sure you are testing against the\n    interface type, not the concrete types (in other words, you want to make\n    sure `implicit_cast<MyInterface*>(my_concrete_impl)` works, not just that\n    `my_concrete_impl` works). It's less likely to make mistakes in this area\n    when using value-parameterized tests.\n\nI hope I didn't confuse you more. :-) If you don't mind, I'd suggest you to give\nboth approaches a try. Practice is a much better way to grasp the subtle\ndifferences between the two tools. Once you have some concrete experience, you\ncan much more easily decide which one to use the next time.\n\n## I got some run-time errors about invalid proto descriptors when using `ProtocolMessageEquals`. Help!\n\n{: .callout .note}\n**Note:** `ProtocolMessageEquals` and `ProtocolMessageEquiv` are *deprecated*\nnow. Please use `EqualsProto`, etc instead.\n\n`ProtocolMessageEquals` and `ProtocolMessageEquiv` were redefined recently and\nare now less tolerant of invalid protocol buffer definitions. In particular, if\nyou have a `foo.proto` that doesn't fully qualify the type of a protocol message\nit references (e.g. `message<Bar>` where it should be `message<blah.Bar>`), you\nwill now get run-time errors like:\n\n```\n... descriptor.cc:...] Invalid proto descriptor for file \"path/to/foo.proto\":\n... descriptor.cc:...]  blah.MyMessage.my_field: \".Bar\" is not defined.\n```\n\nIf you see this, your `.proto` file is broken and needs to be fixed by making\nthe types fully qualified. The new definition of `ProtocolMessageEquals` and\n`ProtocolMessageEquiv` just happen to reveal your bug.\n\n## My death test modifies some state, but the change seems lost after the death test finishes. Why?\n\nDeath tests (`EXPECT_DEATH`, etc) are executed in a sub-process s.t. the\nexpected crash won't kill the test program (i.e. the parent process). As a\nresult, any in-memory side effects they incur are observable in their respective\nsub-processes, but not in the parent process. You can think of them as running\nin a parallel universe, more or less.\n\nIn particular, if you use mocking and the death test statement invokes some mock\nmethods, the parent process will think the calls have never occurred. Therefore,\nyou may want to move your `EXPECT_CALL` statements inside the `EXPECT_DEATH`\nmacro.\n\n## EXPECT_EQ(htonl(blah), blah_blah) generates weird compiler errors in opt mode. Is this a GoogleTest bug?\n\nActually, the bug is in `htonl()`.\n\nAccording to `'man htonl'`, `htonl()` is a *function*, which means it's valid to\nuse `htonl` as a function pointer. However, in opt mode `htonl()` is defined as\na *macro*, which breaks this usage.\n\nWorse, the macro definition of `htonl()` uses a `gcc` extension and is *not*\nstandard C++. That hacky implementation has some ad hoc limitations. In\nparticular, it prevents you from writing `Foo<sizeof(htonl(x))>()`, where `Foo`\nis a template that has an integral argument.\n\nThe implementation of `EXPECT_EQ(a, b)` uses `sizeof(... a ...)` inside a\ntemplate argument, and thus doesn't compile in opt mode when `a` contains a call\nto `htonl()`. It is difficult to make `EXPECT_EQ` bypass the `htonl()` bug, as\nthe solution must work with different compilers on various platforms.\n\n## The compiler complains about \"undefined references\" to some static const member variables, but I did define them in the class body. What's wrong?\n\nIf your class has a static data member:\n\n```c++\n// foo.h\nclass Foo {\n  ...\n  static const int kBar = 100;\n};\n```\n\nYou also need to define it *outside* of the class body in `foo.cc`:\n\n```c++\nconst int Foo::kBar;  // No initializer here.\n```\n\nOtherwise your code is **invalid C++**, and may break in unexpected ways. In\nparticular, using it in GoogleTest comparison assertions (`EXPECT_EQ`, etc) will\ngenerate an \"undefined reference\" linker error. The fact that \"it used to work\"\ndoesn't mean it's valid. It just means that you were lucky. :-)\n\nIf the declaration of the static data member is `constexpr` then it is\nimplicitly an `inline` definition, and a separate definition in `foo.cc` is not\nneeded:\n\n```c++\n// foo.h\nclass Foo {\n  ...\n  static constexpr int kBar = 100;  // Defines kBar, no need to do it in foo.cc.\n};\n```\n\n## Can I derive a test fixture from another?\n\nYes.\n\nEach test fixture has a corresponding and same named test suite. This means only\none test suite can use a particular fixture. Sometimes, however, multiple test\ncases may want to use the same or slightly different fixtures. For example, you\nmay want to make sure that all of a GUI library's test suites don't leak\nimportant system resources like fonts and brushes.\n\nIn GoogleTest, you share a fixture among test suites by putting the shared logic\nin a base test fixture, then deriving from that base a separate fixture for each\ntest suite that wants to use this common logic. You then use `TEST_F()` to write\ntests using each derived fixture.\n\nTypically, your code looks like this:\n\n```c++\n// Defines a base test fixture.\nclass BaseTest : public ::testing::Test {\n protected:\n  ...\n};\n\n// Derives a fixture FooTest from BaseTest.\nclass FooTest : public BaseTest {\n protected:\n  void SetUp() override {\n    BaseTest::SetUp();  // Sets up the base fixture first.\n    ... additional set-up work ...\n  }\n\n  void TearDown() override {\n    ... clean-up work for FooTest ...\n    BaseTest::TearDown();  // Remember to tear down the base fixture\n                           // after cleaning up FooTest!\n  }\n\n  ... functions and variables for FooTest ...\n};\n\n// Tests that use the fixture FooTest.\nTEST_F(FooTest, Bar) { ... }\nTEST_F(FooTest, Baz) { ... }\n\n... additional fixtures derived from BaseTest ...\n```\n\nIf necessary, you can continue to derive test fixtures from a derived fixture.\nGoogleTest has no limit on how deep the hierarchy can be.\n\nFor a complete example using derived test fixtures, see\n[sample5_unittest.cc](https://github.com/google/googletest/blob/master/googletest/samples/sample5_unittest.cc).\n\n## My compiler complains \"void value not ignored as it ought to be.\" What does this mean?\n\nYou're probably using an `ASSERT_*()` in a function that doesn't return `void`.\n`ASSERT_*()` can only be used in `void` functions, due to exceptions being\ndisabled by our build system. Please see more details\n[here](advanced.md#assertion-placement).\n\n## My death test hangs (or seg-faults). How do I fix it?\n\nIn GoogleTest, death tests are run in a child process and the way they work is\ndelicate. To write death tests you really need to understand how they work—see\nthe details at [Death Assertions](reference/assertions.md#death) in the\nAssertions Reference.\n\nIn particular, death tests don't like having multiple threads in the parent\nprocess. So the first thing you can try is to eliminate creating threads outside\nof `EXPECT_DEATH()`. For example, you may want to use mocks or fake objects\ninstead of real ones in your tests.\n\nSometimes this is impossible as some library you must use may be creating\nthreads before `main()` is even reached. In this case, you can try to minimize\nthe chance of conflicts by either moving as many activities as possible inside\n`EXPECT_DEATH()` (in the extreme case, you want to move everything inside), or\nleaving as few things as possible in it. Also, you can try to set the death test\nstyle to `\"threadsafe\"`, which is safer but slower, and see if it helps.\n\nIf you go with thread-safe death tests, remember that they rerun the test\nprogram from the beginning in the child process. Therefore make sure your\nprogram can run side-by-side with itself and is deterministic.\n\nIn the end, this boils down to good concurrent programming. You have to make\nsure that there are no race conditions or deadlocks in your program. No silver\nbullet - sorry!\n\n## Should I use the constructor/destructor of the test fixture or SetUp()/TearDown()? {#CtorVsSetUp}\n\nThe first thing to remember is that GoogleTest does **not** reuse the same test\nfixture object across multiple tests. For each `TEST_F`, GoogleTest will create\na **fresh** test fixture object, immediately call `SetUp()`, run the test body,\ncall `TearDown()`, and then delete the test fixture object.\n\nWhen you need to write per-test set-up and tear-down logic, you have the choice\nbetween using the test fixture constructor/destructor or `SetUp()/TearDown()`.\nThe former is usually preferred, as it has the following benefits:\n\n*   By initializing a member variable in the constructor, we have the option to\n    make it `const`, which helps prevent accidental changes to its value and\n    makes the tests more obviously correct.\n*   In case we need to subclass the test fixture class, the subclass'\n    constructor is guaranteed to call the base class' constructor *first*, and\n    the subclass' destructor is guaranteed to call the base class' destructor\n    *afterward*. With `SetUp()/TearDown()`, a subclass may make the mistake of\n    forgetting to call the base class' `SetUp()/TearDown()` or call them at the\n    wrong time.\n\nYou may still want to use `SetUp()/TearDown()` in the following cases:\n\n*   C++ does not allow virtual function calls in constructors and destructors.\n    You can call a method declared as virtual, but it will not use dynamic\n    dispatch. It will use the definition from the class the constructor of which\n    is currently executing. This is because calling a virtual method before the\n    derived class constructor has a chance to run is very dangerous - the\n    virtual method might operate on uninitialized data. Therefore, if you need\n    to call a method that will be overridden in a derived class, you have to use\n    `SetUp()/TearDown()`.\n*   In the body of a constructor (or destructor), it's not possible to use the\n    `ASSERT_xx` macros. Therefore, if the set-up operation could cause a fatal\n    test failure that should prevent the test from running, it's necessary to\n    use `abort` and abort the whole test\n    executable, or to use `SetUp()` instead of a constructor.\n*   If the tear-down operation could throw an exception, you must use\n    `TearDown()` as opposed to the destructor, as throwing in a destructor leads\n    to undefined behavior and usually will kill your program right away. Note\n    that many standard libraries (like STL) may throw when exceptions are\n    enabled in the compiler. Therefore you should prefer `TearDown()` if you\n    want to write portable tests that work with or without exceptions.\n*   The GoogleTest team is considering making the assertion macros throw on\n    platforms where exceptions are enabled (e.g. Windows, Mac OS, and Linux\n    client-side), which will eliminate the need for the user to propagate\n    failures from a subroutine to its caller. Therefore, you shouldn't use\n    GoogleTest assertions in a destructor if your code could run on such a\n    platform.\n\n## The compiler complains \"no matching function to call\" when I use ASSERT_PRED*. How do I fix it?\n\nSee details for [`EXPECT_PRED*`](reference/assertions.md#EXPECT_PRED) in the\nAssertions Reference.\n\n## My compiler complains about \"ignoring return value\" when I call RUN_ALL_TESTS(). Why?\n\nSome people had been ignoring the return value of `RUN_ALL_TESTS()`. That is,\ninstead of\n\n```c++\n  return RUN_ALL_TESTS();\n```\n\nthey write\n\n```c++\n  RUN_ALL_TESTS();\n```\n\nThis is **wrong and dangerous**. The testing services needs to see the return\nvalue of `RUN_ALL_TESTS()` in order to determine if a test has passed. If your\n`main()` function ignores it, your test will be considered successful even if it\nhas a GoogleTest assertion failure. Very bad.\n\nWe have decided to fix this (thanks to Michael Chastain for the idea). Now, your\ncode will no longer be able to ignore `RUN_ALL_TESTS()` when compiled with\n`gcc`. If you do so, you'll get a compiler error.\n\nIf you see the compiler complaining about you ignoring the return value of\n`RUN_ALL_TESTS()`, the fix is simple: just make sure its value is used as the\nreturn value of `main()`.\n\nBut how could we introduce a change that breaks existing tests? Well, in this\ncase, the code was already broken in the first place, so we didn't break it. :-)\n\n## My compiler complains that a constructor (or destructor) cannot return a value. What's going on?\n\nDue to a peculiarity of C++, in order to support the syntax for streaming\nmessages to an `ASSERT_*`, e.g.\n\n```c++\n  ASSERT_EQ(1, Foo()) << \"blah blah\" << foo;\n```\n\nwe had to give up using `ASSERT*` and `FAIL*` (but not `EXPECT*` and\n`ADD_FAILURE*`) in constructors and destructors. The workaround is to move the\ncontent of your constructor/destructor to a private void member function, or\nswitch to `EXPECT_*()` if that works. This\n[section](advanced.md#assertion-placement) in the user's guide explains it.\n\n## My SetUp() function is not called. Why?\n\nC++ is case-sensitive. Did you spell it as `Setup()`?\n\nSimilarly, sometimes people spell `SetUpTestSuite()` as `SetupTestSuite()` and\nwonder why it's never called.\n\n## I have several test suites which share the same test fixture logic, do I have to define a new test fixture class for each of them? This seems pretty tedious.\n\nYou don't have to. Instead of\n\n```c++\nclass FooTest : public BaseTest {};\n\nTEST_F(FooTest, Abc) { ... }\nTEST_F(FooTest, Def) { ... }\n\nclass BarTest : public BaseTest {};\n\nTEST_F(BarTest, Abc) { ... }\nTEST_F(BarTest, Def) { ... }\n```\n\nyou can simply `typedef` the test fixtures:\n\n```c++\ntypedef BaseTest FooTest;\n\nTEST_F(FooTest, Abc) { ... }\nTEST_F(FooTest, Def) { ... }\n\ntypedef BaseTest BarTest;\n\nTEST_F(BarTest, Abc) { ... }\nTEST_F(BarTest, Def) { ... }\n```\n\n## GoogleTest output is buried in a whole bunch of LOG messages. What do I do?\n\nThe GoogleTest output is meant to be a concise and human-friendly report. If\nyour test generates textual output itself, it will mix with the GoogleTest\noutput, making it hard to read. However, there is an easy solution to this\nproblem.\n\nSince `LOG` messages go to stderr, we decided to let GoogleTest output go to\nstdout. This way, you can easily separate the two using redirection. For\nexample:\n\n```shell\n$ ./my_test > gtest_output.txt\n```\n\n## Why should I prefer test fixtures over global variables?\n\nThere are several good reasons:\n\n1.  It's likely your test needs to change the states of its global variables.\n    This makes it difficult to keep side effects from escaping one test and\n    contaminating others, making debugging difficult. By using fixtures, each\n    test has a fresh set of variables that's different (but with the same\n    names). Thus, tests are kept independent of each other.\n2.  Global variables pollute the global namespace.\n3.  Test fixtures can be reused via subclassing, which cannot be done easily\n    with global variables. This is useful if many test suites have something in\n    common.\n\n## What can the statement argument in ASSERT_DEATH() be?\n\n`ASSERT_DEATH(statement, matcher)` (or any death assertion macro) can be used\nwherever *`statement`* is valid. So basically *`statement`* can be any C++\nstatement that makes sense in the current context. In particular, it can\nreference global and/or local variables, and can be:\n\n*   a simple function call (often the case),\n*   a complex expression, or\n*   a compound statement.\n\nSome examples are shown here:\n\n```c++\n// A death test can be a simple function call.\nTEST(MyDeathTest, FunctionCall) {\n  ASSERT_DEATH(Xyz(5), \"Xyz failed\");\n}\n\n// Or a complex expression that references variables and functions.\nTEST(MyDeathTest, ComplexExpression) {\n  const bool c = Condition();\n  ASSERT_DEATH((c ? Func1(0) : object2.Method(\"test\")),\n               \"(Func1|Method) failed\");\n}\n\n// Death assertions can be used anywhere in a function.  In\n// particular, they can be inside a loop.\nTEST(MyDeathTest, InsideLoop) {\n  // Verifies that Foo(0), Foo(1), ..., and Foo(4) all die.\n  for (int i = 0; i < 5; i++) {\n    EXPECT_DEATH_M(Foo(i), \"Foo has \\\\d+ errors\",\n                   ::testing::Message() << \"where i is \" << i);\n  }\n}\n\n// A death assertion can contain a compound statement.\nTEST(MyDeathTest, CompoundStatement) {\n  // Verifies that at lease one of Bar(0), Bar(1), ..., and\n  // Bar(4) dies.\n  ASSERT_DEATH({\n    for (int i = 0; i < 5; i++) {\n      Bar(i);\n    }\n  },\n  \"Bar has \\\\d+ errors\");\n}\n```\n\n## I have a fixture class `FooTest`, but `TEST_F(FooTest, Bar)` gives me error ``\"no matching function for call to `FooTest::FooTest()'\"``. Why?\n\nGoogleTest needs to be able to create objects of your test fixture class, so it\nmust have a default constructor. Normally the compiler will define one for you.\nHowever, there are cases where you have to define your own:\n\n*   If you explicitly declare a non-default constructor for class `FooTest`\n    (`DISALLOW_EVIL_CONSTRUCTORS()` does this), then you need to define a\n    default constructor, even if it would be empty.\n*   If `FooTest` has a const non-static data member, then you have to define the\n    default constructor *and* initialize the const member in the initializer\n    list of the constructor. (Early versions of `gcc` doesn't force you to\n    initialize the const member. It's a bug that has been fixed in `gcc 4`.)\n\n## Why does ASSERT_DEATH complain about previous threads that were already joined?\n\nWith the Linux pthread library, there is no turning back once you cross the line\nfrom a single thread to multiple threads. The first time you create a thread, a\nmanager thread is created in addition, so you get 3, not 2, threads. Later when\nthe thread you create joins the main thread, the thread count decrements by 1,\nbut the manager thread will never be killed, so you still have 2 threads, which\nmeans you cannot safely run a death test.\n\nThe new NPTL thread library doesn't suffer from this problem, as it doesn't\ncreate a manager thread. However, if you don't control which machine your test\nruns on, you shouldn't depend on this.\n\n## Why does GoogleTest require the entire test suite, instead of individual tests, to be named *DeathTest when it uses ASSERT_DEATH?\n\nGoogleTest does not interleave tests from different test suites. That is, it\nruns all tests in one test suite first, and then runs all tests in the next test\nsuite, and so on. GoogleTest does this because it needs to set up a test suite\nbefore the first test in it is run, and tear it down afterwards. Splitting up\nthe test case would require multiple set-up and tear-down processes, which is\ninefficient and makes the semantics unclean.\n\nIf we were to determine the order of tests based on test name instead of test\ncase name, then we would have a problem with the following situation:\n\n```c++\nTEST_F(FooTest, AbcDeathTest) { ... }\nTEST_F(FooTest, Uvw) { ... }\n\nTEST_F(BarTest, DefDeathTest) { ... }\nTEST_F(BarTest, Xyz) { ... }\n```\n\nSince `FooTest.AbcDeathTest` needs to run before `BarTest.Xyz`, and we don't\ninterleave tests from different test suites, we need to run all tests in the\n`FooTest` case before running any test in the `BarTest` case. This contradicts\nwith the requirement to run `BarTest.DefDeathTest` before `FooTest.Uvw`.\n\n## But I don't like calling my entire test suite \\*DeathTest when it contains both death tests and non-death tests. What do I do?\n\nYou don't have to, but if you like, you may split up the test suite into\n`FooTest` and `FooDeathTest`, where the names make it clear that they are\nrelated:\n\n```c++\nclass FooTest : public ::testing::Test { ... };\n\nTEST_F(FooTest, Abc) { ... }\nTEST_F(FooTest, Def) { ... }\n\nusing FooDeathTest = FooTest;\n\nTEST_F(FooDeathTest, Uvw) { ... EXPECT_DEATH(...) ... }\nTEST_F(FooDeathTest, Xyz) { ... ASSERT_DEATH(...) ... }\n```\n\n## GoogleTest prints the LOG messages in a death test's child process only when the test fails. How can I see the LOG messages when the death test succeeds?\n\nPrinting the LOG messages generated by the statement inside `EXPECT_DEATH()`\nmakes it harder to search for real problems in the parent's log. Therefore,\nGoogleTest only prints them when the death test has failed.\n\nIf you really need to see such LOG messages, a workaround is to temporarily\nbreak the death test (e.g. by changing the regex pattern it is expected to\nmatch). Admittedly, this is a hack. We'll consider a more permanent solution\nafter the fork-and-exec-style death tests are implemented.\n\n## The compiler complains about `no match for 'operator<<'` when I use an assertion. What gives?\n\nIf you use a user-defined type `FooType` in an assertion, you must make sure\nthere is an `std::ostream& operator<<(std::ostream&, const FooType&)` function\ndefined such that we can print a value of `FooType`.\n\nIn addition, if `FooType` is declared in a name space, the `<<` operator also\nneeds to be defined in the *same* name space. See\n[Tip of the Week #49](http://abseil.io/tips/49) for details.\n\n## How do I suppress the memory leak messages on Windows?\n\nSince the statically initialized GoogleTest singleton requires allocations on\nthe heap, the Visual C++ memory leak detector will report memory leaks at the\nend of the program run. The easiest way to avoid this is to use the\n`_CrtMemCheckpoint` and `_CrtMemDumpAllObjectsSince` calls to not report any\nstatically initialized heap objects. See MSDN for more details and additional\nheap check/debug routines.\n\n## How can my code detect if it is running in a test?\n\nIf you write code that sniffs whether it's running in a test and does different\nthings accordingly, you are leaking test-only logic into production code and\nthere is no easy way to ensure that the test-only code paths aren't run by\nmistake in production. Such cleverness also leads to\n[Heisenbugs](https://en.wikipedia.org/wiki/Heisenbug). Therefore we strongly\nadvise against the practice, and GoogleTest doesn't provide a way to do it.\n\nIn general, the recommended way to cause the code to behave differently under\ntest is [Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection). You can inject\ndifferent functionality from the test and from the production code. Since your\nproduction code doesn't link in the for-test logic at all (the\n[`testonly`](http://docs.bazel.build/versions/master/be/common-definitions.html#common.testonly) attribute for BUILD targets helps to ensure\nthat), there is no danger in accidentally running it.\n\nHowever, if you *really*, *really*, *really* have no choice, and if you follow\nthe rule of ending your test program names with `_test`, you can use the\n*horrible* hack of sniffing your executable name (`argv[0]` in `main()`) to know\nwhether the code is under test.\n\n## How do I temporarily disable a test?\n\nIf you have a broken test that you cannot fix right away, you can add the\n`DISABLED_` prefix to its name. This will exclude it from execution. This is\nbetter than commenting out the code or using `#if 0`, as disabled tests are\nstill compiled (and thus won't rot).\n\nTo include disabled tests in test execution, just invoke the test program with\nthe `--gtest_also_run_disabled_tests` flag.\n\n## Is it OK if I have two separate `TEST(Foo, Bar)` test methods defined in different namespaces?\n\nYes.\n\nThe rule is **all test methods in the same test suite must use the same fixture\nclass.** This means that the following is **allowed** because both tests use the\nsame fixture class (`::testing::Test`).\n\n```c++\nnamespace foo {\nTEST(CoolTest, DoSomething) {\n  SUCCEED();\n}\n}  // namespace foo\n\nnamespace bar {\nTEST(CoolTest, DoSomething) {\n  SUCCEED();\n}\n}  // namespace bar\n```\n\nHowever, the following code is **not allowed** and will produce a runtime error\nfrom GoogleTest because the test methods are using different test fixture\nclasses with the same test suite name.\n\n```c++\nnamespace foo {\nclass CoolTest : public ::testing::Test {};  // Fixture foo::CoolTest\nTEST_F(CoolTest, DoSomething) {\n  SUCCEED();\n}\n}  // namespace foo\n\nnamespace bar {\nclass CoolTest : public ::testing::Test {};  // Fixture: bar::CoolTest\nTEST_F(CoolTest, DoSomething) {\n  SUCCEED();\n}\n}  // namespace bar\n```\n"
  },
  {
    "path": "3rd/googletest-1.12.1/docs/gmock_cheat_sheet.md",
    "content": "# gMock Cheat Sheet\n\n## Defining a Mock Class\n\n### Mocking a Normal Class {#MockClass}\n\nGiven\n\n```cpp\nclass Foo {\n public:\n  virtual ~Foo();\n  virtual int GetSize() const = 0;\n  virtual string Describe(const char* name) = 0;\n  virtual string Describe(int type) = 0;\n  virtual bool Process(Bar elem, int count) = 0;\n};\n```\n\n(note that `~Foo()` **must** be virtual) we can define its mock as\n\n```cpp\n#include \"gmock/gmock.h\"\n\nclass MockFoo : public Foo {\n public:\n  MOCK_METHOD(int, GetSize, (), (const, override));\n  MOCK_METHOD(string, Describe, (const char* name), (override));\n  MOCK_METHOD(string, Describe, (int type), (override));\n  MOCK_METHOD(bool, Process, (Bar elem, int count), (override));\n};\n```\n\nTo create a \"nice\" mock, which ignores all uninteresting calls, a \"naggy\" mock,\nwhich warns on all uninteresting calls, or a \"strict\" mock, which treats them as\nfailures:\n\n```cpp\nusing ::testing::NiceMock;\nusing ::testing::NaggyMock;\nusing ::testing::StrictMock;\n\nNiceMock<MockFoo> nice_foo;      // The type is a subclass of MockFoo.\nNaggyMock<MockFoo> naggy_foo;    // The type is a subclass of MockFoo.\nStrictMock<MockFoo> strict_foo;  // The type is a subclass of MockFoo.\n```\n\n{: .callout .note}\n**Note:** A mock object is currently naggy by default. We may make it nice by\ndefault in the future.\n\n### Mocking a Class Template {#MockTemplate}\n\nClass templates can be mocked just like any class.\n\nTo mock\n\n```cpp\ntemplate <typename Elem>\nclass StackInterface {\n public:\n  virtual ~StackInterface();\n  virtual int GetSize() const = 0;\n  virtual void Push(const Elem& x) = 0;\n};\n```\n\n(note that all member functions that are mocked, including `~StackInterface()`\n**must** be virtual).\n\n```cpp\ntemplate <typename Elem>\nclass MockStack : public StackInterface<Elem> {\n public:\n  MOCK_METHOD(int, GetSize, (), (const, override));\n  MOCK_METHOD(void, Push, (const Elem& x), (override));\n};\n```\n\n### Specifying Calling Conventions for Mock Functions\n\nIf your mock function doesn't use the default calling convention, you can\nspecify it by adding `Calltype(convention)` to `MOCK_METHOD`'s 4th parameter.\nFor example,\n\n```cpp\n  MOCK_METHOD(bool, Foo, (int n), (Calltype(STDMETHODCALLTYPE)));\n  MOCK_METHOD(int, Bar, (double x, double y),\n              (const, Calltype(STDMETHODCALLTYPE)));\n```\n\nwhere `STDMETHODCALLTYPE` is defined by `<objbase.h>` on Windows.\n\n## Using Mocks in Tests {#UsingMocks}\n\nThe typical work flow is:\n\n1.  Import the gMock names you need to use. All gMock symbols are in the\n    `testing` namespace unless they are macros or otherwise noted.\n2.  Create the mock objects.\n3.  Optionally, set the default actions of the mock objects.\n4.  Set your expectations on the mock objects (How will they be called? What\n    will they do?).\n5.  Exercise code that uses the mock objects; if necessary, check the result\n    using googletest assertions.\n6.  When a mock object is destructed, gMock automatically verifies that all\n    expectations on it have been satisfied.\n\nHere's an example:\n\n```cpp\nusing ::testing::Return;                          // #1\n\nTEST(BarTest, DoesThis) {\n  MockFoo foo;                                    // #2\n\n  ON_CALL(foo, GetSize())                         // #3\n      .WillByDefault(Return(1));\n  // ... other default actions ...\n\n  EXPECT_CALL(foo, Describe(5))                   // #4\n      .Times(3)\n      .WillRepeatedly(Return(\"Category 5\"));\n  // ... other expectations ...\n\n  EXPECT_EQ(MyProductionFunction(&foo), \"good\");  // #5\n}                                                 // #6\n```\n\n## Setting Default Actions {#OnCall}\n\ngMock has a **built-in default action** for any function that returns `void`,\n`bool`, a numeric value, or a pointer. In C++11, it will additionally returns\nthe default-constructed value, if one exists for the given type.\n\nTo customize the default action for functions with return type `T`, use\n[`DefaultValue<T>`](reference/mocking.md#DefaultValue). For example:\n\n```cpp\n  // Sets the default action for return type std::unique_ptr<Buzz> to\n  // creating a new Buzz every time.\n  DefaultValue<std::unique_ptr<Buzz>>::SetFactory(\n      [] { return MakeUnique<Buzz>(AccessLevel::kInternal); });\n\n  // When this fires, the default action of MakeBuzz() will run, which\n  // will return a new Buzz object.\n  EXPECT_CALL(mock_buzzer_, MakeBuzz(\"hello\")).Times(AnyNumber());\n\n  auto buzz1 = mock_buzzer_.MakeBuzz(\"hello\");\n  auto buzz2 = mock_buzzer_.MakeBuzz(\"hello\");\n  EXPECT_NE(buzz1, nullptr);\n  EXPECT_NE(buzz2, nullptr);\n  EXPECT_NE(buzz1, buzz2);\n\n  // Resets the default action for return type std::unique_ptr<Buzz>,\n  // to avoid interfere with other tests.\n  DefaultValue<std::unique_ptr<Buzz>>::Clear();\n```\n\nTo customize the default action for a particular method of a specific mock\nobject, use [`ON_CALL`](reference/mocking.md#ON_CALL). `ON_CALL` has a similar\nsyntax to `EXPECT_CALL`, but it is used for setting default behaviors when you\ndo not require that the mock method is called. See\n[Knowing When to Expect](gmock_cook_book.md#UseOnCall) for a more detailed\ndiscussion.\n\n## Setting Expectations {#ExpectCall}\n\nSee [`EXPECT_CALL`](reference/mocking.md#EXPECT_CALL) in the Mocking Reference.\n\n## Matchers {#MatcherList}\n\nSee the [Matchers Reference](reference/matchers.md).\n\n## Actions {#ActionList}\n\nSee the [Actions Reference](reference/actions.md).\n\n## Cardinalities {#CardinalityList}\n\nSee the [`Times` clause](reference/mocking.md#EXPECT_CALL.Times) of\n`EXPECT_CALL` in the Mocking Reference.\n\n## Expectation Order\n\nBy default, expectations can be matched in *any* order. If some or all\nexpectations must be matched in a given order, you can use the\n[`After` clause](reference/mocking.md#EXPECT_CALL.After) or\n[`InSequence` clause](reference/mocking.md#EXPECT_CALL.InSequence) of\n`EXPECT_CALL`, or use an [`InSequence` object](reference/mocking.md#InSequence).\n\n## Verifying and Resetting a Mock\n\ngMock will verify the expectations on a mock object when it is destructed, or\nyou can do it earlier:\n\n```cpp\nusing ::testing::Mock;\n...\n// Verifies and removes the expectations on mock_obj;\n// returns true if and only if successful.\nMock::VerifyAndClearExpectations(&mock_obj);\n...\n// Verifies and removes the expectations on mock_obj;\n// also removes the default actions set by ON_CALL();\n// returns true if and only if successful.\nMock::VerifyAndClear(&mock_obj);\n```\n\nDo not set new expectations after verifying and clearing a mock after its use.\nSetting expectations after code that exercises the mock has undefined behavior.\nSee [Using Mocks in Tests](gmock_for_dummies.md#using-mocks-in-tests) for more\ninformation.\n\nYou can also tell gMock that a mock object can be leaked and doesn't need to be\nverified:\n\n```cpp\nMock::AllowLeak(&mock_obj);\n```\n\n## Mock Classes\n\ngMock defines a convenient mock class template\n\n```cpp\nclass MockFunction<R(A1, ..., An)> {\n public:\n  MOCK_METHOD(R, Call, (A1, ..., An));\n};\n```\n\nSee this [recipe](gmock_cook_book.md#UsingCheckPoints) for one application of\nit.\n\n## Flags\n\n| Flag                           | Description                               |\n| :----------------------------- | :---------------------------------------- |\n| `--gmock_catch_leaked_mocks=0` | Don't report leaked mock objects as failures. |\n| `--gmock_verbose=LEVEL` | Sets the default verbosity level (`info`, `warning`, or `error`) of Google Mock messages. |\n"
  },
  {
    "path": "3rd/googletest-1.12.1/docs/gmock_cook_book.md",
    "content": "# gMock Cookbook\n\nYou can find recipes for using gMock here. If you haven't yet, please read\n[the dummy guide](gmock_for_dummies.md) first to make sure you understand the\nbasics.\n\n{: .callout .note}\n**Note:** gMock lives in the `testing` name space. For readability, it is\nrecommended to write `using ::testing::Foo;` once in your file before using the\nname `Foo` defined by gMock. We omit such `using` statements in this section for\nbrevity, but you should do it in your own code.\n\n## Creating Mock Classes\n\nMock classes are defined as normal classes, using the `MOCK_METHOD` macro to\ngenerate mocked methods. The macro gets 3 or 4 parameters:\n\n```cpp\nclass MyMock {\n public:\n  MOCK_METHOD(ReturnType, MethodName, (Args...));\n  MOCK_METHOD(ReturnType, MethodName, (Args...), (Specs...));\n};\n```\n\nThe first 3 parameters are simply the method declaration, split into 3 parts.\nThe 4th parameter accepts a closed list of qualifiers, which affect the\ngenerated method:\n\n*   **`const`** - Makes the mocked method a `const` method. Required if\n    overriding a `const` method.\n*   **`override`** - Marks the method with `override`. Recommended if overriding\n    a `virtual` method.\n*   **`noexcept`** - Marks the method with `noexcept`. Required if overriding a\n    `noexcept` method.\n*   **`Calltype(...)`** - Sets the call type for the method (e.g. to\n    `STDMETHODCALLTYPE`), useful in Windows.\n*   **`ref(...)`** - Marks the method with the reference qualification\n    specified. Required if overriding a method that has reference\n    qualifications. Eg `ref(&)` or `ref(&&)`.\n\n### Dealing with unprotected commas\n\nUnprotected commas, i.e. commas which are not surrounded by parentheses, prevent\n`MOCK_METHOD` from parsing its arguments correctly:\n\n{: .bad}\n```cpp\nclass MockFoo {\n public:\n  MOCK_METHOD(std::pair<bool, int>, GetPair, ());  // Won't compile!\n  MOCK_METHOD(bool, CheckMap, (std::map<int, double>, bool));  // Won't compile!\n};\n```\n\nSolution 1 - wrap with parentheses:\n\n{: .good}\n```cpp\nclass MockFoo {\n public:\n  MOCK_METHOD((std::pair<bool, int>), GetPair, ());\n  MOCK_METHOD(bool, CheckMap, ((std::map<int, double>), bool));\n};\n```\n\nNote that wrapping a return or argument type with parentheses is, in general,\ninvalid C++. `MOCK_METHOD` removes the parentheses.\n\nSolution 2 - define an alias:\n\n{: .good}\n```cpp\nclass MockFoo {\n public:\n  using BoolAndInt = std::pair<bool, int>;\n  MOCK_METHOD(BoolAndInt, GetPair, ());\n  using MapIntDouble = std::map<int, double>;\n  MOCK_METHOD(bool, CheckMap, (MapIntDouble, bool));\n};\n```\n\n### Mocking Private or Protected Methods\n\nYou must always put a mock method definition (`MOCK_METHOD`) in a `public:`\nsection of the mock class, regardless of the method being mocked being `public`,\n`protected`, or `private` in the base class. This allows `ON_CALL` and\n`EXPECT_CALL` to reference the mock function from outside of the mock class.\n(Yes, C++ allows a subclass to change the access level of a virtual function in\nthe base class.) Example:\n\n```cpp\nclass Foo {\n public:\n  ...\n  virtual bool Transform(Gadget* g) = 0;\n\n protected:\n  virtual void Resume();\n\n private:\n  virtual int GetTimeOut();\n};\n\nclass MockFoo : public Foo {\n public:\n  ...\n  MOCK_METHOD(bool, Transform, (Gadget* g), (override));\n\n  // The following must be in the public section, even though the\n  // methods are protected or private in the base class.\n  MOCK_METHOD(void, Resume, (), (override));\n  MOCK_METHOD(int, GetTimeOut, (), (override));\n};\n```\n\n### Mocking Overloaded Methods\n\nYou can mock overloaded functions as usual. No special attention is required:\n\n```cpp\nclass Foo {\n  ...\n\n  // Must be virtual as we'll inherit from Foo.\n  virtual ~Foo();\n\n  // Overloaded on the types and/or numbers of arguments.\n  virtual int Add(Element x);\n  virtual int Add(int times, Element x);\n\n  // Overloaded on the const-ness of this object.\n  virtual Bar& GetBar();\n  virtual const Bar& GetBar() const;\n};\n\nclass MockFoo : public Foo {\n  ...\n  MOCK_METHOD(int, Add, (Element x), (override));\n  MOCK_METHOD(int, Add, (int times, Element x), (override));\n\n  MOCK_METHOD(Bar&, GetBar, (), (override));\n  MOCK_METHOD(const Bar&, GetBar, (), (const, override));\n};\n```\n\n{: .callout .note}\n**Note:** if you don't mock all versions of the overloaded method, the compiler\nwill give you a warning about some methods in the base class being hidden. To\nfix that, use `using` to bring them in scope:\n\n```cpp\nclass MockFoo : public Foo {\n  ...\n  using Foo::Add;\n  MOCK_METHOD(int, Add, (Element x), (override));\n  // We don't want to mock int Add(int times, Element x);\n  ...\n};\n```\n\n### Mocking Class Templates\n\nYou can mock class templates just like any class.\n\n```cpp\ntemplate <typename Elem>\nclass StackInterface {\n  ...\n  // Must be virtual as we'll inherit from StackInterface.\n  virtual ~StackInterface();\n\n  virtual int GetSize() const = 0;\n  virtual void Push(const Elem& x) = 0;\n};\n\ntemplate <typename Elem>\nclass MockStack : public StackInterface<Elem> {\n  ...\n  MOCK_METHOD(int, GetSize, (), (override));\n  MOCK_METHOD(void, Push, (const Elem& x), (override));\n};\n```\n\n### Mocking Non-virtual Methods {#MockingNonVirtualMethods}\n\ngMock can mock non-virtual functions to be used in Hi-perf dependency injection.\n\nIn this case, instead of sharing a common base class with the real class, your\nmock class will be *unrelated* to the real class, but contain methods with the\nsame signatures. The syntax for mocking non-virtual methods is the *same* as\nmocking virtual methods (just don't add `override`):\n\n```cpp\n// A simple packet stream class.  None of its members is virtual.\nclass ConcretePacketStream {\n public:\n  void AppendPacket(Packet* new_packet);\n  const Packet* GetPacket(size_t packet_number) const;\n  size_t NumberOfPackets() const;\n  ...\n};\n\n// A mock packet stream class.  It inherits from no other, but defines\n// GetPacket() and NumberOfPackets().\nclass MockPacketStream {\n public:\n  MOCK_METHOD(const Packet*, GetPacket, (size_t packet_number), (const));\n  MOCK_METHOD(size_t, NumberOfPackets, (), (const));\n  ...\n};\n```\n\nNote that the mock class doesn't define `AppendPacket()`, unlike the real class.\nThat's fine as long as the test doesn't need to call it.\n\nNext, you need a way to say that you want to use `ConcretePacketStream` in\nproduction code, and use `MockPacketStream` in tests. Since the functions are\nnot virtual and the two classes are unrelated, you must specify your choice at\n*compile time* (as opposed to run time).\n\nOne way to do it is to templatize your code that needs to use a packet stream.\nMore specifically, you will give your code a template type argument for the type\nof the packet stream. In production, you will instantiate your template with\n`ConcretePacketStream` as the type argument. In tests, you will instantiate the\nsame template with `MockPacketStream`. For example, you may write:\n\n```cpp\ntemplate <class PacketStream>\nvoid CreateConnection(PacketStream* stream) { ... }\n\ntemplate <class PacketStream>\nclass PacketReader {\n public:\n  void ReadPackets(PacketStream* stream, size_t packet_num);\n};\n```\n\nThen you can use `CreateConnection<ConcretePacketStream>()` and\n`PacketReader<ConcretePacketStream>` in production code, and use\n`CreateConnection<MockPacketStream>()` and `PacketReader<MockPacketStream>` in\ntests.\n\n```cpp\n  MockPacketStream mock_stream;\n  EXPECT_CALL(mock_stream, ...)...;\n  .. set more expectations on mock_stream ...\n  PacketReader<MockPacketStream> reader(&mock_stream);\n  ... exercise reader ...\n```\n\n### Mocking Free Functions\n\nIt is not possible to directly mock a free function (i.e. a C-style function or\na static method). If you need to, you can rewrite your code to use an interface\n(abstract class).\n\nInstead of calling a free function (say, `OpenFile`) directly, introduce an\ninterface for it and have a concrete subclass that calls the free function:\n\n```cpp\nclass FileInterface {\n public:\n  ...\n  virtual bool Open(const char* path, const char* mode) = 0;\n};\n\nclass File : public FileInterface {\n public:\n  ...\n  bool Open(const char* path, const char* mode) override {\n     return OpenFile(path, mode);\n  }\n};\n```\n\nYour code should talk to `FileInterface` to open a file. Now it's easy to mock\nout the function.\n\nThis may seem like a lot of hassle, but in practice you often have multiple\nrelated functions that you can put in the same interface, so the per-function\nsyntactic overhead will be much lower.\n\nIf you are concerned about the performance overhead incurred by virtual\nfunctions, and profiling confirms your concern, you can combine this with the\nrecipe for [mocking non-virtual methods](#MockingNonVirtualMethods).\n\n### Old-Style `MOCK_METHODn` Macros\n\nBefore the generic `MOCK_METHOD` macro\n[was introduced in 2018](https://github.com/google/googletest/commit/c5f08bf91944ce1b19bcf414fa1760e69d20afc2),\nmocks where created using a family of macros collectively called `MOCK_METHODn`.\nThese macros are still supported, though migration to the new `MOCK_METHOD` is\nrecommended.\n\nThe macros in the `MOCK_METHODn` family differ from `MOCK_METHOD`:\n\n*   The general structure is `MOCK_METHODn(MethodName, ReturnType(Args))`,\n    instead of `MOCK_METHOD(ReturnType, MethodName, (Args))`.\n*   The number `n` must equal the number of arguments.\n*   When mocking a const method, one must use `MOCK_CONST_METHODn`.\n*   When mocking a class template, the macro name must be suffixed with `_T`.\n*   In order to specify the call type, the macro name must be suffixed with\n    `_WITH_CALLTYPE`, and the call type is the first macro argument.\n\nOld macros and their new equivalents:\n\n<table>\n  <tr><th colspan=2>Simple</th></tr>\n  <tr>\n    <td>Old</td>\n    <td><code>MOCK_METHOD1(Foo, bool(int))</code></td>\n  </tr>\n  <tr>\n    <td>New</td>\n    <td><code>MOCK_METHOD(bool, Foo, (int))</code></td>\n  </tr>\n\n  <tr><th colspan=2>Const Method</th></tr>\n  <tr>\n    <td>Old</td>\n    <td><code>MOCK_CONST_METHOD1(Foo, bool(int))</code></td>\n  </tr>\n  <tr>\n    <td>New</td>\n    <td><code>MOCK_METHOD(bool, Foo, (int), (const))</code></td>\n  </tr>\n\n  <tr><th colspan=2>Method in a Class Template</th></tr>\n  <tr>\n    <td>Old</td>\n    <td><code>MOCK_METHOD1_T(Foo, bool(int))</code></td>\n  </tr>\n  <tr>\n    <td>New</td>\n    <td><code>MOCK_METHOD(bool, Foo, (int))</code></td>\n  </tr>\n\n  <tr><th colspan=2>Const Method in a Class Template</th></tr>\n  <tr>\n    <td>Old</td>\n    <td><code>MOCK_CONST_METHOD1_T(Foo, bool(int))</code></td>\n  </tr>\n  <tr>\n    <td>New</td>\n    <td><code>MOCK_METHOD(bool, Foo, (int), (const))</code></td>\n  </tr>\n\n  <tr><th colspan=2>Method with Call Type</th></tr>\n  <tr>\n    <td>Old</td>\n    <td><code>MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))</code></td>\n  </tr>\n  <tr>\n    <td>New</td>\n    <td><code>MOCK_METHOD(bool, Foo, (int), (Calltype(STDMETHODCALLTYPE)))</code></td>\n  </tr>\n\n  <tr><th colspan=2>Const Method with Call Type</th></tr>\n  <tr>\n    <td>Old</td>\n    <td><code>MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))</code></td>\n  </tr>\n  <tr>\n    <td>New</td>\n    <td><code>MOCK_METHOD(bool, Foo, (int), (const, Calltype(STDMETHODCALLTYPE)))</code></td>\n  </tr>\n\n  <tr><th colspan=2>Method with Call Type in a Class Template</th></tr>\n  <tr>\n    <td>Old</td>\n    <td><code>MOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))</code></td>\n  </tr>\n  <tr>\n    <td>New</td>\n    <td><code>MOCK_METHOD(bool, Foo, (int), (Calltype(STDMETHODCALLTYPE)))</code></td>\n  </tr>\n\n  <tr><th colspan=2>Const Method with Call Type in a Class Template</th></tr>\n  <tr>\n    <td>Old</td>\n    <td><code>MOCK_CONST_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Foo, bool(int))</code></td>\n  </tr>\n  <tr>\n    <td>New</td>\n    <td><code>MOCK_METHOD(bool, Foo, (int), (const, Calltype(STDMETHODCALLTYPE)))</code></td>\n  </tr>\n</table>\n\n### The Nice, the Strict, and the Naggy {#NiceStrictNaggy}\n\nIf a mock method has no `EXPECT_CALL` spec but is called, we say that it's an\n\"uninteresting call\", and the default action (which can be specified using\n`ON_CALL()`) of the method will be taken. Currently, an uninteresting call will\nalso by default cause gMock to print a warning.\n\nHowever, sometimes you may want to ignore these uninteresting calls, and\nsometimes you may want to treat them as errors. gMock lets you make the decision\non a per-mock-object basis.\n\nSuppose your test uses a mock class `MockFoo`:\n\n```cpp\nTEST(...) {\n  MockFoo mock_foo;\n  EXPECT_CALL(mock_foo, DoThis());\n  ... code that uses mock_foo ...\n}\n```\n\nIf a method of `mock_foo` other than `DoThis()` is called, you will get a\nwarning. However, if you rewrite your test to use `NiceMock<MockFoo>` instead,\nyou can suppress the warning:\n\n```cpp\nusing ::testing::NiceMock;\n\nTEST(...) {\n  NiceMock<MockFoo> mock_foo;\n  EXPECT_CALL(mock_foo, DoThis());\n  ... code that uses mock_foo ...\n}\n```\n\n`NiceMock<MockFoo>` is a subclass of `MockFoo`, so it can be used wherever\n`MockFoo` is accepted.\n\nIt also works if `MockFoo`'s constructor takes some arguments, as\n`NiceMock<MockFoo>` \"inherits\" `MockFoo`'s constructors:\n\n```cpp\nusing ::testing::NiceMock;\n\nTEST(...) {\n  NiceMock<MockFoo> mock_foo(5, \"hi\");  // Calls MockFoo(5, \"hi\").\n  EXPECT_CALL(mock_foo, DoThis());\n  ... code that uses mock_foo ...\n}\n```\n\nThe usage of `StrictMock` is similar, except that it makes all uninteresting\ncalls failures:\n\n```cpp\nusing ::testing::StrictMock;\n\nTEST(...) {\n  StrictMock<MockFoo> mock_foo;\n  EXPECT_CALL(mock_foo, DoThis());\n  ... code that uses mock_foo ...\n\n  // The test will fail if a method of mock_foo other than DoThis()\n  // is called.\n}\n```\n\n{: .callout .note}\nNOTE: `NiceMock` and `StrictMock` only affects *uninteresting* calls (calls of\n*methods* with no expectations); they do not affect *unexpected* calls (calls of\nmethods with expectations, but they don't match). See\n[Understanding Uninteresting vs Unexpected Calls](#uninteresting-vs-unexpected).\n\nThere are some caveats though (sadly they are side effects of C++'s\nlimitations):\n\n1.  `NiceMock<MockFoo>` and `StrictMock<MockFoo>` only work for mock methods\n    defined using the `MOCK_METHOD` macro **directly** in the `MockFoo` class.\n    If a mock method is defined in a **base class** of `MockFoo`, the \"nice\" or\n    \"strict\" modifier may not affect it, depending on the compiler. In\n    particular, nesting `NiceMock` and `StrictMock` (e.g.\n    `NiceMock<StrictMock<MockFoo> >`) is **not** supported.\n2.  `NiceMock<MockFoo>` and `StrictMock<MockFoo>` may not work correctly if the\n    destructor of `MockFoo` is not virtual. We would like to fix this, but it\n    requires cleaning up existing tests.\n\nFinally, you should be **very cautious** about when to use naggy or strict\nmocks, as they tend to make tests more brittle and harder to maintain. When you\nrefactor your code without changing its externally visible behavior, ideally you\nshouldn't need to update any tests. If your code interacts with a naggy mock,\nhowever, you may start to get spammed with warnings as the result of your\nchange. Worse, if your code interacts with a strict mock, your tests may start\nto fail and you'll be forced to fix them. Our general recommendation is to use\nnice mocks (not yet the default) most of the time, use naggy mocks (the current\ndefault) when developing or debugging tests, and use strict mocks only as the\nlast resort.\n\n### Simplifying the Interface without Breaking Existing Code {#SimplerInterfaces}\n\nSometimes a method has a long list of arguments that is mostly uninteresting.\nFor example:\n\n```cpp\nclass LogSink {\n public:\n  ...\n  virtual void send(LogSeverity severity, const char* full_filename,\n                    const char* base_filename, int line,\n                    const struct tm* tm_time,\n                    const char* message, size_t message_len) = 0;\n};\n```\n\nThis method's argument list is lengthy and hard to work with (the `message`\nargument is not even 0-terminated). If we mock it as is, using the mock will be\nawkward. If, however, we try to simplify this interface, we'll need to fix all\nclients depending on it, which is often infeasible.\n\nThe trick is to redispatch the method in the mock class:\n\n```cpp\nclass ScopedMockLog : public LogSink {\n public:\n  ...\n  void send(LogSeverity severity, const char* full_filename,\n                    const char* base_filename, int line, const tm* tm_time,\n                    const char* message, size_t message_len) override {\n    // We are only interested in the log severity, full file name, and\n    // log message.\n    Log(severity, full_filename, std::string(message, message_len));\n  }\n\n  // Implements the mock method:\n  //\n  //   void Log(LogSeverity severity,\n  //            const string& file_path,\n  //            const string& message);\n  MOCK_METHOD(void, Log,\n              (LogSeverity severity, const string& file_path,\n               const string& message));\n};\n```\n\nBy defining a new mock method with a trimmed argument list, we make the mock\nclass more user-friendly.\n\nThis technique may also be applied to make overloaded methods more amenable to\nmocking. For example, when overloads have been used to implement default\narguments:\n\n```cpp\nclass MockTurtleFactory : public TurtleFactory {\n public:\n  Turtle* MakeTurtle(int length, int weight) override { ... }\n  Turtle* MakeTurtle(int length, int weight, int speed) override { ... }\n\n  // the above methods delegate to this one:\n  MOCK_METHOD(Turtle*, DoMakeTurtle, ());\n};\n```\n\nThis allows tests that don't care which overload was invoked to avoid specifying\nargument matchers:\n\n```cpp\nON_CALL(factory, DoMakeTurtle)\n    .WillByDefault(Return(MakeMockTurtle()));\n```\n\n### Alternative to Mocking Concrete Classes\n\nOften you may find yourself using classes that don't implement interfaces. In\norder to test your code that uses such a class (let's call it `Concrete`), you\nmay be tempted to make the methods of `Concrete` virtual and then mock it.\n\nTry not to do that.\n\nMaking a non-virtual function virtual is a big decision. It creates an extension\npoint where subclasses can tweak your class' behavior. This weakens your control\non the class because now it's harder to maintain the class invariants. You\nshould make a function virtual only when there is a valid reason for a subclass\nto override it.\n\nMocking concrete classes directly is problematic as it creates a tight coupling\nbetween the class and the tests - any small change in the class may invalidate\nyour tests and make test maintenance a pain.\n\nTo avoid such problems, many programmers have been practicing \"coding to\ninterfaces\": instead of talking to the `Concrete` class, your code would define\nan interface and talk to it. Then you implement that interface as an adaptor on\ntop of `Concrete`. In tests, you can easily mock that interface to observe how\nyour code is doing.\n\nThis technique incurs some overhead:\n\n*   You pay the cost of virtual function calls (usually not a problem).\n*   There is more abstraction for the programmers to learn.\n\nHowever, it can also bring significant benefits in addition to better\ntestability:\n\n*   `Concrete`'s API may not fit your problem domain very well, as you may not\n    be the only client it tries to serve. By designing your own interface, you\n    have a chance to tailor it to your need - you may add higher-level\n    functionalities, rename stuff, etc instead of just trimming the class. This\n    allows you to write your code (user of the interface) in a more natural way,\n    which means it will be more readable, more maintainable, and you'll be more\n    productive.\n*   If `Concrete`'s implementation ever has to change, you don't have to rewrite\n    everywhere it is used. Instead, you can absorb the change in your\n    implementation of the interface, and your other code and tests will be\n    insulated from this change.\n\nSome people worry that if everyone is practicing this technique, they will end\nup writing lots of redundant code. This concern is totally understandable.\nHowever, there are two reasons why it may not be the case:\n\n*   Different projects may need to use `Concrete` in different ways, so the best\n    interfaces for them will be different. Therefore, each of them will have its\n    own domain-specific interface on top of `Concrete`, and they will not be the\n    same code.\n*   If enough projects want to use the same interface, they can always share it,\n    just like they have been sharing `Concrete`. You can check in the interface\n    and the adaptor somewhere near `Concrete` (perhaps in a `contrib`\n    sub-directory) and let many projects use it.\n\nYou need to weigh the pros and cons carefully for your particular problem, but\nI'd like to assure you that the Java community has been practicing this for a\nlong time and it's a proven effective technique applicable in a wide variety of\nsituations. :-)\n\n### Delegating Calls to a Fake {#DelegatingToFake}\n\nSome times you have a non-trivial fake implementation of an interface. For\nexample:\n\n```cpp\nclass Foo {\n public:\n  virtual ~Foo() {}\n  virtual char DoThis(int n) = 0;\n  virtual void DoThat(const char* s, int* p) = 0;\n};\n\nclass FakeFoo : public Foo {\n public:\n  char DoThis(int n) override {\n    return (n > 0) ? '+' :\n           (n < 0) ? '-' : '0';\n  }\n\n  void DoThat(const char* s, int* p) override {\n    *p = strlen(s);\n  }\n};\n```\n\nNow you want to mock this interface such that you can set expectations on it.\nHowever, you also want to use `FakeFoo` for the default behavior, as duplicating\nit in the mock object is, well, a lot of work.\n\nWhen you define the mock class using gMock, you can have it delegate its default\naction to a fake class you already have, using this pattern:\n\n```cpp\nclass MockFoo : public Foo {\n public:\n  // Normal mock method definitions using gMock.\n  MOCK_METHOD(char, DoThis, (int n), (override));\n  MOCK_METHOD(void, DoThat, (const char* s, int* p), (override));\n\n  // Delegates the default actions of the methods to a FakeFoo object.\n  // This must be called *before* the custom ON_CALL() statements.\n  void DelegateToFake() {\n    ON_CALL(*this, DoThis).WillByDefault([this](int n) {\n      return fake_.DoThis(n);\n    });\n    ON_CALL(*this, DoThat).WillByDefault([this](const char* s, int* p) {\n      fake_.DoThat(s, p);\n    });\n  }\n\n private:\n  FakeFoo fake_;  // Keeps an instance of the fake in the mock.\n};\n```\n\nWith that, you can use `MockFoo` in your tests as usual. Just remember that if\nyou don't explicitly set an action in an `ON_CALL()` or `EXPECT_CALL()`, the\nfake will be called upon to do it.:\n\n```cpp\nusing ::testing::_;\n\nTEST(AbcTest, Xyz) {\n  MockFoo foo;\n\n  foo.DelegateToFake();  // Enables the fake for delegation.\n\n  // Put your ON_CALL(foo, ...)s here, if any.\n\n  // No action specified, meaning to use the default action.\n  EXPECT_CALL(foo, DoThis(5));\n  EXPECT_CALL(foo, DoThat(_, _));\n\n  int n = 0;\n  EXPECT_EQ('+', foo.DoThis(5));  // FakeFoo::DoThis() is invoked.\n  foo.DoThat(\"Hi\", &n);  // FakeFoo::DoThat() is invoked.\n  EXPECT_EQ(2, n);\n}\n```\n\n**Some tips:**\n\n*   If you want, you can still override the default action by providing your own\n    `ON_CALL()` or using `.WillOnce()` / `.WillRepeatedly()` in `EXPECT_CALL()`.\n*   In `DelegateToFake()`, you only need to delegate the methods whose fake\n    implementation you intend to use.\n\n*   The general technique discussed here works for overloaded methods, but\n    you'll need to tell the compiler which version you mean. To disambiguate a\n    mock function (the one you specify inside the parentheses of `ON_CALL()`),\n    use [this technique](#SelectOverload); to disambiguate a fake function (the\n    one you place inside `Invoke()`), use a `static_cast` to specify the\n    function's type. For instance, if class `Foo` has methods `char DoThis(int\n    n)` and `bool DoThis(double x) const`, and you want to invoke the latter,\n    you need to write `Invoke(&fake_, static_cast<bool (FakeFoo::*)(double)\n    const>(&FakeFoo::DoThis))` instead of `Invoke(&fake_, &FakeFoo::DoThis)`\n    (The strange-looking thing inside the angled brackets of `static_cast` is\n    the type of a function pointer to the second `DoThis()` method.).\n\n*   Having to mix a mock and a fake is often a sign of something gone wrong.\n    Perhaps you haven't got used to the interaction-based way of testing yet. Or\n    perhaps your interface is taking on too many roles and should be split up.\n    Therefore, **don't abuse this**. We would only recommend to do it as an\n    intermediate step when you are refactoring your code.\n\nRegarding the tip on mixing a mock and a fake, here's an example on why it may\nbe a bad sign: Suppose you have a class `System` for low-level system\noperations. In particular, it does file and I/O operations. And suppose you want\nto test how your code uses `System` to do I/O, and you just want the file\noperations to work normally. If you mock out the entire `System` class, you'll\nhave to provide a fake implementation for the file operation part, which\nsuggests that `System` is taking on too many roles.\n\nInstead, you can define a `FileOps` interface and an `IOOps` interface and split\n`System`'s functionalities into the two. Then you can mock `IOOps` without\nmocking `FileOps`.\n\n### Delegating Calls to a Real Object\n\nWhen using testing doubles (mocks, fakes, stubs, and etc), sometimes their\nbehaviors will differ from those of the real objects. This difference could be\neither intentional (as in simulating an error such that you can test the error\nhandling code) or unintentional. If your mocks have different behaviors than the\nreal objects by mistake, you could end up with code that passes the tests but\nfails in production.\n\nYou can use the *delegating-to-real* technique to ensure that your mock has the\nsame behavior as the real object while retaining the ability to validate calls.\nThis technique is very similar to the [delegating-to-fake](#DelegatingToFake)\ntechnique, the difference being that we use a real object instead of a fake.\nHere's an example:\n\n```cpp\nusing ::testing::AtLeast;\n\nclass MockFoo : public Foo {\n public:\n  MockFoo() {\n    // By default, all calls are delegated to the real object.\n    ON_CALL(*this, DoThis).WillByDefault([this](int n) {\n      return real_.DoThis(n);\n    });\n    ON_CALL(*this, DoThat).WillByDefault([this](const char* s, int* p) {\n      real_.DoThat(s, p);\n    });\n    ...\n  }\n  MOCK_METHOD(char, DoThis, ...);\n  MOCK_METHOD(void, DoThat, ...);\n  ...\n private:\n  Foo real_;\n};\n\n...\n  MockFoo mock;\n  EXPECT_CALL(mock, DoThis())\n      .Times(3);\n  EXPECT_CALL(mock, DoThat(\"Hi\"))\n      .Times(AtLeast(1));\n  ... use mock in test ...\n```\n\nWith this, gMock will verify that your code made the right calls (with the right\narguments, in the right order, called the right number of times, etc), and a\nreal object will answer the calls (so the behavior will be the same as in\nproduction). This gives you the best of both worlds.\n\n### Delegating Calls to a Parent Class\n\nIdeally, you should code to interfaces, whose methods are all pure virtual. In\nreality, sometimes you do need to mock a virtual method that is not pure (i.e,\nit already has an implementation). For example:\n\n```cpp\nclass Foo {\n public:\n  virtual ~Foo();\n\n  virtual void Pure(int n) = 0;\n  virtual int Concrete(const char* str) { ... }\n};\n\nclass MockFoo : public Foo {\n public:\n  // Mocking a pure method.\n  MOCK_METHOD(void, Pure, (int n), (override));\n  // Mocking a concrete method.  Foo::Concrete() is shadowed.\n  MOCK_METHOD(int, Concrete, (const char* str), (override));\n};\n```\n\nSometimes you may want to call `Foo::Concrete()` instead of\n`MockFoo::Concrete()`. Perhaps you want to do it as part of a stub action, or\nperhaps your test doesn't need to mock `Concrete()` at all (but it would be\noh-so painful to have to define a new mock class whenever you don't need to mock\none of its methods).\n\nYou can call `Foo::Concrete()` inside an action by:\n\n```cpp\n...\n  EXPECT_CALL(foo, Concrete).WillOnce([&foo](const char* str) {\n    return foo.Foo::Concrete(str);\n  });\n```\n\nor tell the mock object that you don't want to mock `Concrete()`:\n\n```cpp\n...\n  ON_CALL(foo, Concrete).WillByDefault([&foo](const char* str) {\n    return foo.Foo::Concrete(str);\n  });\n```\n\n(Why don't we just write `{ return foo.Concrete(str); }`? If you do that,\n`MockFoo::Concrete()` will be called (and cause an infinite recursion) since\n`Foo::Concrete()` is virtual. That's just how C++ works.)\n\n## Using Matchers\n\n### Matching Argument Values Exactly\n\nYou can specify exactly which arguments a mock method is expecting:\n\n```cpp\nusing ::testing::Return;\n...\n  EXPECT_CALL(foo, DoThis(5))\n      .WillOnce(Return('a'));\n  EXPECT_CALL(foo, DoThat(\"Hello\", bar));\n```\n\n### Using Simple Matchers\n\nYou can use matchers to match arguments that have a certain property:\n\n```cpp\nusing ::testing::NotNull;\nusing ::testing::Return;\n...\n  EXPECT_CALL(foo, DoThis(Ge(5)))  // The argument must be >= 5.\n      .WillOnce(Return('a'));\n  EXPECT_CALL(foo, DoThat(\"Hello\", NotNull()));\n      // The second argument must not be NULL.\n```\n\nA frequently used matcher is `_`, which matches anything:\n\n```cpp\n  EXPECT_CALL(foo, DoThat(_, NotNull()));\n```\n\n### Combining Matchers {#CombiningMatchers}\n\nYou can build complex matchers from existing ones using `AllOf()`,\n`AllOfArray()`, `AnyOf()`, `AnyOfArray()` and `Not()`:\n\n```cpp\nusing ::testing::AllOf;\nusing ::testing::Gt;\nusing ::testing::HasSubstr;\nusing ::testing::Ne;\nusing ::testing::Not;\n...\n  // The argument must be > 5 and != 10.\n  EXPECT_CALL(foo, DoThis(AllOf(Gt(5),\n                                Ne(10))));\n\n  // The first argument must not contain sub-string \"blah\".\n  EXPECT_CALL(foo, DoThat(Not(HasSubstr(\"blah\")),\n                          NULL));\n```\n\nMatchers are function objects, and parametrized matchers can be composed just\nlike any other function. However because their types can be long and rarely\nprovide meaningful information, it can be easier to express them with C++14\ngeneric lambdas to avoid specifying types. For example,\n\n```cpp\nusing ::testing::Contains;\nusing ::testing::Property;\n\ninline constexpr auto HasFoo = [](const auto& f) {\n  return Property(&MyClass::foo, Contains(f));\n};\n...\n  EXPECT_THAT(x, HasFoo(\"blah\"));\n```\n\n### Casting Matchers {#SafeMatcherCast}\n\ngMock matchers are statically typed, meaning that the compiler can catch your\nmistake if you use a matcher of the wrong type (for example, if you use `Eq(5)`\nto match a `string` argument). Good for you!\n\nSometimes, however, you know what you're doing and want the compiler to give you\nsome slack. One example is that you have a matcher for `long` and the argument\nyou want to match is `int`. While the two types aren't exactly the same, there\nis nothing really wrong with using a `Matcher<long>` to match an `int` - after\nall, we can first convert the `int` argument to a `long` losslessly before\ngiving it to the matcher.\n\nTo support this need, gMock gives you the `SafeMatcherCast<T>(m)` function. It\ncasts a matcher `m` to type `Matcher<T>`. To ensure safety, gMock checks that\n(let `U` be the type `m` accepts :\n\n1.  Type `T` can be *implicitly* cast to type `U`;\n2.  When both `T` and `U` are built-in arithmetic types (`bool`, integers, and\n    floating-point numbers), the conversion from `T` to `U` is not lossy (in\n    other words, any value representable by `T` can also be represented by `U`);\n    and\n3.  When `U` is a reference, `T` must also be a reference (as the underlying\n    matcher may be interested in the address of the `U` value).\n\nThe code won't compile if any of these conditions isn't met.\n\nHere's one example:\n\n```cpp\nusing ::testing::SafeMatcherCast;\n\n// A base class and a child class.\nclass Base { ... };\nclass Derived : public Base { ... };\n\nclass MockFoo : public Foo {\n public:\n  MOCK_METHOD(void, DoThis, (Derived* derived), (override));\n};\n\n...\n  MockFoo foo;\n  // m is a Matcher<Base*> we got from somewhere.\n  EXPECT_CALL(foo, DoThis(SafeMatcherCast<Derived*>(m)));\n```\n\nIf you find `SafeMatcherCast<T>(m)` too limiting, you can use a similar function\n`MatcherCast<T>(m)`. The difference is that `MatcherCast` works as long as you\ncan `static_cast` type `T` to type `U`.\n\n`MatcherCast` essentially lets you bypass C++'s type system (`static_cast` isn't\nalways safe as it could throw away information, for example), so be careful not\nto misuse/abuse it.\n\n### Selecting Between Overloaded Functions {#SelectOverload}\n\nIf you expect an overloaded function to be called, the compiler may need some\nhelp on which overloaded version it is.\n\nTo disambiguate functions overloaded on the const-ness of this object, use the\n`Const()` argument wrapper.\n\n```cpp\nusing ::testing::ReturnRef;\n\nclass MockFoo : public Foo {\n  ...\n  MOCK_METHOD(Bar&, GetBar, (), (override));\n  MOCK_METHOD(const Bar&, GetBar, (), (const, override));\n};\n\n...\n  MockFoo foo;\n  Bar bar1, bar2;\n  EXPECT_CALL(foo, GetBar())         // The non-const GetBar().\n      .WillOnce(ReturnRef(bar1));\n  EXPECT_CALL(Const(foo), GetBar())  // The const GetBar().\n      .WillOnce(ReturnRef(bar2));\n```\n\n(`Const()` is defined by gMock and returns a `const` reference to its argument.)\n\nTo disambiguate overloaded functions with the same number of arguments but\ndifferent argument types, you may need to specify the exact type of a matcher,\neither by wrapping your matcher in `Matcher<type>()`, or using a matcher whose\ntype is fixed (`TypedEq<type>`, `An<type>()`, etc):\n\n```cpp\nusing ::testing::An;\nusing ::testing::Matcher;\nusing ::testing::TypedEq;\n\nclass MockPrinter : public Printer {\n public:\n  MOCK_METHOD(void, Print, (int n), (override));\n  MOCK_METHOD(void, Print, (char c), (override));\n};\n\nTEST(PrinterTest, Print) {\n  MockPrinter printer;\n\n  EXPECT_CALL(printer, Print(An<int>()));            // void Print(int);\n  EXPECT_CALL(printer, Print(Matcher<int>(Lt(5))));  // void Print(int);\n  EXPECT_CALL(printer, Print(TypedEq<char>('a')));   // void Print(char);\n\n  printer.Print(3);\n  printer.Print(6);\n  printer.Print('a');\n}\n```\n\n### Performing Different Actions Based on the Arguments\n\nWhen a mock method is called, the *last* matching expectation that's still\nactive will be selected (think \"newer overrides older\"). So, you can make a\nmethod do different things depending on its argument values like this:\n\n```cpp\nusing ::testing::_;\nusing ::testing::Lt;\nusing ::testing::Return;\n...\n  // The default case.\n  EXPECT_CALL(foo, DoThis(_))\n      .WillRepeatedly(Return('b'));\n  // The more specific case.\n  EXPECT_CALL(foo, DoThis(Lt(5)))\n      .WillRepeatedly(Return('a'));\n```\n\nNow, if `foo.DoThis()` is called with a value less than 5, `'a'` will be\nreturned; otherwise `'b'` will be returned.\n\n### Matching Multiple Arguments as a Whole\n\nSometimes it's not enough to match the arguments individually. For example, we\nmay want to say that the first argument must be less than the second argument.\nThe `With()` clause allows us to match all arguments of a mock function as a\nwhole. For example,\n\n```cpp\nusing ::testing::_;\nusing ::testing::Ne;\nusing ::testing::Lt;\n...\n  EXPECT_CALL(foo, InRange(Ne(0), _))\n      .With(Lt());\n```\n\nsays that the first argument of `InRange()` must not be 0, and must be less than\nthe second argument.\n\nThe expression inside `With()` must be a matcher of type `Matcher<std::tuple<A1,\n..., An>>`, where `A1`, ..., `An` are the types of the function arguments.\n\nYou can also write `AllArgs(m)` instead of `m` inside `.With()`. The two forms\nare equivalent, but `.With(AllArgs(Lt()))` is more readable than `.With(Lt())`.\n\nYou can use `Args<k1, ..., kn>(m)` to match the `n` selected arguments (as a\ntuple) against `m`. For example,\n\n```cpp\nusing ::testing::_;\nusing ::testing::AllOf;\nusing ::testing::Args;\nusing ::testing::Lt;\n...\n  EXPECT_CALL(foo, Blah)\n      .With(AllOf(Args<0, 1>(Lt()), Args<1, 2>(Lt())));\n```\n\nsays that `Blah` will be called with arguments `x`, `y`, and `z` where `x < y <\nz`. Note that in this example, it wasn't necessary to specify the positional\nmatchers.\n\nAs a convenience and example, gMock provides some matchers for 2-tuples,\nincluding the `Lt()` matcher above. See\n[Multi-argument Matchers](reference/matchers.md#MultiArgMatchers) for the\ncomplete list.\n\nNote that if you want to pass the arguments to a predicate of your own (e.g.\n`.With(Args<0, 1>(Truly(&MyPredicate)))`), that predicate MUST be written to\ntake a `std::tuple` as its argument; gMock will pass the `n` selected arguments\nas *one* single tuple to the predicate.\n\n### Using Matchers as Predicates\n\nHave you noticed that a matcher is just a fancy predicate that also knows how to\ndescribe itself? Many existing algorithms take predicates as arguments (e.g.\nthose defined in STL's `<algorithm>` header), and it would be a shame if gMock\nmatchers were not allowed to participate.\n\nLuckily, you can use a matcher where a unary predicate functor is expected by\nwrapping it inside the `Matches()` function. For example,\n\n```cpp\n#include <algorithm>\n#include <vector>\n\nusing ::testing::Matches;\nusing ::testing::Ge;\n\nvector<int> v;\n...\n// How many elements in v are >= 10?\nconst int count = count_if(v.begin(), v.end(), Matches(Ge(10)));\n```\n\nSince you can build complex matchers from simpler ones easily using gMock, this\ngives you a way to conveniently construct composite predicates (doing the same\nusing STL's `<functional>` header is just painful). For example, here's a\npredicate that's satisfied by any number that is >= 0, <= 100, and != 50:\n\n```cpp\nusing testing::AllOf;\nusing testing::Ge;\nusing testing::Le;\nusing testing::Matches;\nusing testing::Ne;\n...\nMatches(AllOf(Ge(0), Le(100), Ne(50)))\n```\n\n### Using Matchers in googletest Assertions\n\nSee [`EXPECT_THAT`](reference/assertions.md#EXPECT_THAT) in the Assertions\nReference.\n\n### Using Predicates as Matchers\n\ngMock provides a set of built-in matchers for matching arguments with expected\nvalues—see the [Matchers Reference](reference/matchers.md) for more information.\nIn case you find the built-in set lacking, you can use an arbitrary unary\npredicate function or functor as a matcher - as long as the predicate accepts a\nvalue of the type you want. You do this by wrapping the predicate inside the\n`Truly()` function, for example:\n\n```cpp\nusing ::testing::Truly;\n\nint IsEven(int n) { return (n % 2) == 0 ? 1 : 0; }\n...\n  // Bar() must be called with an even number.\n  EXPECT_CALL(foo, Bar(Truly(IsEven)));\n```\n\nNote that the predicate function / functor doesn't have to return `bool`. It\nworks as long as the return value can be used as the condition in in statement\n`if (condition) ...`.\n\n### Matching Arguments that Are Not Copyable\n\nWhen you do an `EXPECT_CALL(mock_obj, Foo(bar))`, gMock saves away a copy of\n`bar`. When `Foo()` is called later, gMock compares the argument to `Foo()` with\nthe saved copy of `bar`. This way, you don't need to worry about `bar` being\nmodified or destroyed after the `EXPECT_CALL()` is executed. The same is true\nwhen you use matchers like `Eq(bar)`, `Le(bar)`, and so on.\n\nBut what if `bar` cannot be copied (i.e. has no copy constructor)? You could\ndefine your own matcher function or callback and use it with `Truly()`, as the\nprevious couple of recipes have shown. Or, you may be able to get away from it\nif you can guarantee that `bar` won't be changed after the `EXPECT_CALL()` is\nexecuted. Just tell gMock that it should save a reference to `bar`, instead of a\ncopy of it. Here's how:\n\n```cpp\nusing ::testing::Eq;\nusing ::testing::Lt;\n...\n  // Expects that Foo()'s argument == bar.\n  EXPECT_CALL(mock_obj, Foo(Eq(std::ref(bar))));\n\n  // Expects that Foo()'s argument < bar.\n  EXPECT_CALL(mock_obj, Foo(Lt(std::ref(bar))));\n```\n\nRemember: if you do this, don't change `bar` after the `EXPECT_CALL()`, or the\nresult is undefined.\n\n### Validating a Member of an Object\n\nOften a mock function takes a reference to object as an argument. When matching\nthe argument, you may not want to compare the entire object against a fixed\nobject, as that may be over-specification. Instead, you may need to validate a\ncertain member variable or the result of a certain getter method of the object.\nYou can do this with `Field()` and `Property()`. More specifically,\n\n```cpp\nField(&Foo::bar, m)\n```\n\nis a matcher that matches a `Foo` object whose `bar` member variable satisfies\nmatcher `m`.\n\n```cpp\nProperty(&Foo::baz, m)\n```\n\nis a matcher that matches a `Foo` object whose `baz()` method returns a value\nthat satisfies matcher `m`.\n\nFor example:\n\n| Expression                   | Description                              |\n| :--------------------------- | :--------------------------------------- |\n| `Field(&Foo::number, Ge(3))` | Matches `x` where `x.number >= 3`.       |\n| `Property(&Foo::name,  StartsWith(\"John \"))` | Matches `x` where `x.name()` starts with  `\"John \"`. |\n\nNote that in `Property(&Foo::baz, ...)`, method `baz()` must take no argument\nand be declared as `const`. Don't use `Property()` against member functions that\nyou do not own, because taking addresses of functions is fragile and generally\nnot part of the contract of the function.\n\n`Field()` and `Property()` can also match plain pointers to objects. For\ninstance,\n\n```cpp\nusing ::testing::Field;\nusing ::testing::Ge;\n...\nField(&Foo::number, Ge(3))\n```\n\nmatches a plain pointer `p` where `p->number >= 3`. If `p` is `NULL`, the match\nwill always fail regardless of the inner matcher.\n\nWhat if you want to validate more than one members at the same time? Remember\nthat there are [`AllOf()` and `AllOfArray()`](#CombiningMatchers).\n\nFinally `Field()` and `Property()` provide overloads that take the field or\nproperty names as the first argument to include it in the error message. This\ncan be useful when creating combined matchers.\n\n```cpp\nusing ::testing::AllOf;\nusing ::testing::Field;\nusing ::testing::Matcher;\nusing ::testing::SafeMatcherCast;\n\nMatcher<Foo> IsFoo(const Foo& foo) {\n  return AllOf(Field(\"some_field\", &Foo::some_field, foo.some_field),\n               Field(\"other_field\", &Foo::other_field, foo.other_field),\n               Field(\"last_field\", &Foo::last_field, foo.last_field));\n}\n```\n\n### Validating the Value Pointed to by a Pointer Argument\n\nC++ functions often take pointers as arguments. You can use matchers like\n`IsNull()`, `NotNull()`, and other comparison matchers to match a pointer, but\nwhat if you want to make sure the value *pointed to* by the pointer, instead of\nthe pointer itself, has a certain property? Well, you can use the `Pointee(m)`\nmatcher.\n\n`Pointee(m)` matches a pointer if and only if `m` matches the value the pointer\npoints to. For example:\n\n```cpp\nusing ::testing::Ge;\nusing ::testing::Pointee;\n...\n  EXPECT_CALL(foo, Bar(Pointee(Ge(3))));\n```\n\nexpects `foo.Bar()` to be called with a pointer that points to a value greater\nthan or equal to 3.\n\nOne nice thing about `Pointee()` is that it treats a `NULL` pointer as a match\nfailure, so you can write `Pointee(m)` instead of\n\n```cpp\nusing ::testing::AllOf;\nusing ::testing::NotNull;\nusing ::testing::Pointee;\n...\n  AllOf(NotNull(), Pointee(m))\n```\n\nwithout worrying that a `NULL` pointer will crash your test.\n\nAlso, did we tell you that `Pointee()` works with both raw pointers **and**\nsmart pointers (`std::unique_ptr`, `std::shared_ptr`, etc)?\n\nWhat if you have a pointer to pointer? You guessed it - you can use nested\n`Pointee()` to probe deeper inside the value. For example,\n`Pointee(Pointee(Lt(3)))` matches a pointer that points to a pointer that points\nto a number less than 3 (what a mouthful...).\n\n### Defining a Custom Matcher Class {#CustomMatcherClass}\n\nMost matchers can be simply defined using [the MATCHER* macros](#NewMatchers),\nwhich are terse and flexible, and produce good error messages. However, these\nmacros are not very explicit about the interfaces they create and are not always\nsuitable, especially for matchers that will be widely reused.\n\nFor more advanced cases, you may need to define your own matcher class. A custom\nmatcher allows you to test a specific invariant property of that object. Let's\ntake a look at how to do so.\n\nImagine you have a mock function that takes an object of type `Foo`, which has\nan `int bar()` method and an `int baz()` method. You want to constrain that the\nargument's `bar()` value plus its `baz()` value is a given number. (This is an\ninvariant.) Here's how we can write and use a matcher class to do so:\n\n```cpp\nclass BarPlusBazEqMatcher {\n public:\n  using is_gtest_matcher = void;\n\n  explicit BarPlusBazEqMatcher(int expected_sum)\n      : expected_sum_(expected_sum) {}\n\n  bool MatchAndExplain(const Foo& foo,\n                       std::ostream* /* listener */) const {\n    return (foo.bar() + foo.baz()) == expected_sum_;\n  }\n\n  void DescribeTo(std::ostream* os) const {\n    *os << \"bar() + baz() equals \" << expected_sum_;\n  }\n\n  void DescribeNegationTo(std::ostream* os) const {\n    *os << \"bar() + baz() does not equal \" << expected_sum_;\n  }\n private:\n  const int expected_sum_;\n};\n\n::testing::Matcher<const Foo&> BarPlusBazEq(int expected_sum) {\n  return BarPlusBazEqMatcher(expected_sum);\n}\n\n...\n  Foo foo;\n  EXPECT_CALL(foo, BarPlusBazEq(5))...;\n```\n\n### Matching Containers\n\nSometimes an STL container (e.g. list, vector, map, ...) is passed to a mock\nfunction and you may want to validate it. Since most STL containers support the\n`==` operator, you can write `Eq(expected_container)` or simply\n`expected_container` to match a container exactly.\n\nSometimes, though, you may want to be more flexible (for example, the first\nelement must be an exact match, but the second element can be any positive\nnumber, and so on). Also, containers used in tests often have a small number of\nelements, and having to define the expected container out-of-line is a bit of a\nhassle.\n\nYou can use the `ElementsAre()` or `UnorderedElementsAre()` matcher in such\ncases:\n\n```cpp\nusing ::testing::_;\nusing ::testing::ElementsAre;\nusing ::testing::Gt;\n...\n  MOCK_METHOD(void, Foo, (const vector<int>& numbers), (override));\n...\n  EXPECT_CALL(mock, Foo(ElementsAre(1, Gt(0), _, 5)));\n```\n\nThe above matcher says that the container must have 4 elements, which must be 1,\ngreater than 0, anything, and 5 respectively.\n\nIf you instead write:\n\n```cpp\nusing ::testing::_;\nusing ::testing::Gt;\nusing ::testing::UnorderedElementsAre;\n...\n  MOCK_METHOD(void, Foo, (const vector<int>& numbers), (override));\n...\n  EXPECT_CALL(mock, Foo(UnorderedElementsAre(1, Gt(0), _, 5)));\n```\n\nIt means that the container must have 4 elements, which (under some permutation)\nmust be 1, greater than 0, anything, and 5 respectively.\n\nAs an alternative you can place the arguments in a C-style array and use\n`ElementsAreArray()` or `UnorderedElementsAreArray()` instead:\n\n```cpp\nusing ::testing::ElementsAreArray;\n...\n  // ElementsAreArray accepts an array of element values.\n  const int expected_vector1[] = {1, 5, 2, 4, ...};\n  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector1)));\n\n  // Or, an array of element matchers.\n  Matcher<int> expected_vector2[] = {1, Gt(2), _, 3, ...};\n  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector2)));\n```\n\nIn case the array needs to be dynamically created (and therefore the array size\ncannot be inferred by the compiler), you can give `ElementsAreArray()` an\nadditional argument to specify the array size:\n\n```cpp\nusing ::testing::ElementsAreArray;\n...\n  int* const expected_vector3 = new int[count];\n  ... fill expected_vector3 with values ...\n  EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector3, count)));\n```\n\nUse `Pair` when comparing maps or other associative containers.\n\n{% raw %}\n\n```cpp\nusing testing::ElementsAre;\nusing testing::Pair;\n...\n  std::map<string, int> m = {{\"a\", 1}, {\"b\", 2}, {\"c\", 3}};\n  EXPECT_THAT(m, ElementsAre(Pair(\"a\", 1), Pair(\"b\", 2), Pair(\"c\", 3)));\n```\n\n{% endraw %}\n\n**Tips:**\n\n*   `ElementsAre*()` can be used to match *any* container that implements the\n    STL iterator pattern (i.e. it has a `const_iterator` type and supports\n    `begin()/end()`), not just the ones defined in STL. It will even work with\n    container types yet to be written - as long as they follows the above\n    pattern.\n*   You can use nested `ElementsAre*()` to match nested (multi-dimensional)\n    containers.\n*   If the container is passed by pointer instead of by reference, just write\n    `Pointee(ElementsAre*(...))`.\n*   The order of elements *matters* for `ElementsAre*()`. If you are using it\n    with containers whose element order are undefined (e.g. `hash_map`) you\n    should use `WhenSorted` around `ElementsAre`.\n\n### Sharing Matchers\n\nUnder the hood, a gMock matcher object consists of a pointer to a ref-counted\nimplementation object. Copying matchers is allowed and very efficient, as only\nthe pointer is copied. When the last matcher that references the implementation\nobject dies, the implementation object will be deleted.\n\nTherefore, if you have some complex matcher that you want to use again and\nagain, there is no need to build it every time. Just assign it to a matcher\nvariable and use that variable repeatedly! For example,\n\n```cpp\nusing ::testing::AllOf;\nusing ::testing::Gt;\nusing ::testing::Le;\nusing ::testing::Matcher;\n...\n  Matcher<int> in_range = AllOf(Gt(5), Le(10));\n  ... use in_range as a matcher in multiple EXPECT_CALLs ...\n```\n\n### Matchers must have no side-effects {#PureMatchers}\n\n{: .callout .warning}\nWARNING: gMock does not guarantee when or how many times a matcher will be\ninvoked. Therefore, all matchers must be *purely functional*: they cannot have\nany side effects, and the match result must not depend on anything other than\nthe matcher's parameters and the value being matched.\n\nThis requirement must be satisfied no matter how a matcher is defined (e.g., if\nit is one of the standard matchers, or a custom matcher). In particular, a\nmatcher can never call a mock function, as that will affect the state of the\nmock object and gMock.\n\n## Setting Expectations\n\n### Knowing When to Expect {#UseOnCall}\n\n**`ON_CALL`** is likely the *single most under-utilized construct* in gMock.\n\nThere are basically two constructs for defining the behavior of a mock object:\n`ON_CALL` and `EXPECT_CALL`. The difference? `ON_CALL` defines what happens when\na mock method is called, but <em>doesn't imply any expectation on the method\nbeing called</em>. `EXPECT_CALL` not only defines the behavior, but also sets an\nexpectation that <em>the method will be called with the given arguments, for the\ngiven number of times</em> (and *in the given order* when you specify the order\ntoo).\n\nSince `EXPECT_CALL` does more, isn't it better than `ON_CALL`? Not really. Every\n`EXPECT_CALL` adds a constraint on the behavior of the code under test. Having\nmore constraints than necessary is *baaad* - even worse than not having enough\nconstraints.\n\nThis may be counter-intuitive. How could tests that verify more be worse than\ntests that verify less? Isn't verification the whole point of tests?\n\nThe answer lies in *what* a test should verify. **A good test verifies the\ncontract of the code.** If a test over-specifies, it doesn't leave enough\nfreedom to the implementation. As a result, changing the implementation without\nbreaking the contract (e.g. refactoring and optimization), which should be\nperfectly fine to do, can break such tests. Then you have to spend time fixing\nthem, only to see them broken again the next time the implementation is changed.\n\nKeep in mind that one doesn't have to verify more than one property in one test.\nIn fact, **it's a good style to verify only one thing in one test.** If you do\nthat, a bug will likely break only one or two tests instead of dozens (which\ncase would you rather debug?). If you are also in the habit of giving tests\ndescriptive names that tell what they verify, you can often easily guess what's\nwrong just from the test log itself.\n\nSo use `ON_CALL` by default, and only use `EXPECT_CALL` when you actually intend\nto verify that the call is made. For example, you may have a bunch of `ON_CALL`s\nin your test fixture to set the common mock behavior shared by all tests in the\nsame group, and write (scarcely) different `EXPECT_CALL`s in different `TEST_F`s\nto verify different aspects of the code's behavior. Compared with the style\nwhere each `TEST` has many `EXPECT_CALL`s, this leads to tests that are more\nresilient to implementational changes (and thus less likely to require\nmaintenance) and makes the intent of the tests more obvious (so they are easier\nto maintain when you do need to maintain them).\n\nIf you are bothered by the \"Uninteresting mock function call\" message printed\nwhen a mock method without an `EXPECT_CALL` is called, you may use a `NiceMock`\ninstead to suppress all such messages for the mock object, or suppress the\nmessage for specific methods by adding `EXPECT_CALL(...).Times(AnyNumber())`. DO\nNOT suppress it by blindly adding an `EXPECT_CALL(...)`, or you'll have a test\nthat's a pain to maintain.\n\n### Ignoring Uninteresting Calls\n\nIf you are not interested in how a mock method is called, just don't say\nanything about it. In this case, if the method is ever called, gMock will\nperform its default action to allow the test program to continue. If you are not\nhappy with the default action taken by gMock, you can override it using\n`DefaultValue<T>::Set()` (described [here](#DefaultValue)) or `ON_CALL()`.\n\nPlease note that once you expressed interest in a particular mock method (via\n`EXPECT_CALL()`), all invocations to it must match some expectation. If this\nfunction is called but the arguments don't match any `EXPECT_CALL()` statement,\nit will be an error.\n\n### Disallowing Unexpected Calls\n\nIf a mock method shouldn't be called at all, explicitly say so:\n\n```cpp\nusing ::testing::_;\n...\n  EXPECT_CALL(foo, Bar(_))\n      .Times(0);\n```\n\nIf some calls to the method are allowed, but the rest are not, just list all the\nexpected calls:\n\n```cpp\nusing ::testing::AnyNumber;\nusing ::testing::Gt;\n...\n  EXPECT_CALL(foo, Bar(5));\n  EXPECT_CALL(foo, Bar(Gt(10)))\n      .Times(AnyNumber());\n```\n\nA call to `foo.Bar()` that doesn't match any of the `EXPECT_CALL()` statements\nwill be an error.\n\n### Understanding Uninteresting vs Unexpected Calls {#uninteresting-vs-unexpected}\n\n*Uninteresting* calls and *unexpected* calls are different concepts in gMock.\n*Very* different.\n\nA call `x.Y(...)` is **uninteresting** if there's *not even a single*\n`EXPECT_CALL(x, Y(...))` set. In other words, the test isn't interested in the\n`x.Y()` method at all, as evident in that the test doesn't care to say anything\nabout it.\n\nA call `x.Y(...)` is **unexpected** if there are *some* `EXPECT_CALL(x,\nY(...))`s set, but none of them matches the call. Put another way, the test is\ninterested in the `x.Y()` method (therefore it explicitly sets some\n`EXPECT_CALL` to verify how it's called); however, the verification fails as the\ntest doesn't expect this particular call to happen.\n\n**An unexpected call is always an error,** as the code under test doesn't behave\nthe way the test expects it to behave.\n\n**By default, an uninteresting call is not an error,** as it violates no\nconstraint specified by the test. (gMock's philosophy is that saying nothing\nmeans there is no constraint.) However, it leads to a warning, as it *might*\nindicate a problem (e.g. the test author might have forgotten to specify a\nconstraint).\n\nIn gMock, `NiceMock` and `StrictMock` can be used to make a mock class \"nice\" or\n\"strict\". How does this affect uninteresting calls and unexpected calls?\n\nA **nice mock** suppresses uninteresting call *warnings*. It is less chatty than\nthe default mock, but otherwise is the same. If a test fails with a default\nmock, it will also fail using a nice mock instead. And vice versa. Don't expect\nmaking a mock nice to change the test's result.\n\nA **strict mock** turns uninteresting call warnings into errors. So making a\nmock strict may change the test's result.\n\nLet's look at an example:\n\n```cpp\nTEST(...) {\n  NiceMock<MockDomainRegistry> mock_registry;\n  EXPECT_CALL(mock_registry, GetDomainOwner(\"google.com\"))\n          .WillRepeatedly(Return(\"Larry Page\"));\n\n  // Use mock_registry in code under test.\n  ... &mock_registry ...\n}\n```\n\nThe sole `EXPECT_CALL` here says that all calls to `GetDomainOwner()` must have\n`\"google.com\"` as the argument. If `GetDomainOwner(\"yahoo.com\")` is called, it\nwill be an unexpected call, and thus an error. *Having a nice mock doesn't\nchange the severity of an unexpected call.*\n\nSo how do we tell gMock that `GetDomainOwner()` can be called with some other\narguments as well? The standard technique is to add a \"catch all\" `EXPECT_CALL`:\n\n```cpp\n  EXPECT_CALL(mock_registry, GetDomainOwner(_))\n        .Times(AnyNumber());  // catches all other calls to this method.\n  EXPECT_CALL(mock_registry, GetDomainOwner(\"google.com\"))\n        .WillRepeatedly(Return(\"Larry Page\"));\n```\n\nRemember that `_` is the wildcard matcher that matches anything. With this, if\n`GetDomainOwner(\"google.com\")` is called, it will do what the second\n`EXPECT_CALL` says; if it is called with a different argument, it will do what\nthe first `EXPECT_CALL` says.\n\nNote that the order of the two `EXPECT_CALL`s is important, as a newer\n`EXPECT_CALL` takes precedence over an older one.\n\nFor more on uninteresting calls, nice mocks, and strict mocks, read\n[\"The Nice, the Strict, and the Naggy\"](#NiceStrictNaggy).\n\n### Ignoring Uninteresting Arguments {#ParameterlessExpectations}\n\nIf your test doesn't care about the parameters (it only cares about the number\nor order of calls), you can often simply omit the parameter list:\n\n```cpp\n  // Expect foo.Bar( ... ) twice with any arguments.\n  EXPECT_CALL(foo, Bar).Times(2);\n\n  // Delegate to the given method whenever the factory is invoked.\n  ON_CALL(foo_factory, MakeFoo)\n      .WillByDefault(&BuildFooForTest);\n```\n\nThis functionality is only available when a method is not overloaded; to prevent\nunexpected behavior it is a compilation error to try to set an expectation on a\nmethod where the specific overload is ambiguous. You can work around this by\nsupplying a [simpler mock interface](#SimplerInterfaces) than the mocked class\nprovides.\n\nThis pattern is also useful when the arguments are interesting, but match logic\nis substantially complex. You can leave the argument list unspecified and use\nSaveArg actions to [save the values for later verification](#SaveArgVerify). If\nyou do that, you can easily differentiate calling the method the wrong number of\ntimes from calling it with the wrong arguments.\n\n### Expecting Ordered Calls {#OrderedCalls}\n\nAlthough an `EXPECT_CALL()` statement defined later takes precedence when gMock\ntries to match a function call with an expectation, by default calls don't have\nto happen in the order `EXPECT_CALL()` statements are written. For example, if\nthe arguments match the matchers in the second `EXPECT_CALL()`, but not those in\nthe first and third, then the second expectation will be used.\n\nIf you would rather have all calls occur in the order of the expectations, put\nthe `EXPECT_CALL()` statements in a block where you define a variable of type\n`InSequence`:\n\n```cpp\nusing ::testing::_;\nusing ::testing::InSequence;\n\n  {\n    InSequence s;\n\n    EXPECT_CALL(foo, DoThis(5));\n    EXPECT_CALL(bar, DoThat(_))\n        .Times(2);\n    EXPECT_CALL(foo, DoThis(6));\n  }\n```\n\nIn this example, we expect a call to `foo.DoThis(5)`, followed by two calls to\n`bar.DoThat()` where the argument can be anything, which are in turn followed by\na call to `foo.DoThis(6)`. If a call occurred out-of-order, gMock will report an\nerror.\n\n### Expecting Partially Ordered Calls {#PartialOrder}\n\nSometimes requiring everything to occur in a predetermined order can lead to\nbrittle tests. For example, we may care about `A` occurring before both `B` and\n`C`, but aren't interested in the relative order of `B` and `C`. In this case,\nthe test should reflect our real intent, instead of being overly constraining.\n\ngMock allows you to impose an arbitrary DAG (directed acyclic graph) on the\ncalls. One way to express the DAG is to use the\n[`After` clause](reference/mocking.md#EXPECT_CALL.After) of `EXPECT_CALL`.\n\nAnother way is via the `InSequence()` clause (not the same as the `InSequence`\nclass), which we borrowed from jMock 2. It's less flexible than `After()`, but\nmore convenient when you have long chains of sequential calls, as it doesn't\nrequire you to come up with different names for the expectations in the chains.\nHere's how it works:\n\nIf we view `EXPECT_CALL()` statements as nodes in a graph, and add an edge from\nnode A to node B wherever A must occur before B, we can get a DAG. We use the\nterm \"sequence\" to mean a directed path in this DAG. Now, if we decompose the\nDAG into sequences, we just need to know which sequences each `EXPECT_CALL()`\nbelongs to in order to be able to reconstruct the original DAG.\n\nSo, to specify the partial order on the expectations we need to do two things:\nfirst to define some `Sequence` objects, and then for each `EXPECT_CALL()` say\nwhich `Sequence` objects it is part of.\n\nExpectations in the same sequence must occur in the order they are written. For\nexample,\n\n```cpp\nusing ::testing::Sequence;\n...\n  Sequence s1, s2;\n\n  EXPECT_CALL(foo, A())\n      .InSequence(s1, s2);\n  EXPECT_CALL(bar, B())\n      .InSequence(s1);\n  EXPECT_CALL(bar, C())\n      .InSequence(s2);\n  EXPECT_CALL(foo, D())\n      .InSequence(s2);\n```\n\nspecifies the following DAG (where `s1` is `A -> B`, and `s2` is `A -> C -> D`):\n\n```text\n       +---> B\n       |\n  A ---|\n       |\n       +---> C ---> D\n```\n\nThis means that A must occur before B and C, and C must occur before D. There's\nno restriction about the order other than these.\n\n### Controlling When an Expectation Retires\n\nWhen a mock method is called, gMock only considers expectations that are still\nactive. An expectation is active when created, and becomes inactive (aka\n*retires*) when a call that has to occur later has occurred. For example, in\n\n```cpp\nusing ::testing::_;\nusing ::testing::Sequence;\n...\n  Sequence s1, s2;\n\n  EXPECT_CALL(log, Log(WARNING, _, \"File too large.\"))      // #1\n      .Times(AnyNumber())\n      .InSequence(s1, s2);\n  EXPECT_CALL(log, Log(WARNING, _, \"Data set is empty.\"))   // #2\n      .InSequence(s1);\n  EXPECT_CALL(log, Log(WARNING, _, \"User not found.\"))      // #3\n      .InSequence(s2);\n```\n\nas soon as either #2 or #3 is matched, #1 will retire. If a warning `\"File too\nlarge.\"` is logged after this, it will be an error.\n\nNote that an expectation doesn't retire automatically when it's saturated. For\nexample,\n\n```cpp\nusing ::testing::_;\n...\n  EXPECT_CALL(log, Log(WARNING, _, _));                     // #1\n  EXPECT_CALL(log, Log(WARNING, _, \"File too large.\"));     // #2\n```\n\nsays that there will be exactly one warning with the message `\"File too\nlarge.\"`. If the second warning contains this message too, #2 will match again\nand result in an upper-bound-violated error.\n\nIf this is not what you want, you can ask an expectation to retire as soon as it\nbecomes saturated:\n\n```cpp\nusing ::testing::_;\n...\n  EXPECT_CALL(log, Log(WARNING, _, _));                     // #1\n  EXPECT_CALL(log, Log(WARNING, _, \"File too large.\"))      // #2\n      .RetiresOnSaturation();\n```\n\nHere #2 can be used only once, so if you have two warnings with the message\n`\"File too large.\"`, the first will match #2 and the second will match #1 -\nthere will be no error.\n\n## Using Actions\n\n### Returning References from Mock Methods\n\nIf a mock function's return type is a reference, you need to use `ReturnRef()`\ninstead of `Return()` to return a result:\n\n```cpp\nusing ::testing::ReturnRef;\n\nclass MockFoo : public Foo {\n public:\n  MOCK_METHOD(Bar&, GetBar, (), (override));\n};\n...\n  MockFoo foo;\n  Bar bar;\n  EXPECT_CALL(foo, GetBar())\n      .WillOnce(ReturnRef(bar));\n...\n```\n\n### Returning Live Values from Mock Methods\n\nThe `Return(x)` action saves a copy of `x` when the action is created, and\nalways returns the same value whenever it's executed. Sometimes you may want to\ninstead return the *live* value of `x` (i.e. its value at the time when the\naction is *executed*.). Use either `ReturnRef()` or `ReturnPointee()` for this\npurpose.\n\nIf the mock function's return type is a reference, you can do it using\n`ReturnRef(x)`, as shown in the previous recipe (\"Returning References from Mock\nMethods\"). However, gMock doesn't let you use `ReturnRef()` in a mock function\nwhose return type is not a reference, as doing that usually indicates a user\nerror. So, what shall you do?\n\nThough you may be tempted, DO NOT use `std::ref()`:\n\n```cpp\nusing testing::Return;\n\nclass MockFoo : public Foo {\n public:\n  MOCK_METHOD(int, GetValue, (), (override));\n};\n...\n  int x = 0;\n  MockFoo foo;\n  EXPECT_CALL(foo, GetValue())\n      .WillRepeatedly(Return(std::ref(x)));  // Wrong!\n  x = 42;\n  EXPECT_EQ(42, foo.GetValue());\n```\n\nUnfortunately, it doesn't work here. The above code will fail with error:\n\n```text\nValue of: foo.GetValue()\n  Actual: 0\nExpected: 42\n```\n\nThe reason is that `Return(*value*)` converts `value` to the actual return type\nof the mock function at the time when the action is *created*, not when it is\n*executed*. (This behavior was chosen for the action to be safe when `value` is\na proxy object that references some temporary objects.) As a result,\n`std::ref(x)` is converted to an `int` value (instead of a `const int&`) when\nthe expectation is set, and `Return(std::ref(x))` will always return 0.\n\n`ReturnPointee(pointer)` was provided to solve this problem specifically. It\nreturns the value pointed to by `pointer` at the time the action is *executed*:\n\n```cpp\nusing testing::ReturnPointee;\n...\n  int x = 0;\n  MockFoo foo;\n  EXPECT_CALL(foo, GetValue())\n      .WillRepeatedly(ReturnPointee(&x));  // Note the & here.\n  x = 42;\n  EXPECT_EQ(42, foo.GetValue());  // This will succeed now.\n```\n\n### Combining Actions\n\nWant to do more than one thing when a function is called? That's fine. `DoAll()`\nallow you to do sequence of actions every time. Only the return value of the\nlast action in the sequence will be used.\n\n```cpp\nusing ::testing::_;\nusing ::testing::DoAll;\n\nclass MockFoo : public Foo {\n public:\n  MOCK_METHOD(bool, Bar, (int n), (override));\n};\n...\n  EXPECT_CALL(foo, Bar(_))\n      .WillOnce(DoAll(action_1,\n                      action_2,\n                      ...\n                      action_n));\n```\n\n### Verifying Complex Arguments {#SaveArgVerify}\n\nIf you want to verify that a method is called with a particular argument but the\nmatch criteria is complex, it can be difficult to distinguish between\ncardinality failures (calling the method the wrong number of times) and argument\nmatch failures. Similarly, if you are matching multiple parameters, it may not\nbe easy to distinguishing which argument failed to match. For example:\n\n```cpp\n  // Not ideal: this could fail because of a problem with arg1 or arg2, or maybe\n  // just the method wasn't called.\n  EXPECT_CALL(foo, SendValues(_, ElementsAre(1, 4, 4, 7), EqualsProto( ... )));\n```\n\nYou can instead save the arguments and test them individually:\n\n```cpp\n  EXPECT_CALL(foo, SendValues)\n      .WillOnce(DoAll(SaveArg<1>(&actual_array), SaveArg<2>(&actual_proto)));\n  ... run the test\n  EXPECT_THAT(actual_array, ElementsAre(1, 4, 4, 7));\n  EXPECT_THAT(actual_proto, EqualsProto( ... ));\n```\n\n### Mocking Side Effects {#MockingSideEffects}\n\nSometimes a method exhibits its effect not via returning a value but via side\neffects. For example, it may change some global state or modify an output\nargument. To mock side effects, in general you can define your own action by\nimplementing `::testing::ActionInterface`.\n\nIf all you need to do is to change an output argument, the built-in\n`SetArgPointee()` action is convenient:\n\n```cpp\nusing ::testing::_;\nusing ::testing::SetArgPointee;\n\nclass MockMutator : public Mutator {\n public:\n  MOCK_METHOD(void, Mutate, (bool mutate, int* value), (override));\n  ...\n}\n...\n  MockMutator mutator;\n  EXPECT_CALL(mutator, Mutate(true, _))\n      .WillOnce(SetArgPointee<1>(5));\n```\n\nIn this example, when `mutator.Mutate()` is called, we will assign 5 to the\n`int` variable pointed to by argument #1 (0-based).\n\n`SetArgPointee()` conveniently makes an internal copy of the value you pass to\nit, removing the need to keep the value in scope and alive. The implication\nhowever is that the value must have a copy constructor and assignment operator.\n\nIf the mock method also needs to return a value as well, you can chain\n`SetArgPointee()` with `Return()` using `DoAll()`, remembering to put the\n`Return()` statement last:\n\n```cpp\nusing ::testing::_;\nusing ::testing::DoAll;\nusing ::testing::Return;\nusing ::testing::SetArgPointee;\n\nclass MockMutator : public Mutator {\n public:\n  ...\n  MOCK_METHOD(bool, MutateInt, (int* value), (override));\n}\n...\n  MockMutator mutator;\n  EXPECT_CALL(mutator, MutateInt(_))\n      .WillOnce(DoAll(SetArgPointee<0>(5),\n                      Return(true)));\n```\n\nNote, however, that if you use the `ReturnOKWith()` method, it will override the\nvalues provided by `SetArgPointee()` in the response parameters of your function\ncall.\n\nIf the output argument is an array, use the `SetArrayArgument<N>(first, last)`\naction instead. It copies the elements in source range `[first, last)` to the\narray pointed to by the `N`-th (0-based) argument:\n\n```cpp\nusing ::testing::NotNull;\nusing ::testing::SetArrayArgument;\n\nclass MockArrayMutator : public ArrayMutator {\n public:\n  MOCK_METHOD(void, Mutate, (int* values, int num_values), (override));\n  ...\n}\n...\n  MockArrayMutator mutator;\n  int values[5] = {1, 2, 3, 4, 5};\n  EXPECT_CALL(mutator, Mutate(NotNull(), 5))\n      .WillOnce(SetArrayArgument<0>(values, values + 5));\n```\n\nThis also works when the argument is an output iterator:\n\n```cpp\nusing ::testing::_;\nusing ::testing::SetArrayArgument;\n\nclass MockRolodex : public Rolodex {\n public:\n  MOCK_METHOD(void, GetNames, (std::back_insert_iterator<vector<string>>),\n              (override));\n  ...\n}\n...\n  MockRolodex rolodex;\n  vector<string> names = {\"George\", \"John\", \"Thomas\"};\n  EXPECT_CALL(rolodex, GetNames(_))\n      .WillOnce(SetArrayArgument<0>(names.begin(), names.end()));\n```\n\n### Changing a Mock Object's Behavior Based on the State\n\nIf you expect a call to change the behavior of a mock object, you can use\n`::testing::InSequence` to specify different behaviors before and after the\ncall:\n\n```cpp\nusing ::testing::InSequence;\nusing ::testing::Return;\n\n...\n  {\n     InSequence seq;\n     EXPECT_CALL(my_mock, IsDirty())\n         .WillRepeatedly(Return(true));\n     EXPECT_CALL(my_mock, Flush());\n     EXPECT_CALL(my_mock, IsDirty())\n         .WillRepeatedly(Return(false));\n  }\n  my_mock.FlushIfDirty();\n```\n\nThis makes `my_mock.IsDirty()` return `true` before `my_mock.Flush()` is called\nand return `false` afterwards.\n\nIf the behavior change is more complex, you can store the effects in a variable\nand make a mock method get its return value from that variable:\n\n```cpp\nusing ::testing::_;\nusing ::testing::SaveArg;\nusing ::testing::Return;\n\nACTION_P(ReturnPointee, p) { return *p; }\n...\n  int previous_value = 0;\n  EXPECT_CALL(my_mock, GetPrevValue)\n      .WillRepeatedly(ReturnPointee(&previous_value));\n  EXPECT_CALL(my_mock, UpdateValue)\n      .WillRepeatedly(SaveArg<0>(&previous_value));\n  my_mock.DoSomethingToUpdateValue();\n```\n\nHere `my_mock.GetPrevValue()` will always return the argument of the last\n`UpdateValue()` call.\n\n### Setting the Default Value for a Return Type {#DefaultValue}\n\nIf a mock method's return type is a built-in C++ type or pointer, by default it\nwill return 0 when invoked. Also, in C++ 11 and above, a mock method whose\nreturn type has a default constructor will return a default-constructed value by\ndefault. You only need to specify an action if this default value doesn't work\nfor you.\n\nSometimes, you may want to change this default value, or you may want to specify\na default value for types gMock doesn't know about. You can do this using the\n`::testing::DefaultValue` class template:\n\n```cpp\nusing ::testing::DefaultValue;\n\nclass MockFoo : public Foo {\n public:\n  MOCK_METHOD(Bar, CalculateBar, (), (override));\n};\n\n\n...\n  Bar default_bar;\n  // Sets the default return value for type Bar.\n  DefaultValue<Bar>::Set(default_bar);\n\n  MockFoo foo;\n\n  // We don't need to specify an action here, as the default\n  // return value works for us.\n  EXPECT_CALL(foo, CalculateBar());\n\n  foo.CalculateBar();  // This should return default_bar.\n\n  // Unsets the default return value.\n  DefaultValue<Bar>::Clear();\n```\n\nPlease note that changing the default value for a type can make your tests hard\nto understand. We recommend you to use this feature judiciously. For example,\nyou may want to make sure the `Set()` and `Clear()` calls are right next to the\ncode that uses your mock.\n\n### Setting the Default Actions for a Mock Method\n\nYou've learned how to change the default value of a given type. However, this\nmay be too coarse for your purpose: perhaps you have two mock methods with the\nsame return type and you want them to have different behaviors. The `ON_CALL()`\nmacro allows you to customize your mock's behavior at the method level:\n\n```cpp\nusing ::testing::_;\nusing ::testing::AnyNumber;\nusing ::testing::Gt;\nusing ::testing::Return;\n...\n  ON_CALL(foo, Sign(_))\n      .WillByDefault(Return(-1));\n  ON_CALL(foo, Sign(0))\n      .WillByDefault(Return(0));\n  ON_CALL(foo, Sign(Gt(0)))\n      .WillByDefault(Return(1));\n\n  EXPECT_CALL(foo, Sign(_))\n      .Times(AnyNumber());\n\n  foo.Sign(5);   // This should return 1.\n  foo.Sign(-9);  // This should return -1.\n  foo.Sign(0);   // This should return 0.\n```\n\nAs you may have guessed, when there are more than one `ON_CALL()` statements,\nthe newer ones in the order take precedence over the older ones. In other words,\nthe **last** one that matches the function arguments will be used. This matching\norder allows you to set up the common behavior in a mock object's constructor or\nthe test fixture's set-up phase and specialize the mock's behavior later.\n\nNote that both `ON_CALL` and `EXPECT_CALL` have the same \"later statements take\nprecedence\" rule, but they don't interact. That is, `EXPECT_CALL`s have their\nown precedence order distinct from the `ON_CALL` precedence order.\n\n### Using Functions/Methods/Functors/Lambdas as Actions {#FunctionsAsActions}\n\nIf the built-in actions don't suit you, you can use an existing callable\n(function, `std::function`, method, functor, lambda) as an action.\n\n```cpp\nusing ::testing::_; using ::testing::Invoke;\n\nclass MockFoo : public Foo {\n public:\n  MOCK_METHOD(int, Sum, (int x, int y), (override));\n  MOCK_METHOD(bool, ComplexJob, (int x), (override));\n};\n\nint CalculateSum(int x, int y) { return x + y; }\nint Sum3(int x, int y, int z) { return x + y + z; }\n\nclass Helper {\n public:\n  bool ComplexJob(int x);\n};\n\n...\n  MockFoo foo;\n  Helper helper;\n  EXPECT_CALL(foo, Sum(_, _))\n      .WillOnce(&CalculateSum)\n      .WillRepeatedly(Invoke(NewPermanentCallback(Sum3, 1)));\n  EXPECT_CALL(foo, ComplexJob(_))\n      .WillOnce(Invoke(&helper, &Helper::ComplexJob))\n      .WillOnce([] { return true; })\n      .WillRepeatedly([](int x) { return x > 0; });\n\n  foo.Sum(5, 6);         // Invokes CalculateSum(5, 6).\n  foo.Sum(2, 3);         // Invokes Sum3(1, 2, 3).\n  foo.ComplexJob(10);    // Invokes helper.ComplexJob(10).\n  foo.ComplexJob(-1);    // Invokes the inline lambda.\n```\n\nThe only requirement is that the type of the function, etc must be *compatible*\nwith the signature of the mock function, meaning that the latter's arguments (if\nit takes any) can be implicitly converted to the corresponding arguments of the\nformer, and the former's return type can be implicitly converted to that of the\nlatter. So, you can invoke something whose type is *not* exactly the same as the\nmock function, as long as it's safe to do so - nice, huh?\n\nNote that:\n\n*   The action takes ownership of the callback and will delete it when the\n    action itself is destructed.\n*   If the type of a callback is derived from a base callback type `C`, you need\n    to implicitly cast it to `C` to resolve the overloading, e.g.\n\n    ```cpp\n    using ::testing::Invoke;\n    ...\n      ResultCallback<bool>* is_ok = ...;\n      ... Invoke(is_ok) ...;  // This works.\n\n      BlockingClosure* done = new BlockingClosure;\n      ... Invoke(implicit_cast<Closure*>(done)) ...;  // The cast is necessary.\n    ```\n\n### Using Functions with Extra Info as Actions\n\nThe function or functor you call using `Invoke()` must have the same number of\narguments as the mock function you use it for. Sometimes you may have a function\nthat takes more arguments, and you are willing to pass in the extra arguments\nyourself to fill the gap. You can do this in gMock using callbacks with\npre-bound arguments. Here's an example:\n\n```cpp\nusing ::testing::Invoke;\n\nclass MockFoo : public Foo {\n public:\n  MOCK_METHOD(char, DoThis, (int n), (override));\n};\n\nchar SignOfSum(int x, int y) {\n  const int sum = x + y;\n  return (sum > 0) ? '+' : (sum < 0) ? '-' : '0';\n}\n\nTEST_F(FooTest, Test) {\n  MockFoo foo;\n\n  EXPECT_CALL(foo, DoThis(2))\n      .WillOnce(Invoke(NewPermanentCallback(SignOfSum, 5)));\n  EXPECT_EQ('+', foo.DoThis(2));  // Invokes SignOfSum(5, 2).\n}\n```\n\n### Invoking a Function/Method/Functor/Lambda/Callback Without Arguments\n\n`Invoke()` passes the mock function's arguments to the function, etc being\ninvoked such that the callee has the full context of the call to work with. If\nthe invoked function is not interested in some or all of the arguments, it can\nsimply ignore them.\n\nYet, a common pattern is that a test author wants to invoke a function without\nthe arguments of the mock function. She could do that using a wrapper function\nthat throws away the arguments before invoking an underlining nullary function.\nNeedless to say, this can be tedious and obscures the intent of the test.\n\nThere are two solutions to this problem. First, you can pass any callable of\nzero args as an action. Alternatively, use `InvokeWithoutArgs()`, which is like\n`Invoke()` except that it doesn't pass the mock function's arguments to the\ncallee. Here's an example of each:\n\n```cpp\nusing ::testing::_;\nusing ::testing::InvokeWithoutArgs;\n\nclass MockFoo : public Foo {\n public:\n  MOCK_METHOD(bool, ComplexJob, (int n), (override));\n};\n\nbool Job1() { ... }\nbool Job2(int n, char c) { ... }\n\n...\n  MockFoo foo;\n  EXPECT_CALL(foo, ComplexJob(_))\n      .WillOnce([] { Job1(); });\n      .WillOnce(InvokeWithoutArgs(NewPermanentCallback(Job2, 5, 'a')));\n\n  foo.ComplexJob(10);  // Invokes Job1().\n  foo.ComplexJob(20);  // Invokes Job2(5, 'a').\n```\n\nNote that:\n\n*   The action takes ownership of the callback and will delete it when the\n    action itself is destructed.\n*   If the type of a callback is derived from a base callback type `C`, you need\n    to implicitly cast it to `C` to resolve the overloading, e.g.\n\n    ```cpp\n    using ::testing::InvokeWithoutArgs;\n    ...\n      ResultCallback<bool>* is_ok = ...;\n      ... InvokeWithoutArgs(is_ok) ...;  // This works.\n\n      BlockingClosure* done = ...;\n      ... InvokeWithoutArgs(implicit_cast<Closure*>(done)) ...;\n      // The cast is necessary.\n    ```\n\n### Invoking an Argument of the Mock Function\n\nSometimes a mock function will receive a function pointer, a functor (in other\nwords, a \"callable\") as an argument, e.g.\n\n```cpp\nclass MockFoo : public Foo {\n public:\n  MOCK_METHOD(bool, DoThis, (int n, (ResultCallback1<bool, int>* callback)),\n              (override));\n};\n```\n\nand you may want to invoke this callable argument:\n\n```cpp\nusing ::testing::_;\n...\n  MockFoo foo;\n  EXPECT_CALL(foo, DoThis(_, _))\n      .WillOnce(...);\n      // Will execute callback->Run(5), where callback is the\n      // second argument DoThis() receives.\n```\n\n{: .callout .note}\nNOTE: The section below is legacy documentation from before C++ had lambdas:\n\nArghh, you need to refer to a mock function argument but C++ has no lambda\n(yet), so you have to define your own action. :-( Or do you really?\n\nWell, gMock has an action to solve *exactly* this problem:\n\n```cpp\nInvokeArgument<N>(arg_1, arg_2, ..., arg_m)\n```\n\nwill invoke the `N`-th (0-based) argument the mock function receives, with\n`arg_1`, `arg_2`, ..., and `arg_m`. No matter if the argument is a function\npointer, a functor, or a callback. gMock handles them all.\n\nWith that, you could write:\n\n```cpp\nusing ::testing::_;\nusing ::testing::InvokeArgument;\n...\n  EXPECT_CALL(foo, DoThis(_, _))\n      .WillOnce(InvokeArgument<1>(5));\n      // Will execute callback->Run(5), where callback is the\n      // second argument DoThis() receives.\n```\n\nWhat if the callable takes an argument by reference? No problem - just wrap it\ninside `std::ref()`:\n\n```cpp\n  ...\n  MOCK_METHOD(bool, Bar,\n              ((ResultCallback2<bool, int, const Helper&>* callback)),\n              (override));\n  ...\n  using ::testing::_;\n  using ::testing::InvokeArgument;\n  ...\n  MockFoo foo;\n  Helper helper;\n  ...\n  EXPECT_CALL(foo, Bar(_))\n      .WillOnce(InvokeArgument<0>(5, std::ref(helper)));\n      // std::ref(helper) guarantees that a reference to helper, not a copy of\n      // it, will be passed to the callback.\n```\n\nWhat if the callable takes an argument by reference and we do **not** wrap the\nargument in `std::ref()`? Then `InvokeArgument()` will *make a copy* of the\nargument, and pass a *reference to the copy*, instead of a reference to the\noriginal value, to the callable. This is especially handy when the argument is a\ntemporary value:\n\n```cpp\n  ...\n  MOCK_METHOD(bool, DoThat, (bool (*f)(const double& x, const string& s)),\n              (override));\n  ...\n  using ::testing::_;\n  using ::testing::InvokeArgument;\n  ...\n  MockFoo foo;\n  ...\n  EXPECT_CALL(foo, DoThat(_))\n      .WillOnce(InvokeArgument<0>(5.0, string(\"Hi\")));\n      // Will execute (*f)(5.0, string(\"Hi\")), where f is the function pointer\n      // DoThat() receives.  Note that the values 5.0 and string(\"Hi\") are\n      // temporary and dead once the EXPECT_CALL() statement finishes.  Yet\n      // it's fine to perform this action later, since a copy of the values\n      // are kept inside the InvokeArgument action.\n```\n\n### Ignoring an Action's Result\n\nSometimes you have an action that returns *something*, but you need an action\nthat returns `void` (perhaps you want to use it in a mock function that returns\n`void`, or perhaps it needs to be used in `DoAll()` and it's not the last in the\nlist). `IgnoreResult()` lets you do that. For example:\n\n```cpp\nusing ::testing::_;\nusing ::testing::DoAll;\nusing ::testing::IgnoreResult;\nusing ::testing::Return;\n\nint Process(const MyData& data);\nstring DoSomething();\n\nclass MockFoo : public Foo {\n public:\n  MOCK_METHOD(void, Abc, (const MyData& data), (override));\n  MOCK_METHOD(bool, Xyz, (), (override));\n};\n\n  ...\n  MockFoo foo;\n  EXPECT_CALL(foo, Abc(_))\n      // .WillOnce(Invoke(Process));\n      // The above line won't compile as Process() returns int but Abc() needs\n      // to return void.\n      .WillOnce(IgnoreResult(Process));\n  EXPECT_CALL(foo, Xyz())\n      .WillOnce(DoAll(IgnoreResult(DoSomething),\n                      // Ignores the string DoSomething() returns.\n                      Return(true)));\n```\n\nNote that you **cannot** use `IgnoreResult()` on an action that already returns\n`void`. Doing so will lead to ugly compiler errors.\n\n### Selecting an Action's Arguments {#SelectingArgs}\n\nSay you have a mock function `Foo()` that takes seven arguments, and you have a\ncustom action that you want to invoke when `Foo()` is called. Trouble is, the\ncustom action only wants three arguments:\n\n```cpp\nusing ::testing::_;\nusing ::testing::Invoke;\n...\n  MOCK_METHOD(bool, Foo,\n              (bool visible, const string& name, int x, int y,\n               (const map<pair<int, int>>), double& weight, double min_weight,\n               double max_wight));\n...\nbool IsVisibleInQuadrant1(bool visible, int x, int y) {\n  return visible && x >= 0 && y >= 0;\n}\n...\n  EXPECT_CALL(mock, Foo)\n      .WillOnce(Invoke(IsVisibleInQuadrant1));  // Uh, won't compile. :-(\n```\n\nTo please the compiler God, you need to define an \"adaptor\" that has the same\nsignature as `Foo()` and calls the custom action with the right arguments:\n\n```cpp\nusing ::testing::_;\nusing ::testing::Invoke;\n...\nbool MyIsVisibleInQuadrant1(bool visible, const string& name, int x, int y,\n                            const map<pair<int, int>, double>& weight,\n                            double min_weight, double max_wight) {\n  return IsVisibleInQuadrant1(visible, x, y);\n}\n...\n  EXPECT_CALL(mock, Foo)\n      .WillOnce(Invoke(MyIsVisibleInQuadrant1));  // Now it works.\n```\n\nBut isn't this awkward?\n\ngMock provides a generic *action adaptor*, so you can spend your time minding\nmore important business than writing your own adaptors. Here's the syntax:\n\n```cpp\nWithArgs<N1, N2, ..., Nk>(action)\n```\n\ncreates an action that passes the arguments of the mock function at the given\nindices (0-based) to the inner `action` and performs it. Using `WithArgs`, our\noriginal example can be written as:\n\n```cpp\nusing ::testing::_;\nusing ::testing::Invoke;\nusing ::testing::WithArgs;\n...\n  EXPECT_CALL(mock, Foo)\n      .WillOnce(WithArgs<0, 2, 3>(Invoke(IsVisibleInQuadrant1)));  // No need to define your own adaptor.\n```\n\nFor better readability, gMock also gives you:\n\n*   `WithoutArgs(action)` when the inner `action` takes *no* argument, and\n*   `WithArg<N>(action)` (no `s` after `Arg`) when the inner `action` takes\n    *one* argument.\n\nAs you may have realized, `InvokeWithoutArgs(...)` is just syntactic sugar for\n`WithoutArgs(Invoke(...))`.\n\nHere are more tips:\n\n*   The inner action used in `WithArgs` and friends does not have to be\n    `Invoke()` -- it can be anything.\n*   You can repeat an argument in the argument list if necessary, e.g.\n    `WithArgs<2, 3, 3, 5>(...)`.\n*   You can change the order of the arguments, e.g. `WithArgs<3, 2, 1>(...)`.\n*   The types of the selected arguments do *not* have to match the signature of\n    the inner action exactly. It works as long as they can be implicitly\n    converted to the corresponding arguments of the inner action. For example,\n    if the 4-th argument of the mock function is an `int` and `my_action` takes\n    a `double`, `WithArg<4>(my_action)` will work.\n\n### Ignoring Arguments in Action Functions\n\nThe [selecting-an-action's-arguments](#SelectingArgs) recipe showed us one way\nto make a mock function and an action with incompatible argument lists fit\ntogether. The downside is that wrapping the action in `WithArgs<...>()` can get\ntedious for people writing the tests.\n\nIf you are defining a function (or method, functor, lambda, callback) to be used\nwith `Invoke*()`, and you are not interested in some of its arguments, an\nalternative to `WithArgs` is to declare the uninteresting arguments as `Unused`.\nThis makes the definition less cluttered and less fragile in case the types of\nthe uninteresting arguments change. It could also increase the chance the action\nfunction can be reused. For example, given\n\n```cpp\n public:\n  MOCK_METHOD(double, Foo, double(const string& label, double x, double y),\n              (override));\n  MOCK_METHOD(double, Bar, (int index, double x, double y), (override));\n```\n\ninstead of\n\n```cpp\nusing ::testing::_;\nusing ::testing::Invoke;\n\ndouble DistanceToOriginWithLabel(const string& label, double x, double y) {\n  return sqrt(x*x + y*y);\n}\ndouble DistanceToOriginWithIndex(int index, double x, double y) {\n  return sqrt(x*x + y*y);\n}\n...\n  EXPECT_CALL(mock, Foo(\"abc\", _, _))\n      .WillOnce(Invoke(DistanceToOriginWithLabel));\n  EXPECT_CALL(mock, Bar(5, _, _))\n      .WillOnce(Invoke(DistanceToOriginWithIndex));\n```\n\nyou could write\n\n```cpp\nusing ::testing::_;\nusing ::testing::Invoke;\nusing ::testing::Unused;\n\ndouble DistanceToOrigin(Unused, double x, double y) {\n  return sqrt(x*x + y*y);\n}\n...\n  EXPECT_CALL(mock, Foo(\"abc\", _, _))\n      .WillOnce(Invoke(DistanceToOrigin));\n  EXPECT_CALL(mock, Bar(5, _, _))\n      .WillOnce(Invoke(DistanceToOrigin));\n```\n\n### Sharing Actions\n\nJust like matchers, a gMock action object consists of a pointer to a ref-counted\nimplementation object. Therefore copying actions is also allowed and very\nefficient. When the last action that references the implementation object dies,\nthe implementation object will be deleted.\n\nIf you have some complex action that you want to use again and again, you may\nnot have to build it from scratch every time. If the action doesn't have an\ninternal state (i.e. if it always does the same thing no matter how many times\nit has been called), you can assign it to an action variable and use that\nvariable repeatedly. For example:\n\n```cpp\nusing ::testing::Action;\nusing ::testing::DoAll;\nusing ::testing::Return;\nusing ::testing::SetArgPointee;\n...\n  Action<bool(int*)> set_flag = DoAll(SetArgPointee<0>(5),\n                                      Return(true));\n  ... use set_flag in .WillOnce() and .WillRepeatedly() ...\n```\n\nHowever, if the action has its own state, you may be surprised if you share the\naction object. Suppose you have an action factory `IncrementCounter(init)` which\ncreates an action that increments and returns a counter whose initial value is\n`init`, using two actions created from the same expression and using a shared\naction will exhibit different behaviors. Example:\n\n```cpp\n  EXPECT_CALL(foo, DoThis())\n      .WillRepeatedly(IncrementCounter(0));\n  EXPECT_CALL(foo, DoThat())\n      .WillRepeatedly(IncrementCounter(0));\n  foo.DoThis();  // Returns 1.\n  foo.DoThis();  // Returns 2.\n  foo.DoThat();  // Returns 1 - Blah() uses a different\n                 // counter than Bar()'s.\n```\n\nversus\n\n```cpp\nusing ::testing::Action;\n...\n  Action<int()> increment = IncrementCounter(0);\n  EXPECT_CALL(foo, DoThis())\n      .WillRepeatedly(increment);\n  EXPECT_CALL(foo, DoThat())\n      .WillRepeatedly(increment);\n  foo.DoThis();  // Returns 1.\n  foo.DoThis();  // Returns 2.\n  foo.DoThat();  // Returns 3 - the counter is shared.\n```\n\n### Testing Asynchronous Behavior\n\nOne oft-encountered problem with gMock is that it can be hard to test\nasynchronous behavior. Suppose you had a `EventQueue` class that you wanted to\ntest, and you created a separate `EventDispatcher` interface so that you could\neasily mock it out. However, the implementation of the class fired all the\nevents on a background thread, which made test timings difficult. You could just\ninsert `sleep()` statements and hope for the best, but that makes your test\nbehavior nondeterministic. A better way is to use gMock actions and\n`Notification` objects to force your asynchronous test to behave synchronously.\n\n```cpp\nclass MockEventDispatcher : public EventDispatcher {\n  MOCK_METHOD(bool, DispatchEvent, (int32), (override));\n};\n\nTEST(EventQueueTest, EnqueueEventTest) {\n  MockEventDispatcher mock_event_dispatcher;\n  EventQueue event_queue(&mock_event_dispatcher);\n\n  const int32 kEventId = 321;\n  absl::Notification done;\n  EXPECT_CALL(mock_event_dispatcher, DispatchEvent(kEventId))\n      .WillOnce([&done] { done.Notify(); });\n\n  event_queue.EnqueueEvent(kEventId);\n  done.WaitForNotification();\n}\n```\n\nIn the example above, we set our normal gMock expectations, but then add an\nadditional action to notify the `Notification` object. Now we can just call\n`Notification::WaitForNotification()` in the main thread to wait for the\nasynchronous call to finish. After that, our test suite is complete and we can\nsafely exit.\n\n{: .callout .note}\nNote: this example has a downside: namely, if the expectation is not satisfied,\nour test will run forever. It will eventually time-out and fail, but it will\ntake longer and be slightly harder to debug. To alleviate this problem, you can\nuse `WaitForNotificationWithTimeout(ms)` instead of `WaitForNotification()`.\n\n## Misc Recipes on Using gMock\n\n### Mocking Methods That Use Move-Only Types\n\nC++11 introduced *move-only types*. A move-only-typed value can be moved from\none object to another, but cannot be copied. `std::unique_ptr<T>` is probably\nthe most commonly used move-only type.\n\nMocking a method that takes and/or returns move-only types presents some\nchallenges, but nothing insurmountable. This recipe shows you how you can do it.\nNote that the support for move-only method arguments was only introduced to\ngMock in April 2017; in older code, you may find more complex\n[workarounds](#LegacyMoveOnly) for lack of this feature.\n\nLet’s say we are working on a fictional project that lets one post and share\nsnippets called “buzzes”. Your code uses these types:\n\n```cpp\nenum class AccessLevel { kInternal, kPublic };\n\nclass Buzz {\n public:\n  explicit Buzz(AccessLevel access) { ... }\n  ...\n};\n\nclass Buzzer {\n public:\n  virtual ~Buzzer() {}\n  virtual std::unique_ptr<Buzz> MakeBuzz(StringPiece text) = 0;\n  virtual bool ShareBuzz(std::unique_ptr<Buzz> buzz, int64_t timestamp) = 0;\n  ...\n};\n```\n\nA `Buzz` object represents a snippet being posted. A class that implements the\n`Buzzer` interface is capable of creating and sharing `Buzz`es. Methods in\n`Buzzer` may return a `unique_ptr<Buzz>` or take a `unique_ptr<Buzz>`. Now we\nneed to mock `Buzzer` in our tests.\n\nTo mock a method that accepts or returns move-only types, you just use the\nfamiliar `MOCK_METHOD` syntax as usual:\n\n```cpp\nclass MockBuzzer : public Buzzer {\n public:\n  MOCK_METHOD(std::unique_ptr<Buzz>, MakeBuzz, (StringPiece text), (override));\n  MOCK_METHOD(bool, ShareBuzz, (std::unique_ptr<Buzz> buzz, int64_t timestamp),\n              (override));\n};\n```\n\nNow that we have the mock class defined, we can use it in tests. In the\nfollowing code examples, we assume that we have defined a `MockBuzzer` object\nnamed `mock_buzzer_`:\n\n```cpp\n  MockBuzzer mock_buzzer_;\n```\n\nFirst let’s see how we can set expectations on the `MakeBuzz()` method, which\nreturns a `unique_ptr<Buzz>`.\n\nAs usual, if you set an expectation without an action (i.e. the `.WillOnce()` or\n`.WillRepeatedly()` clause), when that expectation fires, the default action for\nthat method will be taken. Since `unique_ptr<>` has a default constructor that\nreturns a null `unique_ptr`, that’s what you’ll get if you don’t specify an\naction:\n\n```cpp\n  // Use the default action.\n  EXPECT_CALL(mock_buzzer_, MakeBuzz(\"hello\"));\n\n  // Triggers the previous EXPECT_CALL.\n  EXPECT_EQ(nullptr, mock_buzzer_.MakeBuzz(\"hello\"));\n```\n\nIf you are not happy with the default action, you can tweak it as usual; see\n[Setting Default Actions](#OnCall).\n\nIf you just need to return a pre-defined move-only value, you can use the\n`Return(ByMove(...))` action:\n\n```cpp\n  // When this fires, the unique_ptr<> specified by ByMove(...) will\n  // be returned.\n  EXPECT_CALL(mock_buzzer_, MakeBuzz(\"world\"))\n      .WillOnce(Return(ByMove(MakeUnique<Buzz>(AccessLevel::kInternal))));\n\n  EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz(\"world\"));\n```\n\nNote that `ByMove()` is essential here - if you drop it, the code won’t compile.\n\nQuiz time! What do you think will happen if a `Return(ByMove(...))` action is\nperformed more than once (e.g. you write `...\n.WillRepeatedly(Return(ByMove(...)));`)? Come think of it, after the first time\nthe action runs, the source value will be consumed (since it’s a move-only\nvalue), so the next time around, there’s no value to move from -- you’ll get a\nrun-time error that `Return(ByMove(...))` can only be run once.\n\nIf you need your mock method to do more than just moving a pre-defined value,\nremember that you can always use a lambda or a callable object, which can do\npretty much anything you want:\n\n```cpp\n  EXPECT_CALL(mock_buzzer_, MakeBuzz(\"x\"))\n      .WillRepeatedly([](StringPiece text) {\n        return MakeUnique<Buzz>(AccessLevel::kInternal);\n      });\n\n  EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz(\"x\"));\n  EXPECT_NE(nullptr, mock_buzzer_.MakeBuzz(\"x\"));\n```\n\nEvery time this `EXPECT_CALL` fires, a new `unique_ptr<Buzz>` will be created\nand returned. You cannot do this with `Return(ByMove(...))`.\n\nThat covers returning move-only values; but how do we work with methods\naccepting move-only arguments? The answer is that they work normally, although\nsome actions will not compile when any of method's arguments are move-only. You\ncan always use `Return`, or a [lambda or functor](#FunctionsAsActions):\n\n```cpp\n  using ::testing::Unused;\n\n  EXPECT_CALL(mock_buzzer_, ShareBuzz(NotNull(), _)).WillOnce(Return(true));\n  EXPECT_TRUE(mock_buzzer_.ShareBuzz(MakeUnique<Buzz>(AccessLevel::kInternal)),\n              0);\n\n  EXPECT_CALL(mock_buzzer_, ShareBuzz(_, _)).WillOnce(\n      [](std::unique_ptr<Buzz> buzz, Unused) { return buzz != nullptr; });\n  EXPECT_FALSE(mock_buzzer_.ShareBuzz(nullptr, 0));\n```\n\nMany built-in actions (`WithArgs`, `WithoutArgs`,`DeleteArg`, `SaveArg`, ...)\ncould in principle support move-only arguments, but the support for this is not\nimplemented yet. If this is blocking you, please file a bug.\n\nA few actions (e.g. `DoAll`) copy their arguments internally, so they can never\nwork with non-copyable objects; you'll have to use functors instead.\n\n#### Legacy workarounds for move-only types {#LegacyMoveOnly}\n\nSupport for move-only function arguments was only introduced to gMock in April\nof 2017. In older code, you may encounter the following workaround for the lack\nof this feature (it is no longer necessary - we're including it just for\nreference):\n\n```cpp\nclass MockBuzzer : public Buzzer {\n public:\n  MOCK_METHOD(bool, DoShareBuzz, (Buzz* buzz, Time timestamp));\n  bool ShareBuzz(std::unique_ptr<Buzz> buzz, Time timestamp) override {\n    return DoShareBuzz(buzz.get(), timestamp);\n  }\n};\n```\n\nThe trick is to delegate the `ShareBuzz()` method to a mock method (let’s call\nit `DoShareBuzz()`) that does not take move-only parameters. Then, instead of\nsetting expectations on `ShareBuzz()`, you set them on the `DoShareBuzz()` mock\nmethod:\n\n```cpp\n  MockBuzzer mock_buzzer_;\n  EXPECT_CALL(mock_buzzer_, DoShareBuzz(NotNull(), _));\n\n  // When one calls ShareBuzz() on the MockBuzzer like this, the call is\n  // forwarded to DoShareBuzz(), which is mocked.  Therefore this statement\n  // will trigger the above EXPECT_CALL.\n  mock_buzzer_.ShareBuzz(MakeUnique<Buzz>(AccessLevel::kInternal), 0);\n```\n\n### Making the Compilation Faster\n\nBelieve it or not, the *vast majority* of the time spent on compiling a mock\nclass is in generating its constructor and destructor, as they perform\nnon-trivial tasks (e.g. verification of the expectations). What's more, mock\nmethods with different signatures have different types and thus their\nconstructors/destructors need to be generated by the compiler separately. As a\nresult, if you mock many different types of methods, compiling your mock class\ncan get really slow.\n\nIf you are experiencing slow compilation, you can move the definition of your\nmock class' constructor and destructor out of the class body and into a `.cc`\nfile. This way, even if you `#include` your mock class in N files, the compiler\nonly needs to generate its constructor and destructor once, resulting in a much\nfaster compilation.\n\nLet's illustrate the idea using an example. Here's the definition of a mock\nclass before applying this recipe:\n\n```cpp\n// File mock_foo.h.\n...\nclass MockFoo : public Foo {\n public:\n  // Since we don't declare the constructor or the destructor,\n  // the compiler will generate them in every translation unit\n  // where this mock class is used.\n\n  MOCK_METHOD(int, DoThis, (), (override));\n  MOCK_METHOD(bool, DoThat, (const char* str), (override));\n  ... more mock methods ...\n};\n```\n\nAfter the change, it would look like:\n\n```cpp\n// File mock_foo.h.\n...\nclass MockFoo : public Foo {\n public:\n  // The constructor and destructor are declared, but not defined, here.\n  MockFoo();\n  virtual ~MockFoo();\n\n  MOCK_METHOD(int, DoThis, (), (override));\n  MOCK_METHOD(bool, DoThat, (const char* str), (override));\n  ... more mock methods ...\n};\n```\n\nand\n\n```cpp\n// File mock_foo.cc.\n#include \"path/to/mock_foo.h\"\n\n// The definitions may appear trivial, but the functions actually do a\n// lot of things through the constructors/destructors of the member\n// variables used to implement the mock methods.\nMockFoo::MockFoo() {}\nMockFoo::~MockFoo() {}\n```\n\n### Forcing a Verification\n\nWhen it's being destroyed, your friendly mock object will automatically verify\nthat all expectations on it have been satisfied, and will generate googletest\nfailures if not. This is convenient as it leaves you with one less thing to\nworry about. That is, unless you are not sure if your mock object will be\ndestroyed.\n\nHow could it be that your mock object won't eventually be destroyed? Well, it\nmight be created on the heap and owned by the code you are testing. Suppose\nthere's a bug in that code and it doesn't delete the mock object properly - you\ncould end up with a passing test when there's actually a bug.\n\nUsing a heap checker is a good idea and can alleviate the concern, but its\nimplementation is not 100% reliable. So, sometimes you do want to *force* gMock\nto verify a mock object before it is (hopefully) destructed. You can do this\nwith `Mock::VerifyAndClearExpectations(&mock_object)`:\n\n```cpp\nTEST(MyServerTest, ProcessesRequest) {\n  using ::testing::Mock;\n\n  MockFoo* const foo = new MockFoo;\n  EXPECT_CALL(*foo, ...)...;\n  // ... other expectations ...\n\n  // server now owns foo.\n  MyServer server(foo);\n  server.ProcessRequest(...);\n\n  // In case that server's destructor will forget to delete foo,\n  // this will verify the expectations anyway.\n  Mock::VerifyAndClearExpectations(foo);\n}  // server is destroyed when it goes out of scope here.\n```\n\n{: .callout .tip}\n**Tip:** The `Mock::VerifyAndClearExpectations()` function returns a `bool` to\nindicate whether the verification was successful (`true` for yes), so you can\nwrap that function call inside a `ASSERT_TRUE()` if there is no point going\nfurther when the verification has failed.\n\nDo not set new expectations after verifying and clearing a mock after its use.\nSetting expectations after code that exercises the mock has undefined behavior.\nSee [Using Mocks in Tests](gmock_for_dummies.md#using-mocks-in-tests) for more\ninformation.\n\n### Using Checkpoints {#UsingCheckPoints}\n\nSometimes you might want to test a mock object's behavior in phases whose sizes\nare each manageable, or you might want to set more detailed expectations about\nwhich API calls invoke which mock functions.\n\nA technique you can use is to put the expectations in a sequence and insert\ncalls to a dummy \"checkpoint\" function at specific places. Then you can verify\nthat the mock function calls do happen at the right time. For example, if you\nare exercising the code:\n\n```cpp\n  Foo(1);\n  Foo(2);\n  Foo(3);\n```\n\nand want to verify that `Foo(1)` and `Foo(3)` both invoke `mock.Bar(\"a\")`, but\n`Foo(2)` doesn't invoke anything, you can write:\n\n```cpp\nusing ::testing::MockFunction;\n\nTEST(FooTest, InvokesBarCorrectly) {\n  MyMock mock;\n  // Class MockFunction<F> has exactly one mock method.  It is named\n  // Call() and has type F.\n  MockFunction<void(string check_point_name)> check;\n  {\n    InSequence s;\n\n    EXPECT_CALL(mock, Bar(\"a\"));\n    EXPECT_CALL(check, Call(\"1\"));\n    EXPECT_CALL(check, Call(\"2\"));\n    EXPECT_CALL(mock, Bar(\"a\"));\n  }\n  Foo(1);\n  check.Call(\"1\");\n  Foo(2);\n  check.Call(\"2\");\n  Foo(3);\n}\n```\n\nThe expectation spec says that the first `Bar(\"a\")` call must happen before\ncheckpoint \"1\", the second `Bar(\"a\")` call must happen after checkpoint \"2\", and\nnothing should happen between the two checkpoints. The explicit checkpoints make\nit clear which `Bar(\"a\")` is called by which call to `Foo()`.\n\n### Mocking Destructors\n\nSometimes you want to make sure a mock object is destructed at the right time,\ne.g. after `bar->A()` is called but before `bar->B()` is called. We already know\nthat you can specify constraints on the [order](#OrderedCalls) of mock function\ncalls, so all we need to do is to mock the destructor of the mock function.\n\nThis sounds simple, except for one problem: a destructor is a special function\nwith special syntax and special semantics, and the `MOCK_METHOD` macro doesn't\nwork for it:\n\n```cpp\nMOCK_METHOD(void, ~MockFoo, ());  // Won't compile!\n```\n\nThe good news is that you can use a simple pattern to achieve the same effect.\nFirst, add a mock function `Die()` to your mock class and call it in the\ndestructor, like this:\n\n```cpp\nclass MockFoo : public Foo {\n  ...\n  // Add the following two lines to the mock class.\n  MOCK_METHOD(void, Die, ());\n  ~MockFoo() override { Die(); }\n};\n```\n\n(If the name `Die()` clashes with an existing symbol, choose another name.) Now,\nwe have translated the problem of testing when a `MockFoo` object dies to\ntesting when its `Die()` method is called:\n\n```cpp\n  MockFoo* foo = new MockFoo;\n  MockBar* bar = new MockBar;\n  ...\n  {\n    InSequence s;\n\n    // Expects *foo to die after bar->A() and before bar->B().\n    EXPECT_CALL(*bar, A());\n    EXPECT_CALL(*foo, Die());\n    EXPECT_CALL(*bar, B());\n  }\n```\n\nAnd that's that.\n\n### Using gMock and Threads {#UsingThreads}\n\nIn a **unit** test, it's best if you could isolate and test a piece of code in a\nsingle-threaded context. That avoids race conditions and dead locks, and makes\ndebugging your test much easier.\n\nYet most programs are multi-threaded, and sometimes to test something we need to\npound on it from more than one thread. gMock works for this purpose too.\n\nRemember the steps for using a mock:\n\n1.  Create a mock object `foo`.\n2.  Set its default actions and expectations using `ON_CALL()` and\n    `EXPECT_CALL()`.\n3.  The code under test calls methods of `foo`.\n4.  Optionally, verify and reset the mock.\n5.  Destroy the mock yourself, or let the code under test destroy it. The\n    destructor will automatically verify it.\n\nIf you follow the following simple rules, your mocks and threads can live\nhappily together:\n\n*   Execute your *test code* (as opposed to the code being tested) in *one*\n    thread. This makes your test easy to follow.\n*   Obviously, you can do step #1 without locking.\n*   When doing step #2 and #5, make sure no other thread is accessing `foo`.\n    Obvious too, huh?\n*   #3 and #4 can be done either in one thread or in multiple threads - anyway\n    you want. gMock takes care of the locking, so you don't have to do any -\n    unless required by your test logic.\n\nIf you violate the rules (for example, if you set expectations on a mock while\nanother thread is calling its methods), you get undefined behavior. That's not\nfun, so don't do it.\n\ngMock guarantees that the action for a mock function is done in the same thread\nthat called the mock function. For example, in\n\n```cpp\n  EXPECT_CALL(mock, Foo(1))\n      .WillOnce(action1);\n  EXPECT_CALL(mock, Foo(2))\n      .WillOnce(action2);\n```\n\nif `Foo(1)` is called in thread 1 and `Foo(2)` is called in thread 2, gMock will\nexecute `action1` in thread 1 and `action2` in thread 2.\n\ngMock does *not* impose a sequence on actions performed in different threads\n(doing so may create deadlocks as the actions may need to cooperate). This means\nthat the execution of `action1` and `action2` in the above example *may*\ninterleave. If this is a problem, you should add proper synchronization logic to\n`action1` and `action2` to make the test thread-safe.\n\nAlso, remember that `DefaultValue<T>` is a global resource that potentially\naffects *all* living mock objects in your program. Naturally, you won't want to\nmess with it from multiple threads or when there still are mocks in action.\n\n### Controlling How Much Information gMock Prints\n\nWhen gMock sees something that has the potential of being an error (e.g. a mock\nfunction with no expectation is called, a.k.a. an uninteresting call, which is\nallowed but perhaps you forgot to explicitly ban the call), it prints some\nwarning messages, including the arguments of the function, the return value, and\nthe stack trace. Hopefully this will remind you to take a look and see if there\nis indeed a problem.\n\nSometimes you are confident that your tests are correct and may not appreciate\nsuch friendly messages. Some other times, you are debugging your tests or\nlearning about the behavior of the code you are testing, and wish you could\nobserve every mock call that happens (including argument values, the return\nvalue, and the stack trace). Clearly, one size doesn't fit all.\n\nYou can control how much gMock tells you using the `--gmock_verbose=LEVEL`\ncommand-line flag, where `LEVEL` is a string with three possible values:\n\n*   `info`: gMock will print all informational messages, warnings, and errors\n    (most verbose). At this setting, gMock will also log any calls to the\n    `ON_CALL/EXPECT_CALL` macros. It will include a stack trace in\n    \"uninteresting call\" warnings.\n*   `warning`: gMock will print both warnings and errors (less verbose); it will\n    omit the stack traces in \"uninteresting call\" warnings. This is the default.\n*   `error`: gMock will print errors only (least verbose).\n\nAlternatively, you can adjust the value of that flag from within your tests like\nso:\n\n```cpp\n  ::testing::FLAGS_gmock_verbose = \"error\";\n```\n\nIf you find gMock printing too many stack frames with its informational or\nwarning messages, remember that you can control their amount with the\n`--gtest_stack_trace_depth=max_depth` flag.\n\nNow, judiciously use the right flag to enable gMock serve you better!\n\n### Gaining Super Vision into Mock Calls\n\nYou have a test using gMock. It fails: gMock tells you some expectations aren't\nsatisfied. However, you aren't sure why: Is there a typo somewhere in the\nmatchers? Did you mess up the order of the `EXPECT_CALL`s? Or is the code under\ntest doing something wrong? How can you find out the cause?\n\nWon't it be nice if you have X-ray vision and can actually see the trace of all\n`EXPECT_CALL`s and mock method calls as they are made? For each call, would you\nlike to see its actual argument values and which `EXPECT_CALL` gMock thinks it\nmatches? If you still need some help to figure out who made these calls, how\nabout being able to see the complete stack trace at each mock call?\n\nYou can unlock this power by running your test with the `--gmock_verbose=info`\nflag. For example, given the test program:\n\n```cpp\n#include \"gmock/gmock.h\"\n\nusing testing::_;\nusing testing::HasSubstr;\nusing testing::Return;\n\nclass MockFoo {\n public:\n  MOCK_METHOD(void, F, (const string& x, const string& y));\n};\n\nTEST(Foo, Bar) {\n  MockFoo mock;\n  EXPECT_CALL(mock, F(_, _)).WillRepeatedly(Return());\n  EXPECT_CALL(mock, F(\"a\", \"b\"));\n  EXPECT_CALL(mock, F(\"c\", HasSubstr(\"d\")));\n\n  mock.F(\"a\", \"good\");\n  mock.F(\"a\", \"b\");\n}\n```\n\nif you run it with `--gmock_verbose=info`, you will see this output:\n\n```shell\n[ RUN       ] Foo.Bar\n\nfoo_test.cc:14: EXPECT_CALL(mock, F(_, _)) invoked\nStack trace: ...\n\nfoo_test.cc:15: EXPECT_CALL(mock, F(\"a\", \"b\")) invoked\nStack trace: ...\n\nfoo_test.cc:16: EXPECT_CALL(mock, F(\"c\", HasSubstr(\"d\"))) invoked\nStack trace: ...\n\nfoo_test.cc:14: Mock function call matches EXPECT_CALL(mock, F(_, _))...\n    Function call: F(@0x7fff7c8dad40\"a\",@0x7fff7c8dad10\"good\")\nStack trace: ...\n\nfoo_test.cc:15: Mock function call matches EXPECT_CALL(mock, F(\"a\", \"b\"))...\n    Function call: F(@0x7fff7c8dada0\"a\",@0x7fff7c8dad70\"b\")\nStack trace: ...\n\nfoo_test.cc:16: Failure\nActual function call count doesn't match EXPECT_CALL(mock, F(\"c\", HasSubstr(\"d\")))...\n         Expected: to be called once\n           Actual: never called - unsatisfied and active\n[  FAILED  ] Foo.Bar\n```\n\nSuppose the bug is that the `\"c\"` in the third `EXPECT_CALL` is a typo and\nshould actually be `\"a\"`. With the above message, you should see that the actual\n`F(\"a\", \"good\")` call is matched by the first `EXPECT_CALL`, not the third as\nyou thought. From that it should be obvious that the third `EXPECT_CALL` is\nwritten wrong. Case solved.\n\nIf you are interested in the mock call trace but not the stack traces, you can\ncombine `--gmock_verbose=info` with `--gtest_stack_trace_depth=0` on the test\ncommand line.\n\n### Running Tests in Emacs\n\nIf you build and run your tests in Emacs using the `M-x google-compile` command\n(as many googletest users do), the source file locations of gMock and googletest\nerrors will be highlighted. Just press `<Enter>` on one of them and you'll be\ntaken to the offending line. Or, you can just type `C-x`` to jump to the next\nerror.\n\nTo make it even easier, you can add the following lines to your `~/.emacs` file:\n\n```text\n(global-set-key \"\\M-m\"  'google-compile)  ; m is for make\n(global-set-key [M-down] 'next-error)\n(global-set-key [M-up]  '(lambda () (interactive) (next-error -1)))\n```\n\nThen you can type `M-m` to start a build (if you want to run the test as well,\njust make sure `foo_test.run` or `runtests` is in the build command you supply\nafter typing `M-m`), or `M-up`/`M-down` to move back and forth between errors.\n\n## Extending gMock\n\n### Writing New Matchers Quickly {#NewMatchers}\n\n{: .callout .warning}\nWARNING: gMock does not guarantee when or how many times a matcher will be\ninvoked. Therefore, all matchers must be functionally pure. See\n[this section](#PureMatchers) for more details.\n\nThe `MATCHER*` family of macros can be used to define custom matchers easily.\nThe syntax:\n\n```cpp\nMATCHER(name, description_string_expression) { statements; }\n```\n\nwill define a matcher with the given name that executes the statements, which\nmust return a `bool` to indicate if the match succeeds. Inside the statements,\nyou can refer to the value being matched by `arg`, and refer to its type by\n`arg_type`.\n\nThe *description string* is a `string`-typed expression that documents what the\nmatcher does, and is used to generate the failure message when the match fails.\nIt can (and should) reference the special `bool` variable `negation`, and should\nevaluate to the description of the matcher when `negation` is `false`, or that\nof the matcher's negation when `negation` is `true`.\n\nFor convenience, we allow the description string to be empty (`\"\"`), in which\ncase gMock will use the sequence of words in the matcher name as the\ndescription.\n\nFor example:\n\n```cpp\nMATCHER(IsDivisibleBy7, \"\") { return (arg % 7) == 0; }\n```\n\nallows you to write\n\n```cpp\n  // Expects mock_foo.Bar(n) to be called where n is divisible by 7.\n  EXPECT_CALL(mock_foo, Bar(IsDivisibleBy7()));\n```\n\nor,\n\n```cpp\n  using ::testing::Not;\n  ...\n  // Verifies that a value is divisible by 7 and the other is not.\n  EXPECT_THAT(some_expression, IsDivisibleBy7());\n  EXPECT_THAT(some_other_expression, Not(IsDivisibleBy7()));\n```\n\nIf the above assertions fail, they will print something like:\n\n```shell\n  Value of: some_expression\n  Expected: is divisible by 7\n    Actual: 27\n  ...\n  Value of: some_other_expression\n  Expected: not (is divisible by 7)\n    Actual: 21\n```\n\nwhere the descriptions `\"is divisible by 7\"` and `\"not (is divisible by 7)\"` are\nautomatically calculated from the matcher name `IsDivisibleBy7`.\n\nAs you may have noticed, the auto-generated descriptions (especially those for\nthe negation) may not be so great. You can always override them with a `string`\nexpression of your own:\n\n```cpp\nMATCHER(IsDivisibleBy7,\n        absl::StrCat(negation ? \"isn't\" : \"is\", \" divisible by 7\")) {\n  return (arg % 7) == 0;\n}\n```\n\nOptionally, you can stream additional information to a hidden argument named\n`result_listener` to explain the match result. For example, a better definition\nof `IsDivisibleBy7` is:\n\n```cpp\nMATCHER(IsDivisibleBy7, \"\") {\n  if ((arg % 7) == 0)\n    return true;\n\n  *result_listener << \"the remainder is \" << (arg % 7);\n  return false;\n}\n```\n\nWith this definition, the above assertion will give a better message:\n\n```shell\n  Value of: some_expression\n  Expected: is divisible by 7\n    Actual: 27 (the remainder is 6)\n```\n\nYou should let `MatchAndExplain()` print *any additional information* that can\nhelp a user understand the match result. Note that it should explain why the\nmatch succeeds in case of a success (unless it's obvious) - this is useful when\nthe matcher is used inside `Not()`. There is no need to print the argument value\nitself, as gMock already prints it for you.\n\n{: .callout .note}\nNOTE: The type of the value being matched (`arg_type`) is determined by the\ncontext in which you use the matcher and is supplied to you by the compiler, so\nyou don't need to worry about declaring it (nor can you). This allows the\nmatcher to be polymorphic. For example, `IsDivisibleBy7()` can be used to match\nany type where the value of `(arg % 7) == 0` can be implicitly converted to a\n`bool`. In the `Bar(IsDivisibleBy7())` example above, if method `Bar()` takes an\n`int`, `arg_type` will be `int`; if it takes an `unsigned long`, `arg_type` will\nbe `unsigned long`; and so on.\n\n### Writing New Parameterized Matchers Quickly\n\nSometimes you'll want to define a matcher that has parameters. For that you can\nuse the macro:\n\n```cpp\nMATCHER_P(name, param_name, description_string) { statements; }\n```\n\nwhere the description string can be either `\"\"` or a `string` expression that\nreferences `negation` and `param_name`.\n\nFor example:\n\n```cpp\nMATCHER_P(HasAbsoluteValue, value, \"\") { return abs(arg) == value; }\n```\n\nwill allow you to write:\n\n```cpp\n  EXPECT_THAT(Blah(\"a\"), HasAbsoluteValue(n));\n```\n\nwhich may lead to this message (assuming `n` is 10):\n\n```shell\n  Value of: Blah(\"a\")\n  Expected: has absolute value 10\n    Actual: -9\n```\n\nNote that both the matcher description and its parameter are printed, making the\nmessage human-friendly.\n\nIn the matcher definition body, you can write `foo_type` to reference the type\nof a parameter named `foo`. For example, in the body of\n`MATCHER_P(HasAbsoluteValue, value)` above, you can write `value_type` to refer\nto the type of `value`.\n\ngMock also provides `MATCHER_P2`, `MATCHER_P3`, ..., up to `MATCHER_P10` to\nsupport multi-parameter matchers:\n\n```cpp\nMATCHER_Pk(name, param_1, ..., param_k, description_string) { statements; }\n```\n\nPlease note that the custom description string is for a particular *instance* of\nthe matcher, where the parameters have been bound to actual values. Therefore\nusually you'll want the parameter values to be part of the description. gMock\nlets you do that by referencing the matcher parameters in the description string\nexpression.\n\nFor example,\n\n```cpp\nusing ::testing::PrintToString;\nMATCHER_P2(InClosedRange, low, hi,\n           absl::StrFormat(\"%s in range [%s, %s]\", negation ? \"isn't\" : \"is\",\n                           PrintToString(low), PrintToString(hi))) {\n  return low <= arg && arg <= hi;\n}\n...\nEXPECT_THAT(3, InClosedRange(4, 6));\n```\n\nwould generate a failure that contains the message:\n\n```shell\n  Expected: is in range [4, 6]\n```\n\nIf you specify `\"\"` as the description, the failure message will contain the\nsequence of words in the matcher name followed by the parameter values printed\nas a tuple. For example,\n\n```cpp\n  MATCHER_P2(InClosedRange, low, hi, \"\") { ... }\n  ...\n  EXPECT_THAT(3, InClosedRange(4, 6));\n```\n\nwould generate a failure that contains the text:\n\n```shell\n  Expected: in closed range (4, 6)\n```\n\nFor the purpose of typing, you can view\n\n```cpp\nMATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }\n```\n\nas shorthand for\n\n```cpp\ntemplate <typename p1_type, ..., typename pk_type>\nFooMatcherPk<p1_type, ..., pk_type>\nFoo(p1_type p1, ..., pk_type pk) { ... }\n```\n\nWhen you write `Foo(v1, ..., vk)`, the compiler infers the types of the\nparameters `v1`, ..., and `vk` for you. If you are not happy with the result of\nthe type inference, you can specify the types by explicitly instantiating the\ntemplate, as in `Foo<long, bool>(5, false)`. As said earlier, you don't get to\n(or need to) specify `arg_type` as that's determined by the context in which the\nmatcher is used.\n\nYou can assign the result of expression `Foo(p1, ..., pk)` to a variable of type\n`FooMatcherPk<p1_type, ..., pk_type>`. This can be useful when composing\nmatchers. Matchers that don't have a parameter or have only one parameter have\nspecial types: you can assign `Foo()` to a `FooMatcher`-typed variable, and\nassign `Foo(p)` to a `FooMatcherP<p_type>`-typed variable.\n\nWhile you can instantiate a matcher template with reference types, passing the\nparameters by pointer usually makes your code more readable. If, however, you\nstill want to pass a parameter by reference, be aware that in the failure\nmessage generated by the matcher you will see the value of the referenced object\nbut not its address.\n\nYou can overload matchers with different numbers of parameters:\n\n```cpp\nMATCHER_P(Blah, a, description_string_1) { ... }\nMATCHER_P2(Blah, a, b, description_string_2) { ... }\n```\n\nWhile it's tempting to always use the `MATCHER*` macros when defining a new\nmatcher, you should also consider implementing the matcher interface directly\ninstead (see the recipes that follow), especially if you need to use the matcher\na lot. While these approaches require more work, they give you more control on\nthe types of the value being matched and the matcher parameters, which in\ngeneral leads to better compiler error messages that pay off in the long run.\nThey also allow overloading matchers based on parameter types (as opposed to\njust based on the number of parameters).\n\n### Writing New Monomorphic Matchers\n\nA matcher of argument type `T` implements the matcher interface for `T` and does\ntwo things: it tests whether a value of type `T` matches the matcher, and can\ndescribe what kind of values it matches. The latter ability is used for\ngenerating readable error messages when expectations are violated.\n\nA matcher of `T` must declare a typedef like:\n\n```cpp\nusing is_gtest_matcher = void;\n```\n\nand supports the following operations:\n\n```cpp\n// Match a value and optionally explain into an ostream.\nbool matched = matcher.MatchAndExplain(value, maybe_os);\n// where `value` is of type `T` and\n// `maybe_os` is of type `std::ostream*`, where it can be null if the caller\n// is not interested in there textual explanation.\n\nmatcher.DescribeTo(os);\nmatcher.DescribeNegationTo(os);\n// where `os` is of type `std::ostream*`.\n```\n\nIf you need a custom matcher but `Truly()` is not a good option (for example,\nyou may not be happy with the way `Truly(predicate)` describes itself, or you\nmay want your matcher to be polymorphic as `Eq(value)` is), you can define a\nmatcher to do whatever you want in two steps: first implement the matcher\ninterface, and then define a factory function to create a matcher instance. The\nsecond step is not strictly needed but it makes the syntax of using the matcher\nnicer.\n\nFor example, you can define a matcher to test whether an `int` is divisible by 7\nand then use it like this:\n\n```cpp\nusing ::testing::Matcher;\n\nclass DivisibleBy7Matcher {\n public:\n  using is_gtest_matcher = void;\n\n  bool MatchAndExplain(int n, std::ostream*) const {\n    return (n % 7) == 0;\n  }\n\n  void DescribeTo(std::ostream* os) const {\n    *os << \"is divisible by 7\";\n  }\n\n  void DescribeNegationTo(std::ostream* os) const {\n    *os << \"is not divisible by 7\";\n  }\n};\n\nMatcher<int> DivisibleBy7() {\n  return DivisibleBy7Matcher();\n}\n\n...\n  EXPECT_CALL(foo, Bar(DivisibleBy7()));\n```\n\nYou may improve the matcher message by streaming additional information to the\n`os` argument in `MatchAndExplain()`:\n\n```cpp\nclass DivisibleBy7Matcher {\n public:\n  bool MatchAndExplain(int n, std::ostream* os) const {\n    const int remainder = n % 7;\n    if (remainder != 0 && os != nullptr) {\n      *os << \"the remainder is \" << remainder;\n    }\n    return remainder == 0;\n  }\n  ...\n};\n```\n\nThen, `EXPECT_THAT(x, DivisibleBy7());` may generate a message like this:\n\n```shell\nValue of: x\nExpected: is divisible by 7\n  Actual: 23 (the remainder is 2)\n```\n\n{: .callout .tip}\nTip: for convenience, `MatchAndExplain()` can take a `MatchResultListener*`\ninstead of `std::ostream*`.\n\n### Writing New Polymorphic Matchers\n\nExpanding what we learned above to *polymorphic* matchers is now just as simple\nas adding templates in the right place.\n\n```cpp\n\nclass NotNullMatcher {\n public:\n  using is_gtest_matcher = void;\n\n  // To implement a polymorphic matcher, we just need to make MatchAndExplain a\n  // template on its first argument.\n\n  // In this example, we want to use NotNull() with any pointer, so\n  // MatchAndExplain() accepts a pointer of any type as its first argument.\n  // In general, you can define MatchAndExplain() as an ordinary method or\n  // a method template, or even overload it.\n  template <typename T>\n  bool MatchAndExplain(T* p, std::ostream*) const {\n    return p != nullptr;\n  }\n\n  // Describes the property of a value matching this matcher.\n  void DescribeTo(std::ostream* os) const { *os << \"is not NULL\"; }\n\n  // Describes the property of a value NOT matching this matcher.\n  void DescribeNegationTo(std::ostream* os) const { *os << \"is NULL\"; }\n};\n\nNotNullMatcher NotNull() {\n  return NotNullMatcher();\n}\n\n...\n\n  EXPECT_CALL(foo, Bar(NotNull()));  // The argument must be a non-NULL pointer.\n```\n\n### Legacy Matcher Implementation\n\nDefining matchers used to be somewhat more complicated, in which it required\nseveral supporting classes and virtual functions. To implement a matcher for\ntype `T` using the legacy API you have to derive from `MatcherInterface<T>` and\ncall `MakeMatcher` to construct the object.\n\nThe interface looks like this:\n\n```cpp\nclass MatchResultListener {\n public:\n  ...\n  // Streams x to the underlying ostream; does nothing if the ostream\n  // is NULL.\n  template <typename T>\n  MatchResultListener& operator<<(const T& x);\n\n  // Returns the underlying ostream.\n  std::ostream* stream();\n};\n\ntemplate <typename T>\nclass MatcherInterface {\n public:\n  virtual ~MatcherInterface();\n\n  // Returns true if and only if the matcher matches x; also explains the match\n  // result to 'listener'.\n  virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;\n\n  // Describes this matcher to an ostream.\n  virtual void DescribeTo(std::ostream* os) const = 0;\n\n  // Describes the negation of this matcher to an ostream.\n  virtual void DescribeNegationTo(std::ostream* os) const;\n};\n```\n\nFortunately, most of the time you can define a polymorphic matcher easily with\nthe help of `MakePolymorphicMatcher()`. Here's how you can define `NotNull()` as\nan example:\n\n```cpp\nusing ::testing::MakePolymorphicMatcher;\nusing ::testing::MatchResultListener;\nusing ::testing::PolymorphicMatcher;\n\nclass NotNullMatcher {\n public:\n  // To implement a polymorphic matcher, first define a COPYABLE class\n  // that has three members MatchAndExplain(), DescribeTo(), and\n  // DescribeNegationTo(), like the following.\n\n  // In this example, we want to use NotNull() with any pointer, so\n  // MatchAndExplain() accepts a pointer of any type as its first argument.\n  // In general, you can define MatchAndExplain() as an ordinary method or\n  // a method template, or even overload it.\n  template <typename T>\n  bool MatchAndExplain(T* p,\n                       MatchResultListener* /* listener */) const {\n    return p != NULL;\n  }\n\n  // Describes the property of a value matching this matcher.\n  void DescribeTo(std::ostream* os) const { *os << \"is not NULL\"; }\n\n  // Describes the property of a value NOT matching this matcher.\n  void DescribeNegationTo(std::ostream* os) const { *os << \"is NULL\"; }\n};\n\n// To construct a polymorphic matcher, pass an instance of the class\n// to MakePolymorphicMatcher().  Note the return type.\nPolymorphicMatcher<NotNullMatcher> NotNull() {\n  return MakePolymorphicMatcher(NotNullMatcher());\n}\n\n...\n\n  EXPECT_CALL(foo, Bar(NotNull()));  // The argument must be a non-NULL pointer.\n```\n\n{: .callout .note}\n**Note:** Your polymorphic matcher class does **not** need to inherit from\n`MatcherInterface` or any other class, and its methods do **not** need to be\nvirtual.\n\nLike in a monomorphic matcher, you may explain the match result by streaming\nadditional information to the `listener` argument in `MatchAndExplain()`.\n\n### Writing New Cardinalities\n\nA cardinality is used in `Times()` to tell gMock how many times you expect a\ncall to occur. It doesn't have to be exact. For example, you can say\n`AtLeast(5)` or `Between(2, 4)`.\n\nIf the [built-in set](gmock_cheat_sheet.md#CardinalityList) of cardinalities\ndoesn't suit you, you are free to define your own by implementing the following\ninterface (in namespace `testing`):\n\n```cpp\nclass CardinalityInterface {\n public:\n  virtual ~CardinalityInterface();\n\n  // Returns true if and only if call_count calls will satisfy this cardinality.\n  virtual bool IsSatisfiedByCallCount(int call_count) const = 0;\n\n  // Returns true if and only if call_count calls will saturate this\n  // cardinality.\n  virtual bool IsSaturatedByCallCount(int call_count) const = 0;\n\n  // Describes self to an ostream.\n  virtual void DescribeTo(std::ostream* os) const = 0;\n};\n```\n\nFor example, to specify that a call must occur even number of times, you can\nwrite\n\n```cpp\nusing ::testing::Cardinality;\nusing ::testing::CardinalityInterface;\nusing ::testing::MakeCardinality;\n\nclass EvenNumberCardinality : public CardinalityInterface {\n public:\n  bool IsSatisfiedByCallCount(int call_count) const override {\n    return (call_count % 2) == 0;\n  }\n\n  bool IsSaturatedByCallCount(int call_count) const override {\n    return false;\n  }\n\n  void DescribeTo(std::ostream* os) const {\n    *os << \"called even number of times\";\n  }\n};\n\nCardinality EvenNumber() {\n  return MakeCardinality(new EvenNumberCardinality);\n}\n\n...\n  EXPECT_CALL(foo, Bar(3))\n      .Times(EvenNumber());\n```\n\n### Writing New Actions {#QuickNewActions}\n\nIf the built-in actions don't work for you, you can easily define your own one.\nAll you need is a call operator with a signature compatible with the mocked\nfunction. So you can use a lambda:\n\n```\nMockFunction<int(int)> mock;\nEXPECT_CALL(mock, Call).WillOnce([](const int input) { return input * 7; });\nEXPECT_EQ(14, mock.AsStdFunction()(2));\n```\n\nOr a struct with a call operator (even a templated one):\n\n```\nstruct MultiplyBy {\n  template <typename T>\n  T operator()(T arg) { return arg * multiplier; }\n\n  int multiplier;\n};\n\n// Then use:\n// EXPECT_CALL(...).WillOnce(MultiplyBy{7});\n```\n\nIt's also fine for the callable to take no arguments, ignoring the arguments\nsupplied to the mock function:\n\n```\nMockFunction<int(int)> mock;\nEXPECT_CALL(mock, Call).WillOnce([] { return 17; });\nEXPECT_EQ(17, mock.AsStdFunction()(0));\n```\n\nWhen used with `WillOnce`, the callable can assume it will be called at most\nonce and is allowed to be a move-only type:\n\n```\n// An action that contains move-only types and has an &&-qualified operator,\n// demanding in the type system that it be called at most once. This can be\n// used with WillOnce, but the compiler will reject it if handed to\n// WillRepeatedly.\nstruct MoveOnlyAction {\n  std::unique_ptr<int> move_only_state;\n  std::unique_ptr<int> operator()() && { return std::move(move_only_state); }\n};\n\nMockFunction<std::unique_ptr<int>()> mock;\nEXPECT_CALL(mock, Call).WillOnce(MoveOnlyAction{std::make_unique<int>(17)});\nEXPECT_THAT(mock.AsStdFunction()(), Pointee(Eq(17)));\n```\n\nMore generally, to use with a mock function whose signature is `R(Args...)` the\nobject can be anything convertible to `OnceAction<R(Args...)>` or\n`Action<R(Args...)`>. The difference between the two is that `OnceAction` has\nweaker requirements (`Action` requires a copy-constructible input that can be\ncalled repeatedly whereas `OnceAction` requires only move-constructible and\nsupports `&&`-qualified call operators), but can be used only with `WillOnce`.\n`OnceAction` is typically relevant only when supporting move-only types or\nactions that want a type-system guarantee that they will be called at most once.\n\nTypically the `OnceAction` and `Action` templates need not be referenced\ndirectly in your actions: a struct or class with a call operator is sufficient,\nas in the examples above. But fancier polymorphic actions that need to know the\nspecific return type of the mock function can define templated conversion\noperators to make that possible. See `gmock-actions.h` for examples.\n\n#### Legacy macro-based Actions\n\nBefore C++11, the functor-based actions were not supported; the old way of\nwriting actions was through a set of `ACTION*` macros. We suggest to avoid them\nin new code; they hide a lot of logic behind the macro, potentially leading to\nharder-to-understand compiler errors. Nevertheless, we cover them here for\ncompleteness.\n\nBy writing\n\n```cpp\nACTION(name) { statements; }\n```\n\nin a namespace scope (i.e. not inside a class or function), you will define an\naction with the given name that executes the statements. The value returned by\n`statements` will be used as the return value of the action. Inside the\nstatements, you can refer to the K-th (0-based) argument of the mock function as\n`argK`. For example:\n\n```cpp\nACTION(IncrementArg1) { return ++(*arg1); }\n```\n\nallows you to write\n\n```cpp\n... WillOnce(IncrementArg1());\n```\n\nNote that you don't need to specify the types of the mock function arguments.\nRest assured that your code is type-safe though: you'll get a compiler error if\n`*arg1` doesn't support the `++` operator, or if the type of `++(*arg1)` isn't\ncompatible with the mock function's return type.\n\nAnother example:\n\n```cpp\nACTION(Foo) {\n  (*arg2)(5);\n  Blah();\n  *arg1 = 0;\n  return arg0;\n}\n```\n\ndefines an action `Foo()` that invokes argument #2 (a function pointer) with 5,\ncalls function `Blah()`, sets the value pointed to by argument #1 to 0, and\nreturns argument #0.\n\nFor more convenience and flexibility, you can also use the following pre-defined\nsymbols in the body of `ACTION`:\n\n`argK_type`     | The type of the K-th (0-based) argument of the mock function\n:-------------- | :-----------------------------------------------------------\n`args`          | All arguments of the mock function as a tuple\n`args_type`     | The type of all arguments of the mock function as a tuple\n`return_type`   | The return type of the mock function\n`function_type` | The type of the mock function\n\nFor example, when using an `ACTION` as a stub action for mock function:\n\n```cpp\nint DoSomething(bool flag, int* ptr);\n```\n\nwe have:\n\nPre-defined Symbol | Is Bound To\n------------------ | ---------------------------------\n`arg0`             | the value of `flag`\n`arg0_type`        | the type `bool`\n`arg1`             | the value of `ptr`\n`arg1_type`        | the type `int*`\n`args`             | the tuple `(flag, ptr)`\n`args_type`        | the type `std::tuple<bool, int*>`\n`return_type`      | the type `int`\n`function_type`    | the type `int(bool, int*)`\n\n#### Legacy macro-based parameterized Actions\n\nSometimes you'll want to parameterize an action you define. For that we have\nanother macro\n\n```cpp\nACTION_P(name, param) { statements; }\n```\n\nFor example,\n\n```cpp\nACTION_P(Add, n) { return arg0 + n; }\n```\n\nwill allow you to write\n\n```cpp\n// Returns argument #0 + 5.\n... WillOnce(Add(5));\n```\n\nFor convenience, we use the term *arguments* for the values used to invoke the\nmock function, and the term *parameters* for the values used to instantiate an\naction.\n\nNote that you don't need to provide the type of the parameter either. Suppose\nthe parameter is named `param`, you can also use the gMock-defined symbol\n`param_type` to refer to the type of the parameter as inferred by the compiler.\nFor example, in the body of `ACTION_P(Add, n)` above, you can write `n_type` for\nthe type of `n`.\n\ngMock also provides `ACTION_P2`, `ACTION_P3`, and etc to support multi-parameter\nactions. For example,\n\n```cpp\nACTION_P2(ReturnDistanceTo, x, y) {\n  double dx = arg0 - x;\n  double dy = arg1 - y;\n  return sqrt(dx*dx + dy*dy);\n}\n```\n\nlets you write\n\n```cpp\n... WillOnce(ReturnDistanceTo(5.0, 26.5));\n```\n\nYou can view `ACTION` as a degenerated parameterized action where the number of\nparameters is 0.\n\nYou can also easily define actions overloaded on the number of parameters:\n\n```cpp\nACTION_P(Plus, a) { ... }\nACTION_P2(Plus, a, b) { ... }\n```\n\n### Restricting the Type of an Argument or Parameter in an ACTION\n\nFor maximum brevity and reusability, the `ACTION*` macros don't ask you to\nprovide the types of the mock function arguments and the action parameters.\nInstead, we let the compiler infer the types for us.\n\nSometimes, however, we may want to be more explicit about the types. There are\nseveral tricks to do that. For example:\n\n```cpp\nACTION(Foo) {\n  // Makes sure arg0 can be converted to int.\n  int n = arg0;\n  ... use n instead of arg0 here ...\n}\n\nACTION_P(Bar, param) {\n  // Makes sure the type of arg1 is const char*.\n  ::testing::StaticAssertTypeEq<const char*, arg1_type>();\n\n  // Makes sure param can be converted to bool.\n  bool flag = param;\n}\n```\n\nwhere `StaticAssertTypeEq` is a compile-time assertion in googletest that\nverifies two types are the same.\n\n### Writing New Action Templates Quickly\n\nSometimes you want to give an action explicit template parameters that cannot be\ninferred from its value parameters. `ACTION_TEMPLATE()` supports that and can be\nviewed as an extension to `ACTION()` and `ACTION_P*()`.\n\nThe syntax:\n\n```cpp\nACTION_TEMPLATE(ActionName,\n                HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m),\n                AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; }\n```\n\ndefines an action template that takes *m* explicit template parameters and *n*\nvalue parameters, where *m* is in [1, 10] and *n* is in [0, 10]. `name_i` is the\nname of the *i*-th template parameter, and `kind_i` specifies whether it's a\n`typename`, an integral constant, or a template. `p_i` is the name of the *i*-th\nvalue parameter.\n\nExample:\n\n```cpp\n// DuplicateArg<k, T>(output) converts the k-th argument of the mock\n// function to type T and copies it to *output.\nACTION_TEMPLATE(DuplicateArg,\n                // Note the comma between int and k:\n                HAS_2_TEMPLATE_PARAMS(int, k, typename, T),\n                AND_1_VALUE_PARAMS(output)) {\n  *output = T(std::get<k>(args));\n}\n```\n\nTo create an instance of an action template, write:\n\n```cpp\nActionName<t1, ..., t_m>(v1, ..., v_n)\n```\n\nwhere the `t`s are the template arguments and the `v`s are the value arguments.\nThe value argument types are inferred by the compiler. For example:\n\n```cpp\nusing ::testing::_;\n...\n  int n;\n  EXPECT_CALL(mock, Foo).WillOnce(DuplicateArg<1, unsigned char>(&n));\n```\n\nIf you want to explicitly specify the value argument types, you can provide\nadditional template arguments:\n\n```cpp\nActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n)\n```\n\nwhere `u_i` is the desired type of `v_i`.\n\n`ACTION_TEMPLATE` and `ACTION`/`ACTION_P*` can be overloaded on the number of\nvalue parameters, but not on the number of template parameters. Without the\nrestriction, the meaning of the following is unclear:\n\n```cpp\n  OverloadedAction<int, bool>(x);\n```\n\nAre we using a single-template-parameter action where `bool` refers to the type\nof `x`, or a two-template-parameter action where the compiler is asked to infer\nthe type of `x`?\n\n### Using the ACTION Object's Type\n\nIf you are writing a function that returns an `ACTION` object, you'll need to\nknow its type. The type depends on the macro used to define the action and the\nparameter types. The rule is relatively simple:\n\n\n| Given Definition              | Expression          | Has Type              |\n| ----------------------------- | ------------------- | --------------------- |\n| `ACTION(Foo)`                 | `Foo()`             | `FooAction`           |\n| `ACTION_TEMPLATE(Foo, HAS_m_TEMPLATE_PARAMS(...), AND_0_VALUE_PARAMS())` | `Foo<t1, ..., t_m>()` | `FooAction<t1, ..., t_m>` |\n| `ACTION_P(Bar, param)`        | `Bar(int_value)`    | `BarActionP<int>`     |\n| `ACTION_TEMPLATE(Bar, HAS_m_TEMPLATE_PARAMS(...), AND_1_VALUE_PARAMS(p1))` | `Bar<t1, ..., t_m>(int_value)` | `BarActionP<t1, ..., t_m, int>` |\n| `ACTION_P2(Baz, p1, p2)`      | `Baz(bool_value, int_value)` | `BazActionP2<bool, int>` |\n| `ACTION_TEMPLATE(Baz, HAS_m_TEMPLATE_PARAMS(...), AND_2_VALUE_PARAMS(p1, p2))` | `Baz<t1, ..., t_m>(bool_value, int_value)` | `BazActionP2<t1, ..., t_m, bool, int>` |\n| ...                           | ...                 | ...                   |\n\n\nNote that we have to pick different suffixes (`Action`, `ActionP`, `ActionP2`,\nand etc) for actions with different numbers of value parameters, or the action\ndefinitions cannot be overloaded on the number of them.\n\n### Writing New Monomorphic Actions {#NewMonoActions}\n\nWhile the `ACTION*` macros are very convenient, sometimes they are\ninappropriate. For example, despite the tricks shown in the previous recipes,\nthey don't let you directly specify the types of the mock function arguments and\nthe action parameters, which in general leads to unoptimized compiler error\nmessages that can baffle unfamiliar users. They also don't allow overloading\nactions based on parameter types without jumping through some hoops.\n\nAn alternative to the `ACTION*` macros is to implement\n`::testing::ActionInterface<F>`, where `F` is the type of the mock function in\nwhich the action will be used. For example:\n\n```cpp\ntemplate <typename F>\nclass ActionInterface {\n public:\n  virtual ~ActionInterface();\n\n  // Performs the action.  Result is the return type of function type\n  // F, and ArgumentTuple is the tuple of arguments of F.\n  //\n\n  // For example, if F is int(bool, const string&), then Result would\n  // be int, and ArgumentTuple would be std::tuple<bool, const string&>.\n  virtual Result Perform(const ArgumentTuple& args) = 0;\n};\n```\n\n```cpp\nusing ::testing::_;\nusing ::testing::Action;\nusing ::testing::ActionInterface;\nusing ::testing::MakeAction;\n\ntypedef int IncrementMethod(int*);\n\nclass IncrementArgumentAction : public ActionInterface<IncrementMethod> {\n public:\n  int Perform(const std::tuple<int*>& args) override {\n    int* p = std::get<0>(args);  // Grabs the first argument.\n    return *p++;\n  }\n};\n\nAction<IncrementMethod> IncrementArgument() {\n  return MakeAction(new IncrementArgumentAction);\n}\n\n...\n  EXPECT_CALL(foo, Baz(_))\n      .WillOnce(IncrementArgument());\n\n  int n = 5;\n  foo.Baz(&n);  // Should return 5 and change n to 6.\n```\n\n### Writing New Polymorphic Actions {#NewPolyActions}\n\nThe previous recipe showed you how to define your own action. This is all good,\nexcept that you need to know the type of the function in which the action will\nbe used. Sometimes that can be a problem. For example, if you want to use the\naction in functions with *different* types (e.g. like `Return()` and\n`SetArgPointee()`).\n\nIf an action can be used in several types of mock functions, we say it's\n*polymorphic*. The `MakePolymorphicAction()` function template makes it easy to\ndefine such an action:\n\n```cpp\nnamespace testing {\ntemplate <typename Impl>\nPolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl);\n}  // namespace testing\n```\n\nAs an example, let's define an action that returns the second argument in the\nmock function's argument list. The first step is to define an implementation\nclass:\n\n```cpp\nclass ReturnSecondArgumentAction {\n public:\n  template <typename Result, typename ArgumentTuple>\n  Result Perform(const ArgumentTuple& args) const {\n    // To get the i-th (0-based) argument, use std::get(args).\n    return std::get<1>(args);\n  }\n};\n```\n\nThis implementation class does *not* need to inherit from any particular class.\nWhat matters is that it must have a `Perform()` method template. This method\ntemplate takes the mock function's arguments as a tuple in a **single**\nargument, and returns the result of the action. It can be either `const` or not,\nbut must be invocable with exactly one template argument, which is the result\ntype. In other words, you must be able to call `Perform<R>(args)` where `R` is\nthe mock function's return type and `args` is its arguments in a tuple.\n\nNext, we use `MakePolymorphicAction()` to turn an instance of the implementation\nclass into the polymorphic action we need. It will be convenient to have a\nwrapper for this:\n\n```cpp\nusing ::testing::MakePolymorphicAction;\nusing ::testing::PolymorphicAction;\n\nPolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() {\n  return MakePolymorphicAction(ReturnSecondArgumentAction());\n}\n```\n\nNow, you can use this polymorphic action the same way you use the built-in ones:\n\n```cpp\nusing ::testing::_;\n\nclass MockFoo : public Foo {\n public:\n  MOCK_METHOD(int, DoThis, (bool flag, int n), (override));\n  MOCK_METHOD(string, DoThat, (int x, const char* str1, const char* str2),\n              (override));\n};\n\n  ...\n  MockFoo foo;\n  EXPECT_CALL(foo, DoThis).WillOnce(ReturnSecondArgument());\n  EXPECT_CALL(foo, DoThat).WillOnce(ReturnSecondArgument());\n  ...\n  foo.DoThis(true, 5);  // Will return 5.\n  foo.DoThat(1, \"Hi\", \"Bye\");  // Will return \"Hi\".\n```\n\n### Teaching gMock How to Print Your Values\n\nWhen an uninteresting or unexpected call occurs, gMock prints the argument\nvalues and the stack trace to help you debug. Assertion macros like\n`EXPECT_THAT` and `EXPECT_EQ` also print the values in question when the\nassertion fails. gMock and googletest do this using googletest's user-extensible\nvalue printer.\n\nThis printer knows how to print built-in C++ types, native arrays, STL\ncontainers, and any type that supports the `<<` operator. For other types, it\nprints the raw bytes in the value and hopes that you the user can figure it out.\n[The GoogleTest advanced guide](advanced.md#teaching-googletest-how-to-print-your-values)\nexplains how to extend the printer to do a better job at printing your\nparticular type than to dump the bytes.\n\n## Useful Mocks Created Using gMock\n\n<!--#include file=\"includes/g3_testing_LOGs.md\"-->\n<!--#include file=\"includes/g3_mock_callbacks.md\"-->\n\n### Mock std::function {#MockFunction}\n\n`std::function` is a general function type introduced in C++11. It is a\npreferred way of passing callbacks to new interfaces. Functions are copiable,\nand are not usually passed around by pointer, which makes them tricky to mock.\nBut fear not - `MockFunction` can help you with that.\n\n`MockFunction<R(T1, ..., Tn)>` has a mock method `Call()` with the signature:\n\n```cpp\n  R Call(T1, ..., Tn);\n```\n\nIt also has a `AsStdFunction()` method, which creates a `std::function` proxy\nforwarding to Call:\n\n```cpp\n  std::function<R(T1, ..., Tn)> AsStdFunction();\n```\n\nTo use `MockFunction`, first create `MockFunction` object and set up\nexpectations on its `Call` method. Then pass proxy obtained from\n`AsStdFunction()` to the code you are testing. For example:\n\n```cpp\nTEST(FooTest, RunsCallbackWithBarArgument) {\n  // 1. Create a mock object.\n  MockFunction<int(string)> mock_function;\n\n  // 2. Set expectations on Call() method.\n  EXPECT_CALL(mock_function, Call(\"bar\")).WillOnce(Return(1));\n\n  // 3. Exercise code that uses std::function.\n  Foo(mock_function.AsStdFunction());\n  // Foo's signature can be either of:\n  // void Foo(const std::function<int(string)>& fun);\n  // void Foo(std::function<int(string)> fun);\n\n  // 4. All expectations will be verified when mock_function\n  //     goes out of scope and is destroyed.\n}\n```\n\nRemember that function objects created with `AsStdFunction()` are just\nforwarders. If you create multiple of them, they will share the same set of\nexpectations.\n\nAlthough `std::function` supports unlimited number of arguments, `MockFunction`\nimplementation is limited to ten. If you ever hit that limit... well, your\ncallback has bigger problems than being mockable. :-)\n"
  },
  {
    "path": "3rd/googletest-1.12.1/docs/gmock_faq.md",
    "content": "# Legacy gMock FAQ\n\n### When I call a method on my mock object, the method for the real object is invoked instead. What's the problem?\n\nIn order for a method to be mocked, it must be *virtual*, unless you use the\n[high-perf dependency injection technique](gmock_cook_book.md#MockingNonVirtualMethods).\n\n### Can I mock a variadic function?\n\nYou cannot mock a variadic function (i.e. a function taking ellipsis (`...`)\narguments) directly in gMock.\n\nThe problem is that in general, there is *no way* for a mock object to know how\nmany arguments are passed to the variadic method, and what the arguments' types\nare. Only the *author of the base class* knows the protocol, and we cannot look\ninto his or her head.\n\nTherefore, to mock such a function, the *user* must teach the mock object how to\nfigure out the number of arguments and their types. One way to do it is to\nprovide overloaded versions of the function.\n\nEllipsis arguments are inherited from C and not really a C++ feature. They are\nunsafe to use and don't work with arguments that have constructors or\ndestructors. Therefore we recommend to avoid them in C++ as much as possible.\n\n### MSVC gives me warning C4301 or C4373 when I define a mock method with a const parameter. Why?\n\nIf you compile this using Microsoft Visual C++ 2005 SP1:\n\n```cpp\nclass Foo {\n  ...\n  virtual void Bar(const int i) = 0;\n};\n\nclass MockFoo : public Foo {\n  ...\n  MOCK_METHOD(void, Bar, (const int i), (override));\n};\n```\n\nYou may get the following warning:\n\n```shell\nwarning C4301: 'MockFoo::Bar': overriding virtual function only differs from 'Foo::Bar' by const/volatile qualifier\n```\n\nThis is a MSVC bug. The same code compiles fine with gcc, for example. If you\nuse Visual C++ 2008 SP1, you would get the warning:\n\n```shell\nwarning C4373: 'MockFoo::Bar': virtual function overrides 'Foo::Bar', previous versions of the compiler did not override when parameters only differed by const/volatile qualifiers\n```\n\nIn C++, if you *declare* a function with a `const` parameter, the `const`\nmodifier is ignored. Therefore, the `Foo` base class above is equivalent to:\n\n```cpp\nclass Foo {\n  ...\n  virtual void Bar(int i) = 0;  // int or const int?  Makes no difference.\n};\n```\n\nIn fact, you can *declare* `Bar()` with an `int` parameter, and define it with a\n`const int` parameter. The compiler will still match them up.\n\nSince making a parameter `const` is meaningless in the method declaration, we\nrecommend to remove it in both `Foo` and `MockFoo`. That should workaround the\nVC bug.\n\nNote that we are talking about the *top-level* `const` modifier here. If the\nfunction parameter is passed by pointer or reference, declaring the pointee or\nreferee as `const` is still meaningful. For example, the following two\ndeclarations are *not* equivalent:\n\n```cpp\nvoid Bar(int* p);         // Neither p nor *p is const.\nvoid Bar(const int* p);  // p is not const, but *p is.\n```\n\n### I can't figure out why gMock thinks my expectations are not satisfied. What should I do?\n\nYou might want to run your test with `--gmock_verbose=info`. This flag lets\ngMock print a trace of every mock function call it receives. By studying the\ntrace, you'll gain insights on why the expectations you set are not met.\n\nIf you see the message \"The mock function has no default action set, and its\nreturn type has no default value set.\", then try\n[adding a default action](gmock_cheat_sheet.md#OnCall). Due to a known issue,\nunexpected calls on mocks without default actions don't print out a detailed\ncomparison between the actual arguments and the expected arguments.\n\n### My program crashed and `ScopedMockLog` spit out tons of messages. Is it a gMock bug?\n\ngMock and `ScopedMockLog` are likely doing the right thing here.\n\nWhen a test crashes, the failure signal handler will try to log a lot of\ninformation (the stack trace, and the address map, for example). The messages\nare compounded if you have many threads with depth stacks. When `ScopedMockLog`\nintercepts these messages and finds that they don't match any expectations, it\nprints an error for each of them.\n\nYou can learn to ignore the errors, or you can rewrite your expectations to make\nyour test more robust, for example, by adding something like:\n\n```cpp\nusing ::testing::AnyNumber;\nusing ::testing::Not;\n...\n  // Ignores any log not done by us.\n  EXPECT_CALL(log, Log(_, Not(EndsWith(\"/my_file.cc\")), _))\n      .Times(AnyNumber());\n```\n\n### How can I assert that a function is NEVER called?\n\n```cpp\nusing ::testing::_;\n...\n  EXPECT_CALL(foo, Bar(_))\n      .Times(0);\n```\n\n### I have a failed test where gMock tells me TWICE that a particular expectation is not satisfied. Isn't this redundant?\n\nWhen gMock detects a failure, it prints relevant information (the mock function\narguments, the state of relevant expectations, and etc) to help the user debug.\nIf another failure is detected, gMock will do the same, including printing the\nstate of relevant expectations.\n\nSometimes an expectation's state didn't change between two failures, and you'll\nsee the same description of the state twice. They are however *not* redundant,\nas they refer to *different points in time*. The fact they are the same *is*\ninteresting information.\n\n### I get a heapcheck failure when using a mock object, but using a real object is fine. What can be wrong?\n\nDoes the class (hopefully a pure interface) you are mocking have a virtual\ndestructor?\n\nWhenever you derive from a base class, make sure its destructor is virtual.\nOtherwise Bad Things will happen. Consider the following code:\n\n```cpp\nclass Base {\n public:\n  // Not virtual, but should be.\n  ~Base() { ... }\n  ...\n};\n\nclass Derived : public Base {\n public:\n  ...\n private:\n  std::string value_;\n};\n\n...\n  Base* p = new Derived;\n  ...\n  delete p;  // Surprise! ~Base() will be called, but ~Derived() will not\n                 // - value_ is leaked.\n```\n\nBy changing `~Base()` to virtual, `~Derived()` will be correctly called when\n`delete p` is executed, and the heap checker will be happy.\n\n### The \"newer expectations override older ones\" rule makes writing expectations awkward. Why does gMock do that?\n\nWhen people complain about this, often they are referring to code like:\n\n```cpp\nusing ::testing::Return;\n...\n  // foo.Bar() should be called twice, return 1 the first time, and return\n  // 2 the second time.  However, I have to write the expectations in the\n  // reverse order.  This sucks big time!!!\n  EXPECT_CALL(foo, Bar())\n      .WillOnce(Return(2))\n      .RetiresOnSaturation();\n  EXPECT_CALL(foo, Bar())\n      .WillOnce(Return(1))\n      .RetiresOnSaturation();\n```\n\nThe problem, is that they didn't pick the **best** way to express the test's\nintent.\n\nBy default, expectations don't have to be matched in *any* particular order. If\nyou want them to match in a certain order, you need to be explicit. This is\ngMock's (and jMock's) fundamental philosophy: it's easy to accidentally\nover-specify your tests, and we want to make it harder to do so.\n\nThere are two better ways to write the test spec. You could either put the\nexpectations in sequence:\n\n```cpp\nusing ::testing::Return;\n...\n  // foo.Bar() should be called twice, return 1 the first time, and return\n  // 2 the second time.  Using a sequence, we can write the expectations\n  // in their natural order.\n  {\n    InSequence s;\n    EXPECT_CALL(foo, Bar())\n        .WillOnce(Return(1))\n        .RetiresOnSaturation();\n    EXPECT_CALL(foo, Bar())\n        .WillOnce(Return(2))\n        .RetiresOnSaturation();\n  }\n```\n\nor you can put the sequence of actions in the same expectation:\n\n```cpp\nusing ::testing::Return;\n...\n  // foo.Bar() should be called twice, return 1 the first time, and return\n  // 2 the second time.\n  EXPECT_CALL(foo, Bar())\n      .WillOnce(Return(1))\n      .WillOnce(Return(2))\n      .RetiresOnSaturation();\n```\n\nBack to the original questions: why does gMock search the expectations (and\n`ON_CALL`s) from back to front? Because this allows a user to set up a mock's\nbehavior for the common case early (e.g. in the mock's constructor or the test\nfixture's set-up phase) and customize it with more specific rules later. If\ngMock searches from front to back, this very useful pattern won't be possible.\n\n### gMock prints a warning when a function without EXPECT_CALL is called, even if I have set its behavior using ON_CALL. Would it be reasonable not to show the warning in this case?\n\nWhen choosing between being neat and being safe, we lean toward the latter. So\nthe answer is that we think it's better to show the warning.\n\nOften people write `ON_CALL`s in the mock object's constructor or `SetUp()`, as\nthe default behavior rarely changes from test to test. Then in the test body\nthey set the expectations, which are often different for each test. Having an\n`ON_CALL` in the set-up part of a test doesn't mean that the calls are expected.\nIf there's no `EXPECT_CALL` and the method is called, it's possibly an error. If\nwe quietly let the call go through without notifying the user, bugs may creep in\nunnoticed.\n\nIf, however, you are sure that the calls are OK, you can write\n\n```cpp\nusing ::testing::_;\n...\n  EXPECT_CALL(foo, Bar(_))\n      .WillRepeatedly(...);\n```\n\ninstead of\n\n```cpp\nusing ::testing::_;\n...\n  ON_CALL(foo, Bar(_))\n      .WillByDefault(...);\n```\n\nThis tells gMock that you do expect the calls and no warning should be printed.\n\nAlso, you can control the verbosity by specifying `--gmock_verbose=error`. Other\nvalues are `info` and `warning`. If you find the output too noisy when\ndebugging, just choose a less verbose level.\n\n### How can I delete the mock function's argument in an action?\n\nIf your mock function takes a pointer argument and you want to delete that\nargument, you can use testing::DeleteArg<N>() to delete the N'th (zero-indexed)\nargument:\n\n```cpp\nusing ::testing::_;\n  ...\n  MOCK_METHOD(void, Bar, (X* x, const Y& y));\n  ...\n  EXPECT_CALL(mock_foo_, Bar(_, _))\n      .WillOnce(testing::DeleteArg<0>()));\n```\n\n### How can I perform an arbitrary action on a mock function's argument?\n\nIf you find yourself needing to perform some action that's not supported by\ngMock directly, remember that you can define your own actions using\n[`MakeAction()`](#NewMonoActions) or\n[`MakePolymorphicAction()`](#NewPolyActions), or you can write a stub function\nand invoke it using [`Invoke()`](#FunctionsAsActions).\n\n```cpp\nusing ::testing::_;\nusing ::testing::Invoke;\n  ...\n  MOCK_METHOD(void, Bar, (X* p));\n  ...\n  EXPECT_CALL(mock_foo_, Bar(_))\n      .WillOnce(Invoke(MyAction(...)));\n```\n\n### My code calls a static/global function. Can I mock it?\n\nYou can, but you need to make some changes.\n\nIn general, if you find yourself needing to mock a static function, it's a sign\nthat your modules are too tightly coupled (and less flexible, less reusable,\nless testable, etc). You are probably better off defining a small interface and\ncall the function through that interface, which then can be easily mocked. It's\na bit of work initially, but usually pays for itself quickly.\n\nThis Google Testing Blog\n[post](https://testing.googleblog.com/2008/06/defeat-static-cling.html) says it\nexcellently. Check it out.\n\n### My mock object needs to do complex stuff. It's a lot of pain to specify the actions. gMock sucks!\n\nI know it's not a question, but you get an answer for free any way. :-)\n\nWith gMock, you can create mocks in C++ easily. And people might be tempted to\nuse them everywhere. Sometimes they work great, and sometimes you may find them,\nwell, a pain to use. So, what's wrong in the latter case?\n\nWhen you write a test without using mocks, you exercise the code and assert that\nit returns the correct value or that the system is in an expected state. This is\nsometimes called \"state-based testing\".\n\nMocks are great for what some call \"interaction-based\" testing: instead of\nchecking the system state at the very end, mock objects verify that they are\ninvoked the right way and report an error as soon as it arises, giving you a\nhandle on the precise context in which the error was triggered. This is often\nmore effective and economical to do than state-based testing.\n\nIf you are doing state-based testing and using a test double just to simulate\nthe real object, you are probably better off using a fake. Using a mock in this\ncase causes pain, as it's not a strong point for mocks to perform complex\nactions. If you experience this and think that mocks suck, you are just not\nusing the right tool for your problem. Or, you might be trying to solve the\nwrong problem. :-)\n\n### I got a warning \"Uninteresting function call encountered - default action taken..\" Should I panic?\n\nBy all means, NO! It's just an FYI. :-)\n\nWhat it means is that you have a mock function, you haven't set any expectations\non it (by gMock's rule this means that you are not interested in calls to this\nfunction and therefore it can be called any number of times), and it is called.\nThat's OK - you didn't say it's not OK to call the function!\n\nWhat if you actually meant to disallow this function to be called, but forgot to\nwrite `EXPECT_CALL(foo, Bar()).Times(0)`? While one can argue that it's the\nuser's fault, gMock tries to be nice and prints you a note.\n\nSo, when you see the message and believe that there shouldn't be any\nuninteresting calls, you should investigate what's going on. To make your life\neasier, gMock dumps the stack trace when an uninteresting call is encountered.\nFrom that you can figure out which mock function it is, and how it is called.\n\n### I want to define a custom action. Should I use Invoke() or implement the ActionInterface interface?\n\nEither way is fine - you want to choose the one that's more convenient for your\ncircumstance.\n\nUsually, if your action is for a particular function type, defining it using\n`Invoke()` should be easier; if your action can be used in functions of\ndifferent types (e.g. if you are defining `Return(*value*)`),\n`MakePolymorphicAction()` is easiest. Sometimes you want precise control on what\ntypes of functions the action can be used in, and implementing `ActionInterface`\nis the way to go here. See the implementation of `Return()` in `gmock-actions.h`\nfor an example.\n\n### I use SetArgPointee() in WillOnce(), but gcc complains about \"conflicting return type specified\". What does it mean?\n\nYou got this error as gMock has no idea what value it should return when the\nmock method is called. `SetArgPointee()` says what the side effect is, but\ndoesn't say what the return value should be. You need `DoAll()` to chain a\n`SetArgPointee()` with a `Return()` that provides a value appropriate to the API\nbeing mocked.\n\nSee this [recipe](gmock_cook_book.md#mocking-side-effects) for more details and\nan example.\n\n### I have a huge mock class, and Microsoft Visual C++ runs out of memory when compiling it. What can I do?\n\nWe've noticed that when the `/clr` compiler flag is used, Visual C++ uses 5~6\ntimes as much memory when compiling a mock class. We suggest to avoid `/clr`\nwhen compiling native C++ mocks.\n"
  },
  {
    "path": "3rd/googletest-1.12.1/docs/gmock_for_dummies.md",
    "content": "# gMock for Dummies\n\n## What Is gMock?\n\nWhen you write a prototype or test, often it's not feasible or wise to rely on\nreal objects entirely. A **mock object** implements the same interface as a real\nobject (so it can be used as one), but lets you specify at run time how it will\nbe used and what it should do (which methods will be called? in which order? how\nmany times? with what arguments? what will they return? etc).\n\nIt is easy to confuse the term *fake objects* with mock objects. Fakes and mocks\nactually mean very different things in the Test-Driven Development (TDD)\ncommunity:\n\n*   **Fake** objects have working implementations, but usually take some\n    shortcut (perhaps to make the operations less expensive), which makes them\n    not suitable for production. An in-memory file system would be an example of\n    a fake.\n*   **Mocks** are objects pre-programmed with *expectations*, which form a\n    specification of the calls they are expected to receive.\n\nIf all this seems too abstract for you, don't worry - the most important thing\nto remember is that a mock allows you to check the *interaction* between itself\nand code that uses it. The difference between fakes and mocks shall become much\nclearer once you start to use mocks.\n\n**gMock** is a library (sometimes we also call it a \"framework\" to make it sound\ncool) for creating mock classes and using them. It does to C++ what\njMock/EasyMock does to Java (well, more or less).\n\nWhen using gMock,\n\n1.  first, you use some simple macros to describe the interface you want to\n    mock, and they will expand to the implementation of your mock class;\n2.  next, you create some mock objects and specify its expectations and behavior\n    using an intuitive syntax;\n3.  then you exercise code that uses the mock objects. gMock will catch any\n    violation to the expectations as soon as it arises.\n\n## Why gMock?\n\nWhile mock objects help you remove unnecessary dependencies in tests and make\nthem fast and reliable, using mocks manually in C++ is *hard*:\n\n*   Someone has to implement the mocks. The job is usually tedious and\n    error-prone. No wonder people go great distance to avoid it.\n*   The quality of those manually written mocks is a bit, uh, unpredictable. You\n    may see some really polished ones, but you may also see some that were\n    hacked up in a hurry and have all sorts of ad hoc restrictions.\n*   The knowledge you gained from using one mock doesn't transfer to the next\n    one.\n\nIn contrast, Java and Python programmers have some fine mock frameworks (jMock,\nEasyMock, etc), which automate the creation of mocks. As a result, mocking is a\nproven effective technique and widely adopted practice in those communities.\nHaving the right tool absolutely makes the difference.\n\ngMock was built to help C++ programmers. It was inspired by jMock and EasyMock,\nbut designed with C++'s specifics in mind. It is your friend if any of the\nfollowing problems is bothering you:\n\n*   You are stuck with a sub-optimal design and wish you had done more\n    prototyping before it was too late, but prototyping in C++ is by no means\n    \"rapid\".\n*   Your tests are slow as they depend on too many libraries or use expensive\n    resources (e.g. a database).\n*   Your tests are brittle as some resources they use are unreliable (e.g. the\n    network).\n*   You want to test how your code handles a failure (e.g. a file checksum\n    error), but it's not easy to cause one.\n*   You need to make sure that your module interacts with other modules in the\n    right way, but it's hard to observe the interaction; therefore you resort to\n    observing the side effects at the end of the action, but it's awkward at\n    best.\n*   You want to \"mock out\" your dependencies, except that they don't have mock\n    implementations yet; and, frankly, you aren't thrilled by some of those\n    hand-written mocks.\n\nWe encourage you to use gMock as\n\n*   a *design* tool, for it lets you experiment with your interface design early\n    and often. More iterations lead to better designs!\n*   a *testing* tool to cut your tests' outbound dependencies and probe the\n    interaction between your module and its collaborators.\n\n## Getting Started\n\ngMock is bundled with googletest.\n\n## A Case for Mock Turtles\n\nLet's look at an example. Suppose you are developing a graphics program that\nrelies on a [LOGO](http://en.wikipedia.org/wiki/Logo_programming_language)-like\nAPI for drawing. How would you test that it does the right thing? Well, you can\nrun it and compare the screen with a golden screen snapshot, but let's admit it:\ntests like this are expensive to run and fragile (What if you just upgraded to a\nshiny new graphics card that has better anti-aliasing? Suddenly you have to\nupdate all your golden images.). It would be too painful if all your tests are\nlike this. Fortunately, you learned about\n[Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection) and know the right thing\nto do: instead of having your application talk to the system API directly, wrap\nthe API in an interface (say, `Turtle`) and code to that interface:\n\n```cpp\nclass Turtle {\n  ...\n  virtual ~Turtle() {}\n  virtual void PenUp() = 0;\n  virtual void PenDown() = 0;\n  virtual void Forward(int distance) = 0;\n  virtual void Turn(int degrees) = 0;\n  virtual void GoTo(int x, int y) = 0;\n  virtual int GetX() const = 0;\n  virtual int GetY() const = 0;\n};\n```\n\n(Note that the destructor of `Turtle` **must** be virtual, as is the case for\n**all** classes you intend to inherit from - otherwise the destructor of the\nderived class will not be called when you delete an object through a base\npointer, and you'll get corrupted program states like memory leaks.)\n\nYou can control whether the turtle's movement will leave a trace using `PenUp()`\nand `PenDown()`, and control its movement using `Forward()`, `Turn()`, and\n`GoTo()`. Finally, `GetX()` and `GetY()` tell you the current position of the\nturtle.\n\nYour program will normally use a real implementation of this interface. In\ntests, you can use a mock implementation instead. This allows you to easily\ncheck what drawing primitives your program is calling, with what arguments, and\nin which order. Tests written this way are much more robust (they won't break\nbecause your new machine does anti-aliasing differently), easier to read and\nmaintain (the intent of a test is expressed in the code, not in some binary\nimages), and run *much, much faster*.\n\n## Writing the Mock Class\n\nIf you are lucky, the mocks you need to use have already been implemented by\nsome nice people. If, however, you find yourself in the position to write a mock\nclass, relax - gMock turns this task into a fun game! (Well, almost.)\n\n### How to Define It\n\nUsing the `Turtle` interface as example, here are the simple steps you need to\nfollow:\n\n*   Derive a class `MockTurtle` from `Turtle`.\n*   Take a *virtual* function of `Turtle` (while it's possible to\n    [mock non-virtual methods using templates](gmock_cook_book.md#MockingNonVirtualMethods),\n    it's much more involved).\n*   In the `public:` section of the child class, write `MOCK_METHOD();`\n*   Now comes the fun part: you take the function signature, cut-and-paste it\n    into the macro, and add two commas - one between the return type and the\n    name, another between the name and the argument list.\n*   If you're mocking a const method, add a 4th parameter containing `(const)`\n    (the parentheses are required).\n*   Since you're overriding a virtual method, we suggest adding the `override`\n    keyword. For const methods the 4th parameter becomes `(const, override)`,\n    for non-const methods just `(override)`. This isn't mandatory.\n*   Repeat until all virtual functions you want to mock are done. (It goes\n    without saying that *all* pure virtual methods in your abstract class must\n    be either mocked or overridden.)\n\nAfter the process, you should have something like:\n\n```cpp\n#include \"gmock/gmock.h\"  // Brings in gMock.\n\nclass MockTurtle : public Turtle {\n public:\n  ...\n  MOCK_METHOD(void, PenUp, (), (override));\n  MOCK_METHOD(void, PenDown, (), (override));\n  MOCK_METHOD(void, Forward, (int distance), (override));\n  MOCK_METHOD(void, Turn, (int degrees), (override));\n  MOCK_METHOD(void, GoTo, (int x, int y), (override));\n  MOCK_METHOD(int, GetX, (), (const, override));\n  MOCK_METHOD(int, GetY, (), (const, override));\n};\n```\n\nYou don't need to define these mock methods somewhere else - the `MOCK_METHOD`\nmacro will generate the definitions for you. It's that simple!\n\n### Where to Put It\n\nWhen you define a mock class, you need to decide where to put its definition.\nSome people put it in a `_test.cc`. This is fine when the interface being mocked\n(say, `Foo`) is owned by the same person or team. Otherwise, when the owner of\n`Foo` changes it, your test could break. (You can't really expect `Foo`'s\nmaintainer to fix every test that uses `Foo`, can you?)\n\nGenerally, you should not mock classes you don't own. If you must mock such a\nclass owned by others, define the mock class in `Foo`'s Bazel package (usually\nthe same directory or a `testing` sub-directory), and put it in a `.h` and a\n`cc_library` with `testonly=True`. Then everyone can reference them from their\ntests. If `Foo` ever changes, there is only one copy of `MockFoo` to change, and\nonly tests that depend on the changed methods need to be fixed.\n\nAnother way to do it: you can introduce a thin layer `FooAdaptor` on top of\n`Foo` and code to this new interface. Since you own `FooAdaptor`, you can absorb\nchanges in `Foo` much more easily. While this is more work initially, carefully\nchoosing the adaptor interface can make your code easier to write and more\nreadable (a net win in the long run), as you can choose `FooAdaptor` to fit your\nspecific domain much better than `Foo` does.\n\n## Using Mocks in Tests\n\nOnce you have a mock class, using it is easy. The typical work flow is:\n\n1.  Import the gMock names from the `testing` namespace such that you can use\n    them unqualified (You only have to do it once per file). Remember that\n    namespaces are a good idea.\n2.  Create some mock objects.\n3.  Specify your expectations on them (How many times will a method be called?\n    With what arguments? What should it do? etc.).\n4.  Exercise some code that uses the mocks; optionally, check the result using\n    googletest assertions. If a mock method is called more than expected or with\n    wrong arguments, you'll get an error immediately.\n5.  When a mock is destructed, gMock will automatically check whether all\n    expectations on it have been satisfied.\n\nHere's an example:\n\n```cpp\n#include \"path/to/mock-turtle.h\"\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n\nusing ::testing::AtLeast;                         // #1\n\nTEST(PainterTest, CanDrawSomething) {\n  MockTurtle turtle;                              // #2\n  EXPECT_CALL(turtle, PenDown())                  // #3\n      .Times(AtLeast(1));\n\n  Painter painter(&turtle);                       // #4\n\n  EXPECT_TRUE(painter.DrawCircle(0, 0, 10));      // #5\n}\n```\n\nAs you might have guessed, this test checks that `PenDown()` is called at least\nonce. If the `painter` object didn't call this method, your test will fail with\na message like this:\n\n```text\npath/to/my_test.cc:119: Failure\nActual function call count doesn't match this expectation:\nActually: never called;\nExpected: called at least once.\nStack trace:\n...\n```\n\n**Tip 1:** If you run the test from an Emacs buffer, you can hit `<Enter>` on\nthe line number to jump right to the failed expectation.\n\n**Tip 2:** If your mock objects are never deleted, the final verification won't\nhappen. Therefore it's a good idea to turn on the heap checker in your tests\nwhen you allocate mocks on the heap. You get that automatically if you use the\n`gtest_main` library already.\n\n**Important note:** gMock requires expectations to be set **before** the mock\nfunctions are called, otherwise the behavior is **undefined**. Do not alternate\nbetween calls to `EXPECT_CALL()` and calls to the mock functions, and do not set\nany expectations on a mock after passing the mock to an API.\n\nThis means `EXPECT_CALL()` should be read as expecting that a call will occur\n*in the future*, not that a call has occurred. Why does gMock work like that?\nWell, specifying the expectation beforehand allows gMock to report a violation\nas soon as it rises, when the context (stack trace, etc) is still available.\nThis makes debugging much easier.\n\nAdmittedly, this test is contrived and doesn't do much. You can easily achieve\nthe same effect without using gMock. However, as we shall reveal soon, gMock\nallows you to do *so much more* with the mocks.\n\n## Setting Expectations\n\nThe key to using a mock object successfully is to set the *right expectations*\non it. If you set the expectations too strict, your test will fail as the result\nof unrelated changes. If you set them too loose, bugs can slip through. You want\nto do it just right such that your test can catch exactly the kind of bugs you\nintend it to catch. gMock provides the necessary means for you to do it \"just\nright.\"\n\n### General Syntax\n\nIn gMock we use the `EXPECT_CALL()` macro to set an expectation on a mock\nmethod. The general syntax is:\n\n```cpp\nEXPECT_CALL(mock_object, method(matchers))\n    .Times(cardinality)\n    .WillOnce(action)\n    .WillRepeatedly(action);\n```\n\nThe macro has two arguments: first the mock object, and then the method and its\narguments. Note that the two are separated by a comma (`,`), not a period (`.`).\n(Why using a comma? The answer is that it was necessary for technical reasons.)\nIf the method is not overloaded, the macro can also be called without matchers:\n\n```cpp\nEXPECT_CALL(mock_object, non-overloaded-method)\n    .Times(cardinality)\n    .WillOnce(action)\n    .WillRepeatedly(action);\n```\n\nThis syntax allows the test writer to specify \"called with any arguments\"\nwithout explicitly specifying the number or types of arguments. To avoid\nunintended ambiguity, this syntax may only be used for methods that are not\noverloaded.\n\nEither form of the macro can be followed by some optional *clauses* that provide\nmore information about the expectation. We'll discuss how each clause works in\nthe coming sections.\n\nThis syntax is designed to make an expectation read like English. For example,\nyou can probably guess that\n\n```cpp\nusing ::testing::Return;\n...\nEXPECT_CALL(turtle, GetX())\n    .Times(5)\n    .WillOnce(Return(100))\n    .WillOnce(Return(150))\n    .WillRepeatedly(Return(200));\n```\n\nsays that the `turtle` object's `GetX()` method will be called five times, it\nwill return 100 the first time, 150 the second time, and then 200 every time.\nSome people like to call this style of syntax a Domain-Specific Language (DSL).\n\n{: .callout .note}\n**Note:** Why do we use a macro to do this? Well it serves two purposes: first\nit makes expectations easily identifiable (either by `grep` or by a human\nreader), and second it allows gMock to include the source file location of a\nfailed expectation in messages, making debugging easier.\n\n### Matchers: What Arguments Do We Expect?\n\nWhen a mock function takes arguments, we may specify what arguments we are\nexpecting, for example:\n\n```cpp\n// Expects the turtle to move forward by 100 units.\nEXPECT_CALL(turtle, Forward(100));\n```\n\nOftentimes you do not want to be too specific. Remember that talk about tests\nbeing too rigid? Over specification leads to brittle tests and obscures the\nintent of tests. Therefore we encourage you to specify only what's necessary—no\nmore, no less. If you aren't interested in the value of an argument, write `_`\nas the argument, which means \"anything goes\":\n\n```cpp\nusing ::testing::_;\n...\n// Expects that the turtle jumps to somewhere on the x=50 line.\nEXPECT_CALL(turtle, GoTo(50, _));\n```\n\n`_` is an instance of what we call **matchers**. A matcher is like a predicate\nand can test whether an argument is what we'd expect. You can use a matcher\ninside `EXPECT_CALL()` wherever a function argument is expected. `_` is a\nconvenient way of saying \"any value\".\n\nIn the above examples, `100` and `50` are also matchers; implicitly, they are\nthe same as `Eq(100)` and `Eq(50)`, which specify that the argument must be\nequal (using `operator==`) to the matcher argument. There are many\n[built-in matchers](reference/matchers.md) for common types (as well as\n[custom matchers](gmock_cook_book.md#NewMatchers)); for example:\n\n```cpp\nusing ::testing::Ge;\n...\n// Expects the turtle moves forward by at least 100.\nEXPECT_CALL(turtle, Forward(Ge(100)));\n```\n\nIf you don't care about *any* arguments, rather than specify `_` for each of\nthem you may instead omit the parameter list:\n\n```cpp\n// Expects the turtle to move forward.\nEXPECT_CALL(turtle, Forward);\n// Expects the turtle to jump somewhere.\nEXPECT_CALL(turtle, GoTo);\n```\n\nThis works for all non-overloaded methods; if a method is overloaded, you need\nto help gMock resolve which overload is expected by specifying the number of\narguments and possibly also the\n[types of the arguments](gmock_cook_book.md#SelectOverload).\n\n### Cardinalities: How Many Times Will It Be Called?\n\nThe first clause we can specify following an `EXPECT_CALL()` is `Times()`. We\ncall its argument a **cardinality** as it tells *how many times* the call should\noccur. It allows us to repeat an expectation many times without actually writing\nit as many times. More importantly, a cardinality can be \"fuzzy\", just like a\nmatcher can be. This allows a user to express the intent of a test exactly.\n\nAn interesting special case is when we say `Times(0)`. You may have guessed - it\nmeans that the function shouldn't be called with the given arguments at all, and\ngMock will report a googletest failure whenever the function is (wrongfully)\ncalled.\n\nWe've seen `AtLeast(n)` as an example of fuzzy cardinalities earlier. For the\nlist of built-in cardinalities you can use, see\n[here](gmock_cheat_sheet.md#CardinalityList).\n\nThe `Times()` clause can be omitted. **If you omit `Times()`, gMock will infer\nthe cardinality for you.** The rules are easy to remember:\n\n*   If **neither** `WillOnce()` **nor** `WillRepeatedly()` is in the\n    `EXPECT_CALL()`, the inferred cardinality is `Times(1)`.\n*   If there are *n* `WillOnce()`'s but **no** `WillRepeatedly()`, where *n* >=\n    1, the cardinality is `Times(n)`.\n*   If there are *n* `WillOnce()`'s and **one** `WillRepeatedly()`, where *n* >=\n    0, the cardinality is `Times(AtLeast(n))`.\n\n**Quick quiz:** what do you think will happen if a function is expected to be\ncalled twice but actually called four times?\n\n### Actions: What Should It Do?\n\nRemember that a mock object doesn't really have a working implementation? We as\nusers have to tell it what to do when a method is invoked. This is easy in\ngMock.\n\nFirst, if the return type of a mock function is a built-in type or a pointer,\nthe function has a **default action** (a `void` function will just return, a\n`bool` function will return `false`, and other functions will return 0). In\naddition, in C++ 11 and above, a mock function whose return type is\ndefault-constructible (i.e. has a default constructor) has a default action of\nreturning a default-constructed value. If you don't say anything, this behavior\nwill be used.\n\nSecond, if a mock function doesn't have a default action, or the default action\ndoesn't suit you, you can specify the action to be taken each time the\nexpectation matches using a series of `WillOnce()` clauses followed by an\noptional `WillRepeatedly()`. For example,\n\n```cpp\nusing ::testing::Return;\n...\nEXPECT_CALL(turtle, GetX())\n     .WillOnce(Return(100))\n     .WillOnce(Return(200))\n     .WillOnce(Return(300));\n```\n\nsays that `turtle.GetX()` will be called *exactly three times* (gMock inferred\nthis from how many `WillOnce()` clauses we've written, since we didn't\nexplicitly write `Times()`), and will return 100, 200, and 300 respectively.\n\n```cpp\nusing ::testing::Return;\n...\nEXPECT_CALL(turtle, GetY())\n     .WillOnce(Return(100))\n     .WillOnce(Return(200))\n     .WillRepeatedly(Return(300));\n```\n\nsays that `turtle.GetY()` will be called *at least twice* (gMock knows this as\nwe've written two `WillOnce()` clauses and a `WillRepeatedly()` while having no\nexplicit `Times()`), will return 100 and 200 respectively the first two times,\nand 300 from the third time on.\n\nOf course, if you explicitly write a `Times()`, gMock will not try to infer the\ncardinality itself. What if the number you specified is larger than there are\n`WillOnce()` clauses? Well, after all `WillOnce()`s are used up, gMock will do\nthe *default* action for the function every time (unless, of course, you have a\n`WillRepeatedly()`.).\n\nWhat can we do inside `WillOnce()` besides `Return()`? You can return a\nreference using `ReturnRef(`*`variable`*`)`, or invoke a pre-defined function,\namong [others](gmock_cook_book.md#using-actions).\n\n**Important note:** The `EXPECT_CALL()` statement evaluates the action clause\nonly once, even though the action may be performed many times. Therefore you\nmust be careful about side effects. The following may not do what you want:\n\n```cpp\nusing ::testing::Return;\n...\nint n = 100;\nEXPECT_CALL(turtle, GetX())\n    .Times(4)\n    .WillRepeatedly(Return(n++));\n```\n\nInstead of returning 100, 101, 102, ..., consecutively, this mock function will\nalways return 100 as `n++` is only evaluated once. Similarly, `Return(new Foo)`\nwill create a new `Foo` object when the `EXPECT_CALL()` is executed, and will\nreturn the same pointer every time. If you want the side effect to happen every\ntime, you need to define a custom action, which we'll teach in the\n[cook book](gmock_cook_book.md).\n\nTime for another quiz! What do you think the following means?\n\n```cpp\nusing ::testing::Return;\n...\nEXPECT_CALL(turtle, GetY())\n    .Times(4)\n    .WillOnce(Return(100));\n```\n\nObviously `turtle.GetY()` is expected to be called four times. But if you think\nit will return 100 every time, think twice! Remember that one `WillOnce()`\nclause will be consumed each time the function is invoked and the default action\nwill be taken afterwards. So the right answer is that `turtle.GetY()` will\nreturn 100 the first time, but **return 0 from the second time on**, as\nreturning 0 is the default action for `int` functions.\n\n### Using Multiple Expectations {#MultiExpectations}\n\nSo far we've only shown examples where you have a single expectation. More\nrealistically, you'll specify expectations on multiple mock methods which may be\nfrom multiple mock objects.\n\nBy default, when a mock method is invoked, gMock will search the expectations in\nthe **reverse order** they are defined, and stop when an active expectation that\nmatches the arguments is found (you can think of it as \"newer rules override\nolder ones.\"). If the matching expectation cannot take any more calls, you will\nget an upper-bound-violated failure. Here's an example:\n\n```cpp\nusing ::testing::_;\n...\nEXPECT_CALL(turtle, Forward(_));  // #1\nEXPECT_CALL(turtle, Forward(10))  // #2\n    .Times(2);\n```\n\nIf `Forward(10)` is called three times in a row, the third time it will be an\nerror, as the last matching expectation (#2) has been saturated. If, however,\nthe third `Forward(10)` call is replaced by `Forward(20)`, then it would be OK,\nas now #1 will be the matching expectation.\n\n{: .callout .note}\n**Note:** Why does gMock search for a match in the *reverse* order of the\nexpectations? The reason is that this allows a user to set up the default\nexpectations in a mock object's constructor or the test fixture's set-up phase\nand then customize the mock by writing more specific expectations in the test\nbody. So, if you have two expectations on the same method, you want to put the\none with more specific matchers **after** the other, or the more specific rule\nwould be shadowed by the more general one that comes after it.\n\n{: .callout .tip}\n**Tip:** It is very common to start with a catch-all expectation for a method\nand `Times(AnyNumber())` (omitting arguments, or with `_` for all arguments, if\noverloaded). This makes any calls to the method expected. This is not necessary\nfor methods that are not mentioned at all (these are \"uninteresting\"), but is\nuseful for methods that have some expectations, but for which other calls are\nok. See\n[Understanding Uninteresting vs Unexpected Calls](gmock_cook_book.md#uninteresting-vs-unexpected).\n\n### Ordered vs Unordered Calls {#OrderedCalls}\n\nBy default, an expectation can match a call even though an earlier expectation\nhasn't been satisfied. In other words, the calls don't have to occur in the\norder the expectations are specified.\n\nSometimes, you may want all the expected calls to occur in a strict order. To\nsay this in gMock is easy:\n\n```cpp\nusing ::testing::InSequence;\n...\nTEST(FooTest, DrawsLineSegment) {\n  ...\n  {\n    InSequence seq;\n\n    EXPECT_CALL(turtle, PenDown());\n    EXPECT_CALL(turtle, Forward(100));\n    EXPECT_CALL(turtle, PenUp());\n  }\n  Foo();\n}\n```\n\nBy creating an object of type `InSequence`, all expectations in its scope are\nput into a *sequence* and have to occur *sequentially*. Since we are just\nrelying on the constructor and destructor of this object to do the actual work,\nits name is really irrelevant.\n\nIn this example, we test that `Foo()` calls the three expected functions in the\norder as written. If a call is made out-of-order, it will be an error.\n\n(What if you care about the relative order of some of the calls, but not all of\nthem? Can you specify an arbitrary partial order? The answer is ... yes! The\ndetails can be found [here](gmock_cook_book.md#OrderedCalls).)\n\n### All Expectations Are Sticky (Unless Said Otherwise) {#StickyExpectations}\n\nNow let's do a quick quiz to see how well you can use this mock stuff already.\nHow would you test that the turtle is asked to go to the origin *exactly twice*\n(you want to ignore any other instructions it receives)?\n\nAfter you've come up with your answer, take a look at ours and compare notes\n(solve it yourself first - don't cheat!):\n\n```cpp\nusing ::testing::_;\nusing ::testing::AnyNumber;\n...\nEXPECT_CALL(turtle, GoTo(_, _))  // #1\n     .Times(AnyNumber());\nEXPECT_CALL(turtle, GoTo(0, 0))  // #2\n     .Times(2);\n```\n\nSuppose `turtle.GoTo(0, 0)` is called three times. In the third time, gMock will\nsee that the arguments match expectation #2 (remember that we always pick the\nlast matching expectation). Now, since we said that there should be only two\nsuch calls, gMock will report an error immediately. This is basically what we've\ntold you in the [Using Multiple Expectations](#MultiExpectations) section above.\n\nThis example shows that **expectations in gMock are \"sticky\" by default**, in\nthe sense that they remain active even after we have reached their invocation\nupper bounds. This is an important rule to remember, as it affects the meaning\nof the spec, and is **different** to how it's done in many other mocking\nframeworks (Why'd we do that? Because we think our rule makes the common cases\neasier to express and understand.).\n\nSimple? Let's see if you've really understood it: what does the following code\nsay?\n\n```cpp\nusing ::testing::Return;\n...\nfor (int i = n; i > 0; i--) {\n  EXPECT_CALL(turtle, GetX())\n      .WillOnce(Return(10*i));\n}\n```\n\nIf you think it says that `turtle.GetX()` will be called `n` times and will\nreturn 10, 20, 30, ..., consecutively, think twice! The problem is that, as we\nsaid, expectations are sticky. So, the second time `turtle.GetX()` is called,\nthe last (latest) `EXPECT_CALL()` statement will match, and will immediately\nlead to an \"upper bound violated\" error - this piece of code is not very useful!\n\nOne correct way of saying that `turtle.GetX()` will return 10, 20, 30, ..., is\nto explicitly say that the expectations are *not* sticky. In other words, they\nshould *retire* as soon as they are saturated:\n\n```cpp\nusing ::testing::Return;\n...\nfor (int i = n; i > 0; i--) {\n  EXPECT_CALL(turtle, GetX())\n      .WillOnce(Return(10*i))\n      .RetiresOnSaturation();\n}\n```\n\nAnd, there's a better way to do it: in this case, we expect the calls to occur\nin a specific order, and we line up the actions to match the order. Since the\norder is important here, we should make it explicit using a sequence:\n\n```cpp\nusing ::testing::InSequence;\nusing ::testing::Return;\n...\n{\n  InSequence s;\n\n  for (int i = 1; i <= n; i++) {\n    EXPECT_CALL(turtle, GetX())\n        .WillOnce(Return(10*i))\n        .RetiresOnSaturation();\n  }\n}\n```\n\nBy the way, the other situation where an expectation may *not* be sticky is when\nit's in a sequence - as soon as another expectation that comes after it in the\nsequence has been used, it automatically retires (and will never be used to\nmatch any call).\n\n### Uninteresting Calls\n\nA mock object may have many methods, and not all of them are that interesting.\nFor example, in some tests we may not care about how many times `GetX()` and\n`GetY()` get called.\n\nIn gMock, if you are not interested in a method, just don't say anything about\nit. If a call to this method occurs, you'll see a warning in the test output,\nbut it won't be a failure. This is called \"naggy\" behavior; to change, see\n[The Nice, the Strict, and the Naggy](gmock_cook_book.md#NiceStrictNaggy).\n"
  },
  {
    "path": "3rd/googletest-1.12.1/docs/index.md",
    "content": "# GoogleTest User's Guide\n\n## Welcome to GoogleTest!\n\nGoogleTest is Google's C++ testing and mocking framework. This user's guide has\nthe following contents:\n\n*   [GoogleTest Primer](primer.md) - Teaches you how to write simple tests using\n    GoogleTest. Read this first if you are new to GoogleTest.\n*   [GoogleTest Advanced](advanced.md) - Read this when you've finished the\n    Primer and want to utilize GoogleTest to its full potential.\n*   [GoogleTest Samples](samples.md) - Describes some GoogleTest samples.\n*   [GoogleTest FAQ](faq.md) - Have a question? Want some tips? Check here\n    first.\n*   [Mocking for Dummies](gmock_for_dummies.md) - Teaches you how to create mock\n    objects and use them in tests.\n*   [Mocking Cookbook](gmock_cook_book.md) - Includes tips and approaches to\n    common mocking use cases.\n*   [Mocking Cheat Sheet](gmock_cheat_sheet.md) - A handy reference for\n    matchers, actions, invariants, and more.\n*   [Mocking FAQ](gmock_faq.md) - Contains answers to some mocking-specific\n    questions.\n"
  },
  {
    "path": "3rd/googletest-1.12.1/docs/pkgconfig.md",
    "content": "## Using GoogleTest from various build systems\n\nGoogleTest comes with pkg-config files that can be used to determine all\nnecessary flags for compiling and linking to GoogleTest (and GoogleMock).\nPkg-config is a standardised plain-text format containing\n\n*   the includedir (-I) path\n*   necessary macro (-D) definitions\n*   further required flags (-pthread)\n*   the library (-L) path\n*   the library (-l) to link to\n\nAll current build systems support pkg-config in one way or another. For all\nexamples here we assume you want to compile the sample\n`samples/sample3_unittest.cc`.\n\n### CMake\n\nUsing `pkg-config` in CMake is fairly easy:\n\n```cmake\ncmake_minimum_required(VERSION 3.0)\n\ncmake_policy(SET CMP0048 NEW)\nproject(my_gtest_pkgconfig VERSION 0.0.1 LANGUAGES CXX)\n\nfind_package(PkgConfig)\npkg_search_module(GTEST REQUIRED gtest_main)\n\nadd_executable(testapp samples/sample3_unittest.cc)\ntarget_link_libraries(testapp ${GTEST_LDFLAGS})\ntarget_compile_options(testapp PUBLIC ${GTEST_CFLAGS})\n\ninclude(CTest)\nadd_test(first_and_only_test testapp)\n```\n\nIt is generally recommended that you use `target_compile_options` + `_CFLAGS`\nover `target_include_directories` + `_INCLUDE_DIRS` as the former includes not\njust -I flags (GoogleTest might require a macro indicating to internal headers\nthat all libraries have been compiled with threading enabled. In addition,\nGoogleTest might also require `-pthread` in the compiling step, and as such\nsplitting the pkg-config `Cflags` variable into include dirs and macros for\n`target_compile_definitions()` might still miss this). The same recommendation\ngoes for using `_LDFLAGS` over the more commonplace `_LIBRARIES`, which happens\nto discard `-L` flags and `-pthread`.\n\n### Help! pkg-config can't find GoogleTest!\n\nLet's say you have a `CMakeLists.txt` along the lines of the one in this\ntutorial and you try to run `cmake`. It is very possible that you get a failure\nalong the lines of:\n\n```\n-- Checking for one of the modules 'gtest_main'\nCMake Error at /usr/share/cmake/Modules/FindPkgConfig.cmake:640 (message):\n  None of the required 'gtest_main' found\n```\n\nThese failures are common if you installed GoogleTest yourself and have not\nsourced it from a distro or other package manager. If so, you need to tell\npkg-config where it can find the `.pc` files containing the information. Say you\ninstalled GoogleTest to `/usr/local`, then it might be that the `.pc` files are\ninstalled under `/usr/local/lib64/pkgconfig`. If you set\n\n```\nexport PKG_CONFIG_PATH=/usr/local/lib64/pkgconfig\n```\n\npkg-config will also try to look in `PKG_CONFIG_PATH` to find `gtest_main.pc`.\n\n### Using pkg-config in a cross-compilation setting\n\nPkg-config can be used in a cross-compilation setting too. To do this, let's\nassume the final prefix of the cross-compiled installation will be `/usr`, and\nyour sysroot is `/home/MYUSER/sysroot`. Configure and install GTest using\n\n```\nmkdir build && cmake -DCMAKE_INSTALL_PREFIX=/usr ..\n```\n\nInstall into the sysroot using `DESTDIR`:\n\n```\nmake -j install DESTDIR=/home/MYUSER/sysroot\n```\n\nBefore we continue, it is recommended to **always** define the following two\nvariables for pkg-config in a cross-compilation setting:\n\n```\nexport PKG_CONFIG_ALLOW_SYSTEM_CFLAGS=yes\nexport PKG_CONFIG_ALLOW_SYSTEM_LIBS=yes\n```\n\notherwise `pkg-config` will filter `-I` and `-L` flags against standard prefixes\nsuch as `/usr` (see https://bugs.freedesktop.org/show_bug.cgi?id=28264#c3 for\nreasons why this stripping needs to occur usually).\n\nIf you look at the generated pkg-config file, it will look something like\n\n```\nlibdir=/usr/lib64\nincludedir=/usr/include\n\nName: gtest\nDescription: GoogleTest (without main() function)\nVersion: 1.11.0\nURL: https://github.com/google/googletest\nLibs: -L${libdir} -lgtest -lpthread\nCflags: -I${includedir} -DGTEST_HAS_PTHREAD=1 -lpthread\n```\n\nNotice that the sysroot is not included in `libdir` and `includedir`! If you try\nto run `pkg-config` with the correct\n`PKG_CONFIG_LIBDIR=/home/MYUSER/sysroot/usr/lib64/pkgconfig` against this `.pc`\nfile, you will get\n\n```\n$ pkg-config --cflags gtest\n-DGTEST_HAS_PTHREAD=1 -lpthread -I/usr/include\n$ pkg-config --libs gtest\n-L/usr/lib64 -lgtest -lpthread\n```\n\nwhich is obviously wrong and points to the `CBUILD` and not `CHOST` root. In\norder to use this in a cross-compilation setting, we need to tell pkg-config to\ninject the actual sysroot into `-I` and `-L` variables. Let us now tell\npkg-config about the actual sysroot\n\n```\nexport PKG_CONFIG_DIR=\nexport PKG_CONFIG_SYSROOT_DIR=/home/MYUSER/sysroot\nexport PKG_CONFIG_LIBDIR=${PKG_CONFIG_SYSROOT_DIR}/usr/lib64/pkgconfig\n```\n\nand running `pkg-config` again we get\n\n```\n$ pkg-config --cflags gtest\n-DGTEST_HAS_PTHREAD=1 -lpthread -I/home/MYUSER/sysroot/usr/include\n$ pkg-config --libs gtest\n-L/home/MYUSER/sysroot/usr/lib64 -lgtest -lpthread\n```\n\nwhich contains the correct sysroot now. For a more comprehensive guide to also\nincluding `${CHOST}` in build system calls, see the excellent tutorial by Diego\nElio Pettenò: <https://autotools.io/pkgconfig/cross-compiling.html>\n"
  },
  {
    "path": "3rd/googletest-1.12.1/docs/platforms.md",
    "content": "# Supported Platforms\n\nGoogleTest requires a codebase and compiler compliant with the C++11 standard or\nnewer.\n\nThe GoogleTest code is officially supported on the following platforms.\nOperating systems or tools not listed below are community-supported. For\ncommunity-supported platforms, patches that do not complicate the code may be\nconsidered.\n\nIf you notice any problems on your platform, please file an issue on the\n[GoogleTest GitHub Issue Tracker](https://github.com/google/googletest/issues).\nPull requests containing fixes are welcome!\n\n### Operating systems\n\n*   Linux\n*   macOS\n*   Windows\n\n### Compilers\n\n*   gcc 5.0+\n*   clang 5.0+\n*   MSVC 2015+\n\n**macOS users:** Xcode 9.3+ provides clang 5.0+.\n\n### Build systems\n\n*   [Bazel](https://bazel.build/)\n*   [CMake](https://cmake.org/)\n\nBazel is the build system used by the team internally and in tests. CMake is\nsupported on a best-effort basis and by the community.\n"
  },
  {
    "path": "3rd/googletest-1.12.1/docs/primer.md",
    "content": "# Googletest Primer\n\n## Introduction: Why googletest?\n\n*googletest* helps you write better C++ tests.\n\ngoogletest is a testing framework developed by the Testing Technology team with\nGoogle's specific requirements and constraints in mind. Whether you work on\nLinux, Windows, or a Mac, if you write C++ code, googletest can help you. And it\nsupports *any* kind of tests, not just unit tests.\n\nSo what makes a good test, and how does googletest fit in? We believe:\n\n1.  Tests should be *independent* and *repeatable*. It's a pain to debug a test\n    that succeeds or fails as a result of other tests. googletest isolates the\n    tests by running each of them on a different object. When a test fails,\n    googletest allows you to run it in isolation for quick debugging.\n2.  Tests should be well *organized* and reflect the structure of the tested\n    code. googletest groups related tests into test suites that can share data\n    and subroutines. This common pattern is easy to recognize and makes tests\n    easy to maintain. Such consistency is especially helpful when people switch\n    projects and start to work on a new code base.\n3.  Tests should be *portable* and *reusable*. Google has a lot of code that is\n    platform-neutral; its tests should also be platform-neutral. googletest\n    works on different OSes, with different compilers, with or without\n    exceptions, so googletest tests can work with a variety of configurations.\n4.  When tests fail, they should provide as much *information* about the problem\n    as possible. googletest doesn't stop at the first test failure. Instead, it\n    only stops the current test and continues with the next. You can also set up\n    tests that report non-fatal failures after which the current test continues.\n    Thus, you can detect and fix multiple bugs in a single run-edit-compile\n    cycle.\n5.  The testing framework should liberate test writers from housekeeping chores\n    and let them focus on the test *content*. googletest automatically keeps\n    track of all tests defined, and doesn't require the user to enumerate them\n    in order to run them.\n6.  Tests should be *fast*. With googletest, you can reuse shared resources\n    across tests and pay for the set-up/tear-down only once, without making\n    tests depend on each other.\n\nSince googletest is based on the popular xUnit architecture, you'll feel right\nat home if you've used JUnit or PyUnit before. If not, it will take you about 10\nminutes to learn the basics and get started. So let's go!\n\n## Beware of the nomenclature\n\n{: .callout .note}\n_Note:_ There might be some confusion arising from different definitions of the\nterms _Test_, _Test Case_ and _Test Suite_, so beware of misunderstanding these.\n\nHistorically, googletest started to use the term _Test Case_ for grouping\nrelated tests, whereas current publications, including International Software\nTesting Qualifications Board ([ISTQB](http://www.istqb.org/)) materials and\nvarious textbooks on software quality, use the term\n_[Test Suite][istqb test suite]_ for this.\n\nThe related term _Test_, as it is used in googletest, corresponds to the term\n_[Test Case][istqb test case]_ of ISTQB and others.\n\nThe term _Test_ is commonly of broad enough sense, including ISTQB's definition\nof _Test Case_, so it's not much of a problem here. But the term _Test Case_ as\nwas used in Google Test is of contradictory sense and thus confusing.\n\ngoogletest recently started replacing the term _Test Case_ with _Test Suite_.\nThe preferred API is *TestSuite*. The older TestCase API is being slowly\ndeprecated and refactored away.\n\nSo please be aware of the different definitions of the terms:\n\n\nMeaning                                                                              | googletest Term         | [ISTQB](http://www.istqb.org/) Term\n:----------------------------------------------------------------------------------- | :---------------------- | :----------------------------------\nExercise a particular program path with specific input values and verify the results | [TEST()](#simple-tests) | [Test Case][istqb test case]\n\n\n[istqb test case]: http://glossary.istqb.org/en/search/test%20case\n[istqb test suite]: http://glossary.istqb.org/en/search/test%20suite\n\n## Basic Concepts\n\nWhen using googletest, you start by writing *assertions*, which are statements\nthat check whether a condition is true. An assertion's result can be *success*,\n*nonfatal failure*, or *fatal failure*. If a fatal failure occurs, it aborts the\ncurrent function; otherwise the program continues normally.\n\n*Tests* use assertions to verify the tested code's behavior. If a test crashes\nor has a failed assertion, then it *fails*; otherwise it *succeeds*.\n\nA *test suite* contains one or many tests. You should group your tests into test\nsuites that reflect the structure of the tested code. When multiple tests in a\ntest suite need to share common objects and subroutines, you can put them into a\n*test fixture* class.\n\nA *test program* can contain multiple test suites.\n\nWe'll now explain how to write a test program, starting at the individual\nassertion level and building up to tests and test suites.\n\n## Assertions\n\ngoogletest assertions are macros that resemble function calls. You test a class\nor function by making assertions about its behavior. When an assertion fails,\ngoogletest prints the assertion's source file and line number location, along\nwith a failure message. You may also supply a custom failure message which will\nbe appended to googletest's message.\n\nThe assertions come in pairs that test the same thing but have different effects\non the current function. `ASSERT_*` versions generate fatal failures when they\nfail, and **abort the current function**. `EXPECT_*` versions generate nonfatal\nfailures, which don't abort the current function. Usually `EXPECT_*` are\npreferred, as they allow more than one failure to be reported in a test.\nHowever, you should use `ASSERT_*` if it doesn't make sense to continue when the\nassertion in question fails.\n\nSince a failed `ASSERT_*` returns from the current function immediately,\npossibly skipping clean-up code that comes after it, it may cause a space leak.\nDepending on the nature of the leak, it may or may not be worth fixing - so keep\nthis in mind if you get a heap checker error in addition to assertion errors.\n\nTo provide a custom failure message, simply stream it into the macro using the\n`<<` operator or a sequence of such operators. See the following example, using\nthe [`ASSERT_EQ` and `EXPECT_EQ`](reference/assertions.md#EXPECT_EQ) macros to\nverify value equality:\n\n```c++\nASSERT_EQ(x.size(), y.size()) << \"Vectors x and y are of unequal length\";\n\nfor (int i = 0; i < x.size(); ++i) {\n  EXPECT_EQ(x[i], y[i]) << \"Vectors x and y differ at index \" << i;\n}\n```\n\nAnything that can be streamed to an `ostream` can be streamed to an assertion\nmacro--in particular, C strings and `string` objects. If a wide string\n(`wchar_t*`, `TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is\nstreamed to an assertion, it will be translated to UTF-8 when printed.\n\nGoogleTest provides a collection of assertions for verifying the behavior of\nyour code in various ways. You can check Boolean conditions, compare values\nbased on relational operators, verify string values, floating-point values, and\nmuch more. There are even assertions that enable you to verify more complex\nstates by providing custom predicates. For the complete list of assertions\nprovided by GoogleTest, see the [Assertions Reference](reference/assertions.md).\n\n## Simple Tests\n\nTo create a test:\n\n1.  Use the `TEST()` macro to define and name a test function. These are\n    ordinary C++ functions that don't return a value.\n2.  In this function, along with any valid C++ statements you want to include,\n    use the various googletest assertions to check values.\n3.  The test's result is determined by the assertions; if any assertion in the\n    test fails (either fatally or non-fatally), or if the test crashes, the\n    entire test fails. Otherwise, it succeeds.\n\n```c++\nTEST(TestSuiteName, TestName) {\n  ... test body ...\n}\n```\n\n`TEST()` arguments go from general to specific. The *first* argument is the name\nof the test suite, and the *second* argument is the test's name within the test\nsuite. Both names must be valid C++ identifiers, and they should not contain any\nunderscores (`_`). A test's *full name* consists of its containing test suite\nand its individual name. Tests from different test suites can have the same\nindividual name.\n\nFor example, let's take a simple integer function:\n\n```c++\nint Factorial(int n);  // Returns the factorial of n\n```\n\nA test suite for this function might look like:\n\n```c++\n// Tests factorial of 0.\nTEST(FactorialTest, HandlesZeroInput) {\n  EXPECT_EQ(Factorial(0), 1);\n}\n\n// Tests factorial of positive numbers.\nTEST(FactorialTest, HandlesPositiveInput) {\n  EXPECT_EQ(Factorial(1), 1);\n  EXPECT_EQ(Factorial(2), 2);\n  EXPECT_EQ(Factorial(3), 6);\n  EXPECT_EQ(Factorial(8), 40320);\n}\n```\n\ngoogletest groups the test results by test suites, so logically related tests\nshould be in the same test suite; in other words, the first argument to their\n`TEST()` should be the same. In the above example, we have two tests,\n`HandlesZeroInput` and `HandlesPositiveInput`, that belong to the same test\nsuite `FactorialTest`.\n\nWhen naming your test suites and tests, you should follow the same convention as\nfor\n[naming functions and classes](https://google.github.io/styleguide/cppguide.html#Function_Names).\n\n**Availability**: Linux, Windows, Mac.\n\n## Test Fixtures: Using the Same Data Configuration for Multiple Tests {#same-data-multiple-tests}\n\nIf you find yourself writing two or more tests that operate on similar data, you\ncan use a *test fixture*. This allows you to reuse the same configuration of\nobjects for several different tests.\n\nTo create a fixture:\n\n1.  Derive a class from `::testing::Test` . Start its body with `protected:`, as\n    we'll want to access fixture members from sub-classes.\n2.  Inside the class, declare any objects you plan to use.\n3.  If necessary, write a default constructor or `SetUp()` function to prepare\n    the objects for each test. A common mistake is to spell `SetUp()` as\n    **`Setup()`** with a small `u` - Use `override` in C++11 to make sure you\n    spelled it correctly.\n4.  If necessary, write a destructor or `TearDown()` function to release any\n    resources you allocated in `SetUp()` . To learn when you should use the\n    constructor/destructor and when you should use `SetUp()/TearDown()`, read\n    the [FAQ](faq.md#CtorVsSetUp).\n5.  If needed, define subroutines for your tests to share.\n\nWhen using a fixture, use `TEST_F()` instead of `TEST()` as it allows you to\naccess objects and subroutines in the test fixture:\n\n```c++\nTEST_F(TestFixtureName, TestName) {\n  ... test body ...\n}\n```\n\nLike `TEST()`, the first argument is the test suite name, but for `TEST_F()`\nthis must be the name of the test fixture class. You've probably guessed: `_F`\nis for fixture.\n\nUnfortunately, the C++ macro system does not allow us to create a single macro\nthat can handle both types of tests. Using the wrong macro causes a compiler\nerror.\n\nAlso, you must first define a test fixture class before using it in a\n`TEST_F()`, or you'll get the compiler error \"`virtual outside class\ndeclaration`\".\n\nFor each test defined with `TEST_F()`, googletest will create a *fresh* test\nfixture at runtime, immediately initialize it via `SetUp()`, run the test, clean\nup by calling `TearDown()`, and then delete the test fixture. Note that\ndifferent tests in the same test suite have different test fixture objects, and\ngoogletest always deletes a test fixture before it creates the next one.\ngoogletest does **not** reuse the same test fixture for multiple tests. Any\nchanges one test makes to the fixture do not affect other tests.\n\nAs an example, let's write tests for a FIFO queue class named `Queue`, which has\nthe following interface:\n\n```c++\ntemplate <typename E>  // E is the element type.\nclass Queue {\n public:\n  Queue();\n  void Enqueue(const E& element);\n  E* Dequeue();  // Returns NULL if the queue is empty.\n  size_t size() const;\n  ...\n};\n```\n\nFirst, define a fixture class. By convention, you should give it the name\n`FooTest` where `Foo` is the class being tested.\n\n```c++\nclass QueueTest : public ::testing::Test {\n protected:\n  void SetUp() override {\n     q1_.Enqueue(1);\n     q2_.Enqueue(2);\n     q2_.Enqueue(3);\n  }\n\n  // void TearDown() override {}\n\n  Queue<int> q0_;\n  Queue<int> q1_;\n  Queue<int> q2_;\n};\n```\n\nIn this case, `TearDown()` is not needed since we don't have to clean up after\neach test, other than what's already done by the destructor.\n\nNow we'll write tests using `TEST_F()` and this fixture.\n\n```c++\nTEST_F(QueueTest, IsEmptyInitially) {\n  EXPECT_EQ(q0_.size(), 0);\n}\n\nTEST_F(QueueTest, DequeueWorks) {\n  int* n = q0_.Dequeue();\n  EXPECT_EQ(n, nullptr);\n\n  n = q1_.Dequeue();\n  ASSERT_NE(n, nullptr);\n  EXPECT_EQ(*n, 1);\n  EXPECT_EQ(q1_.size(), 0);\n  delete n;\n\n  n = q2_.Dequeue();\n  ASSERT_NE(n, nullptr);\n  EXPECT_EQ(*n, 2);\n  EXPECT_EQ(q2_.size(), 1);\n  delete n;\n}\n```\n\nThe above uses both `ASSERT_*` and `EXPECT_*` assertions. The rule of thumb is\nto use `EXPECT_*` when you want the test to continue to reveal more errors after\nthe assertion failure, and use `ASSERT_*` when continuing after failure doesn't\nmake sense. For example, the second assertion in the `Dequeue` test is\n`ASSERT_NE(n, nullptr)`, as we need to dereference the pointer `n` later, which\nwould lead to a segfault when `n` is `NULL`.\n\nWhen these tests run, the following happens:\n\n1.  googletest constructs a `QueueTest` object (let's call it `t1`).\n2.  `t1.SetUp()` initializes `t1`.\n3.  The first test (`IsEmptyInitially`) runs on `t1`.\n4.  `t1.TearDown()` cleans up after the test finishes.\n5.  `t1` is destructed.\n6.  The above steps are repeated on another `QueueTest` object, this time\n    running the `DequeueWorks` test.\n\n**Availability**: Linux, Windows, Mac.\n\n## Invoking the Tests\n\n`TEST()` and `TEST_F()` implicitly register their tests with googletest. So,\nunlike with many other C++ testing frameworks, you don't have to re-list all\nyour defined tests in order to run them.\n\nAfter defining your tests, you can run them with `RUN_ALL_TESTS()`, which\nreturns `0` if all the tests are successful, or `1` otherwise. Note that\n`RUN_ALL_TESTS()` runs *all tests* in your link unit--they can be from different\ntest suites, or even different source files.\n\nWhen invoked, the `RUN_ALL_TESTS()` macro:\n\n*   Saves the state of all googletest flags.\n\n*   Creates a test fixture object for the first test.\n\n*   Initializes it via `SetUp()`.\n\n*   Runs the test on the fixture object.\n\n*   Cleans up the fixture via `TearDown()`.\n\n*   Deletes the fixture.\n\n*   Restores the state of all googletest flags.\n\n*   Repeats the above steps for the next test, until all tests have run.\n\nIf a fatal failure happens the subsequent steps will be skipped.\n\n{: .callout .important}\n> IMPORTANT: You must **not** ignore the return value of `RUN_ALL_TESTS()`, or\n> you will get a compiler error. The rationale for this design is that the\n> automated testing service determines whether a test has passed based on its\n> exit code, not on its stdout/stderr output; thus your `main()` function must\n> return the value of `RUN_ALL_TESTS()`.\n>\n> Also, you should call `RUN_ALL_TESTS()` only **once**. Calling it more than\n> once conflicts with some advanced googletest features (e.g., thread-safe\n> [death tests](advanced.md#death-tests)) and thus is not supported.\n\n**Availability**: Linux, Windows, Mac.\n\n## Writing the main() Function\n\nMost users should _not_ need to write their own `main` function and instead link\nwith `gtest_main` (as opposed to with `gtest`), which defines a suitable entry\npoint. See the end of this section for details. The remainder of this section\nshould only apply when you need to do something custom before the tests run that\ncannot be expressed within the framework of fixtures and test suites.\n\nIf you write your own `main` function, it should return the value of\n`RUN_ALL_TESTS()`.\n\nYou can start from this boilerplate:\n\n```c++\n#include \"this/package/foo.h\"\n\n#include \"gtest/gtest.h\"\n\nnamespace my {\nnamespace project {\nnamespace {\n\n// The fixture for testing class Foo.\nclass FooTest : public ::testing::Test {\n protected:\n  // You can remove any or all of the following functions if their bodies would\n  // be empty.\n\n  FooTest() {\n     // You can do set-up work for each test here.\n  }\n\n  ~FooTest() override {\n     // You can do clean-up work that doesn't throw exceptions here.\n  }\n\n  // If the constructor and destructor are not enough for setting up\n  // and cleaning up each test, you can define the following methods:\n\n  void SetUp() override {\n     // Code here will be called immediately after the constructor (right\n     // before each test).\n  }\n\n  void TearDown() override {\n     // Code here will be called immediately after each test (right\n     // before the destructor).\n  }\n\n  // Class members declared here can be used by all tests in the test suite\n  // for Foo.\n};\n\n// Tests that the Foo::Bar() method does Abc.\nTEST_F(FooTest, MethodBarDoesAbc) {\n  const std::string input_filepath = \"this/package/testdata/myinputfile.dat\";\n  const std::string output_filepath = \"this/package/testdata/myoutputfile.dat\";\n  Foo f;\n  EXPECT_EQ(f.Bar(input_filepath, output_filepath), 0);\n}\n\n// Tests that Foo does Xyz.\nTEST_F(FooTest, DoesXyz) {\n  // Exercises the Xyz feature of Foo.\n}\n\n}  // namespace\n}  // namespace project\n}  // namespace my\n\nint main(int argc, char **argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n```\n\nThe `::testing::InitGoogleTest()` function parses the command line for\ngoogletest flags, and removes all recognized flags. This allows the user to\ncontrol a test program's behavior via various flags, which we'll cover in the\n[AdvancedGuide](advanced.md). You **must** call this function before calling\n`RUN_ALL_TESTS()`, or the flags won't be properly initialized.\n\nOn Windows, `InitGoogleTest()` also works with wide strings, so it can be used\nin programs compiled in `UNICODE` mode as well.\n\nBut maybe you think that writing all those `main` functions is too much work? We\nagree with you completely, and that's why Google Test provides a basic\nimplementation of main(). If it fits your needs, then just link your test with\nthe `gtest_main` library and you are good to go.\n\n{: .callout .note}\nNOTE: `ParseGUnitFlags()` is deprecated in favor of `InitGoogleTest()`.\n\n## Known Limitations\n\n*   Google Test is designed to be thread-safe. The implementation is thread-safe\n    on systems where the `pthreads` library is available. It is currently\n    _unsafe_ to use Google Test assertions from two threads concurrently on\n    other systems (e.g. Windows). In most tests this is not an issue as usually\n    the assertions are done in the main thread. If you want to help, you can\n    volunteer to implement the necessary synchronization primitives in\n    `gtest-port.h` for your platform.\n"
  },
  {
    "path": "3rd/googletest-1.12.1/docs/quickstart-bazel.md",
    "content": "# Quickstart: Building with Bazel\n\nThis tutorial aims to get you up and running with GoogleTest using the Bazel\nbuild system. If you're using GoogleTest for the first time or need a refresher,\nwe recommend this tutorial as a starting point.\n\n## Prerequisites\n\nTo complete this tutorial, you'll need:\n\n*   A compatible operating system (e.g. Linux, macOS, Windows).\n*   A compatible C++ compiler that supports at least C++11.\n*   [Bazel](https://bazel.build/), the preferred build system used by the\n    GoogleTest team.\n\nSee [Supported Platforms](platforms.md) for more information about platforms\ncompatible with GoogleTest.\n\nIf you don't already have Bazel installed, see the\n[Bazel installation guide](https://docs.bazel.build/versions/main/install.html).\n\n{: .callout .note}\nNote: The terminal commands in this tutorial show a Unix shell prompt, but the\ncommands work on the Windows command line as well.\n\n## Set up a Bazel workspace\n\nA\n[Bazel workspace](https://docs.bazel.build/versions/main/build-ref.html#workspace)\nis a directory on your filesystem that you use to manage source files for the\nsoftware you want to build. Each workspace directory has a text file named\n`WORKSPACE` which may be empty, or may contain references to external\ndependencies required to build the outputs.\n\nFirst, create a directory for your workspace:\n\n```\n$ mkdir my_workspace && cd my_workspace\n```\n\nNext, you’ll create the `WORKSPACE` file to specify dependencies. A common and\nrecommended way to depend on GoogleTest is to use a\n[Bazel external dependency](https://docs.bazel.build/versions/main/external.html)\nvia the\n[`http_archive` rule](https://docs.bazel.build/versions/main/repo/http.html#http_archive).\nTo do this, in the root directory of your workspace (`my_workspace/`), create a\nfile named `WORKSPACE` with the following contents:\n\n```\nload(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\n\nhttp_archive(\n  name = \"com_google_googletest\",\n  urls = [\"https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip\"],\n  strip_prefix = \"googletest-609281088cfefc76f9d0ce82e1ff6c30cc3591e5\",\n)\n```\n\nThe above configuration declares a dependency on GoogleTest which is downloaded\nas a ZIP archive from GitHub. In the above example,\n`609281088cfefc76f9d0ce82e1ff6c30cc3591e5` is the Git commit hash of the\nGoogleTest version to use; we recommend updating the hash often to point to the\nlatest version.\n\nNow you're ready to build C++ code that uses GoogleTest.\n\n## Create and run a binary\n\nWith your Bazel workspace set up, you can now use GoogleTest code within your\nown project.\n\nAs an example, create a file named `hello_test.cc` in your `my_workspace`\ndirectory with the following contents:\n\n```cpp\n#include <gtest/gtest.h>\n\n// Demonstrate some basic assertions.\nTEST(HelloTest, BasicAssertions) {\n  // Expect two strings not to be equal.\n  EXPECT_STRNE(\"hello\", \"world\");\n  // Expect equality.\n  EXPECT_EQ(7 * 6, 42);\n}\n```\n\nGoogleTest provides [assertions](primer.md#assertions) that you use to test the\nbehavior of your code. The above sample includes the main GoogleTest header file\nand demonstrates some basic assertions.\n\nTo build the code, create a file named `BUILD` in the same directory with the\nfollowing contents:\n\n```\ncc_test(\n  name = \"hello_test\",\n  size = \"small\",\n  srcs = [\"hello_test.cc\"],\n  deps = [\"@com_google_googletest//:gtest_main\"],\n)\n```\n\nThis `cc_test` rule declares the C++ test binary you want to build, and links to\nGoogleTest (`//:gtest_main`) using the prefix you specified in the `WORKSPACE`\nfile (`@com_google_googletest`). For more information about Bazel `BUILD` files,\nsee the\n[Bazel C++ Tutorial](https://docs.bazel.build/versions/main/tutorial/cpp.html).\n\nNow you can build and run your test:\n\n<pre>\n<strong>my_workspace$ bazel test --test_output=all //:hello_test</strong>\nINFO: Analyzed target //:hello_test (26 packages loaded, 362 targets configured).\nINFO: Found 1 test target...\nINFO: From Testing //:hello_test:\n==================== Test output for //:hello_test:\nRunning main() from gmock_main.cc\n[==========] Running 1 test from 1 test suite.\n[----------] Global test environment set-up.\n[----------] 1 test from HelloTest\n[ RUN      ] HelloTest.BasicAssertions\n[       OK ] HelloTest.BasicAssertions (0 ms)\n[----------] 1 test from HelloTest (0 ms total)\n\n[----------] Global test environment tear-down\n[==========] 1 test from 1 test suite ran. (0 ms total)\n[  PASSED  ] 1 test.\n================================================================================\nTarget //:hello_test up-to-date:\n  bazel-bin/hello_test\nINFO: Elapsed time: 4.190s, Critical Path: 3.05s\nINFO: 27 processes: 8 internal, 19 linux-sandbox.\nINFO: Build completed successfully, 27 total actions\n//:hello_test                                                     PASSED in 0.1s\n\nINFO: Build completed successfully, 27 total actions\n</pre>\n\nCongratulations! You've successfully built and run a test binary using\nGoogleTest.\n\n## Next steps\n\n*   [Check out the Primer](primer.md) to start learning how to write simple\n    tests.\n*   [See the code samples](samples.md) for more examples showing how to use a\n    variety of GoogleTest features.\n"
  },
  {
    "path": "3rd/googletest-1.12.1/docs/quickstart-cmake.md",
    "content": "# Quickstart: Building with CMake\n\nThis tutorial aims to get you up and running with GoogleTest using CMake. If\nyou're using GoogleTest for the first time or need a refresher, we recommend\nthis tutorial as a starting point. If your project uses Bazel, see the\n[Quickstart for Bazel](quickstart-bazel.md) instead.\n\n## Prerequisites\n\nTo complete this tutorial, you'll need:\n\n*   A compatible operating system (e.g. Linux, macOS, Windows).\n*   A compatible C++ compiler that supports at least C++11.\n*   [CMake](https://cmake.org/) and a compatible build tool for building the\n    project.\n    *   Compatible build tools include\n        [Make](https://www.gnu.org/software/make/),\n        [Ninja](https://ninja-build.org/), and others - see\n        [CMake Generators](https://cmake.org/cmake/help/latest/manual/cmake-generators.7.html)\n        for more information.\n\nSee [Supported Platforms](platforms.md) for more information about platforms\ncompatible with GoogleTest.\n\nIf you don't already have CMake installed, see the\n[CMake installation guide](https://cmake.org/install).\n\n{: .callout .note}\nNote: The terminal commands in this tutorial show a Unix shell prompt, but the\ncommands work on the Windows command line as well.\n\n## Set up a project\n\nCMake uses a file named `CMakeLists.txt` to configure the build system for a\nproject. You'll use this file to set up your project and declare a dependency on\nGoogleTest.\n\nFirst, create a directory for your project:\n\n```\n$ mkdir my_project && cd my_project\n```\n\nNext, you'll create the `CMakeLists.txt` file and declare a dependency on\nGoogleTest. There are many ways to express dependencies in the CMake ecosystem;\nin this quickstart, you'll use the\n[`FetchContent` CMake module](https://cmake.org/cmake/help/latest/module/FetchContent.html).\nTo do this, in your project directory (`my_project`), create a file named\n`CMakeLists.txt` with the following contents:\n\n```cmake\ncmake_minimum_required(VERSION 3.14)\nproject(my_project)\n\n# GoogleTest requires at least C++11\nset(CMAKE_CXX_STANDARD 11)\n\ninclude(FetchContent)\nFetchContent_Declare(\n  googletest\n  URL https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip\n)\n# For Windows: Prevent overriding the parent project's compiler/linker settings\nset(gtest_force_shared_crt ON CACHE BOOL \"\" FORCE)\nFetchContent_MakeAvailable(googletest)\n```\n\nThe above configuration declares a dependency on GoogleTest which is downloaded\nfrom GitHub. In the above example, `609281088cfefc76f9d0ce82e1ff6c30cc3591e5` is\nthe Git commit hash of the GoogleTest version to use; we recommend updating the\nhash often to point to the latest version.\n\nFor more information about how to create `CMakeLists.txt` files, see the\n[CMake Tutorial](https://cmake.org/cmake/help/latest/guide/tutorial/index.html).\n\n## Create and run a binary\n\nWith GoogleTest declared as a dependency, you can use GoogleTest code within\nyour own project.\n\nAs an example, create a file named `hello_test.cc` in your `my_project`\ndirectory with the following contents:\n\n```cpp\n#include <gtest/gtest.h>\n\n// Demonstrate some basic assertions.\nTEST(HelloTest, BasicAssertions) {\n  // Expect two strings not to be equal.\n  EXPECT_STRNE(\"hello\", \"world\");\n  // Expect equality.\n  EXPECT_EQ(7 * 6, 42);\n}\n```\n\nGoogleTest provides [assertions](primer.md#assertions) that you use to test the\nbehavior of your code. The above sample includes the main GoogleTest header file\nand demonstrates some basic assertions.\n\nTo build the code, add the following to the end of your `CMakeLists.txt` file:\n\n```cmake\nenable_testing()\n\nadd_executable(\n  hello_test\n  hello_test.cc\n)\ntarget_link_libraries(\n  hello_test\n  gtest_main\n)\n\ninclude(GoogleTest)\ngtest_discover_tests(hello_test)\n```\n\nThe above configuration enables testing in CMake, declares the C++ test binary\nyou want to build (`hello_test`), and links it to GoogleTest (`gtest_main`). The\nlast two lines enable CMake's test runner to discover the tests included in the\nbinary, using the\n[`GoogleTest` CMake module](https://cmake.org/cmake/help/git-stage/module/GoogleTest.html).\n\nNow you can build and run your test:\n\n<pre>\n<strong>my_project$ cmake -S . -B build</strong>\n-- The C compiler identification is GNU 10.2.1\n-- The CXX compiler identification is GNU 10.2.1\n...\n-- Build files have been written to: .../my_project/build\n\n<strong>my_project$ cmake --build build</strong>\nScanning dependencies of target gtest\n...\n[100%] Built target gmock_main\n\n<strong>my_project$ cd build && ctest</strong>\nTest project .../my_project/build\n    Start 1: HelloTest.BasicAssertions\n1/1 Test #1: HelloTest.BasicAssertions ........   Passed    0.00 sec\n\n100% tests passed, 0 tests failed out of 1\n\nTotal Test time (real) =   0.01 sec\n</pre>\n\nCongratulations! You've successfully built and run a test binary using\nGoogleTest.\n\n## Next steps\n\n*   [Check out the Primer](primer.md) to start learning how to write simple\n    tests.\n*   [See the code samples](samples.md) for more examples showing how to use a\n    variety of GoogleTest features.\n"
  },
  {
    "path": "3rd/googletest-1.12.1/docs/reference/actions.md",
    "content": "# Actions Reference\n\n[**Actions**](../gmock_for_dummies.md#actions-what-should-it-do) specify what a\nmock function should do when invoked. This page lists the built-in actions\nprovided by GoogleTest. All actions are defined in the `::testing` namespace.\n\n## Returning a Value\n\n| Action                            | Description                                   |\n| :-------------------------------- | :-------------------------------------------- |\n| `Return()`                        | Return from a `void` mock function.           |\n| `Return(value)`                   | Return `value`. If the type of `value` is     different to the mock function's return type, `value` is converted to the latter type <i>at the time the expectation is set</i>, not when the action is executed. |\n| `ReturnArg<N>()`                  | Return the `N`-th (0-based) argument.         |\n| `ReturnNew<T>(a1, ..., ak)`       | Return `new T(a1, ..., ak)`; a different      object is created each time. |\n| `ReturnNull()`                    | Return a null pointer.                        |\n| `ReturnPointee(ptr)`              | Return the value pointed to by `ptr`.         |\n| `ReturnRef(variable)`             | Return a reference to `variable`.             |\n| `ReturnRefOfCopy(value)`          | Return a reference to a copy of `value`; the  copy lives as long as the action. |\n| `ReturnRoundRobin({a1, ..., ak})` | Each call will return the next `ai` in the list, starting at the beginning when the end of the list is reached. |\n\n## Side Effects\n\n| Action                             | Description                             |\n| :--------------------------------- | :-------------------------------------- |\n| `Assign(&variable, value)` | Assign `value` to variable. |\n| `DeleteArg<N>()` | Delete the `N`-th (0-based) argument, which must be a pointer. |\n| `SaveArg<N>(pointer)` | Save the `N`-th (0-based) argument to `*pointer`. |\n| `SaveArgPointee<N>(pointer)` | Save the value pointed to by the `N`-th (0-based) argument to `*pointer`. |\n| `SetArgReferee<N>(value)` | Assign `value` to the variable referenced by the `N`-th (0-based) argument. |\n| `SetArgPointee<N>(value)` | Assign `value` to the variable pointed by the `N`-th (0-based) argument. |\n| `SetArgumentPointee<N>(value)` | Same as `SetArgPointee<N>(value)`. Deprecated. Will be removed in v1.7.0. |\n| `SetArrayArgument<N>(first, last)` | Copies the elements in source range [`first`, `last`) to the array pointed to by the `N`-th (0-based) argument, which can be either a pointer or an iterator. The action does not take ownership of the elements in the source range. |\n| `SetErrnoAndReturn(error, value)` | Set `errno` to `error` and return `value`. |\n| `Throw(exception)` | Throws the given exception, which can be any copyable value. Available since v1.1.0. |\n\n## Using a Function, Functor, or Lambda as an Action\n\nIn the following, by \"callable\" we mean a free function, `std::function`,\nfunctor, or lambda.\n\n| Action                              | Description                            |\n| :---------------------------------- | :------------------------------------- |\n| `f` | Invoke `f` with the arguments passed to the mock function, where `f` is a callable. |\n| `Invoke(f)` | Invoke `f` with the arguments passed to the mock function, where `f` can be a global/static function or a functor. |\n| `Invoke(object_pointer, &class::method)` | Invoke the method on the object with the arguments passed to the mock function. |\n| `InvokeWithoutArgs(f)` | Invoke `f`, which can be a global/static function or a functor. `f` must take no arguments. |\n| `InvokeWithoutArgs(object_pointer, &class::method)` | Invoke the method on the object, which takes no arguments. |\n| `InvokeArgument<N>(arg1, arg2, ..., argk)` | Invoke the mock function's `N`-th (0-based) argument, which must be a function or a functor, with the `k` arguments. |\n\nThe return value of the invoked function is used as the return value of the\naction.\n\nWhen defining a callable to be used with `Invoke*()`, you can declare any unused\nparameters as `Unused`:\n\n```cpp\nusing ::testing::Invoke;\ndouble Distance(Unused, double x, double y) { return sqrt(x*x + y*y); }\n...\nEXPECT_CALL(mock, Foo(\"Hi\", _, _)).WillOnce(Invoke(Distance));\n```\n\n`Invoke(callback)` and `InvokeWithoutArgs(callback)` take ownership of\n`callback`, which must be permanent. The type of `callback` must be a base\ncallback type instead of a derived one, e.g.\n\n```cpp\n  BlockingClosure* done = new BlockingClosure;\n  ... Invoke(done) ...;  // This won't compile!\n\n  Closure* done2 = new BlockingClosure;\n  ... Invoke(done2) ...;  // This works.\n```\n\nIn `InvokeArgument<N>(...)`, if an argument needs to be passed by reference,\nwrap it inside `std::ref()`. For example,\n\n```cpp\nusing ::testing::InvokeArgument;\n...\nInvokeArgument<2>(5, string(\"Hi\"), std::ref(foo))\n```\n\ncalls the mock function's #2 argument, passing to it `5` and `string(\"Hi\")` by\nvalue, and `foo` by reference.\n\n## Default Action\n\n| Action        | Description                                            |\n| :------------ | :----------------------------------------------------- |\n| `DoDefault()` | Do the default action (specified by `ON_CALL()` or the built-in one). |\n\n{: .callout .note}\n**Note:** due to technical reasons, `DoDefault()` cannot be used inside a\ncomposite action - trying to do so will result in a run-time error.\n\n## Composite Actions\n\n| Action                         | Description                                 |\n| :----------------------------- | :------------------------------------------ |\n| `DoAll(a1, a2, ..., an)`       | Do all actions `a1` to `an` and return the result of `an` in each invocation. The first `n - 1` sub-actions must return void and will receive a  readonly view of the arguments. |\n| `IgnoreResult(a)`              | Perform action `a` and ignore its result. `a` must not return void. |\n| `WithArg<N>(a)`                | Pass the `N`-th (0-based) argument of the mock function to action `a` and perform it. |\n| `WithArgs<N1, N2, ..., Nk>(a)` | Pass the selected (0-based) arguments of the mock function to action `a` and perform it. |\n| `WithoutArgs(a)`               | Perform action `a` without any arguments. |\n\n## Defining Actions\n\n| Macro                              | Description                             |\n| :--------------------------------- | :-------------------------------------- |\n| `ACTION(Sum) { return arg0 + arg1; }` | Defines an action `Sum()` to return the sum of the mock function's argument #0 and #1. |\n| `ACTION_P(Plus, n) { return arg0 + n; }` | Defines an action `Plus(n)` to return the sum of the mock function's argument #0 and `n`. |\n| `ACTION_Pk(Foo, p1, ..., pk) { statements; }` | Defines a parameterized action `Foo(p1, ..., pk)` to execute the given `statements`. |\n\nThe `ACTION*` macros cannot be used inside a function or class.\n"
  },
  {
    "path": "3rd/googletest-1.12.1/docs/reference/assertions.md",
    "content": "# Assertions Reference\n\nThis page lists the assertion macros provided by GoogleTest for verifying code\nbehavior. To use them, include the header `gtest/gtest.h`.\n\nThe majority of the macros listed below come as a pair with an `EXPECT_` variant\nand an `ASSERT_` variant. Upon failure, `EXPECT_` macros generate nonfatal\nfailures and allow the current function to continue running, while `ASSERT_`\nmacros generate fatal failures and abort the current function.\n\nAll assertion macros support streaming a custom failure message into them with\nthe `<<` operator, for example:\n\n```cpp\nEXPECT_TRUE(my_condition) << \"My condition is not true\";\n```\n\nAnything that can be streamed to an `ostream` can be streamed to an assertion\nmacro—in particular, C strings and string objects. If a wide string (`wchar_t*`,\n`TCHAR*` in `UNICODE` mode on Windows, or `std::wstring`) is streamed to an\nassertion, it will be translated to UTF-8 when printed.\n\n## Explicit Success and Failure {#success-failure}\n\nThe assertions in this section generate a success or failure directly instead of\ntesting a value or expression. These are useful when control flow, rather than a\nBoolean expression, determines the test's success or failure, as shown by the\nfollowing example:\n\n```c++\nswitch(expression) {\n  case 1:\n    ... some checks ...\n  case 2:\n    ... some other checks ...\n  default:\n    FAIL() << \"We shouldn't get here.\";\n}\n```\n\n### SUCCEED {#SUCCEED}\n\n`SUCCEED()`\n\nGenerates a success. This *does not* make the overall test succeed. A test is\nconsidered successful only if none of its assertions fail during its execution.\n\nThe `SUCCEED` assertion is purely documentary and currently doesn't generate any\nuser-visible output. However, we may add `SUCCEED` messages to GoogleTest output\nin the future.\n\n### FAIL {#FAIL}\n\n`FAIL()`\n\nGenerates a fatal failure, which returns from the current function.\n\nCan only be used in functions that return `void`. See\n[Assertion Placement](../advanced.md#assertion-placement) for more information.\n\n### ADD_FAILURE {#ADD_FAILURE}\n\n`ADD_FAILURE()`\n\nGenerates a nonfatal failure, which allows the current function to continue\nrunning.\n\n### ADD_FAILURE_AT {#ADD_FAILURE_AT}\n\n`ADD_FAILURE_AT(`*`file_path`*`,`*`line_number`*`)`\n\nGenerates a nonfatal failure at the file and line number specified.\n\n## Generalized Assertion {#generalized}\n\nThe following assertion allows [matchers](matchers.md) to be used to verify\nvalues.\n\n### EXPECT_THAT {#EXPECT_THAT}\n\n`EXPECT_THAT(`*`value`*`,`*`matcher`*`)` \\\n`ASSERT_THAT(`*`value`*`,`*`matcher`*`)`\n\nVerifies that *`value`* matches the [matcher](matchers.md) *`matcher`*.\n\nFor example, the following code verifies that the string `value1` starts with\n`\"Hello\"`, `value2` matches a regular expression, and `value3` is between 5 and\n10:\n\n```cpp\n#include \"gmock/gmock.h\"\n\nusing ::testing::AllOf;\nusing ::testing::Gt;\nusing ::testing::Lt;\nusing ::testing::MatchesRegex;\nusing ::testing::StartsWith;\n\n...\nEXPECT_THAT(value1, StartsWith(\"Hello\"));\nEXPECT_THAT(value2, MatchesRegex(\"Line \\\\d+\"));\nASSERT_THAT(value3, AllOf(Gt(5), Lt(10)));\n```\n\nMatchers enable assertions of this form to read like English and generate\ninformative failure messages. For example, if the above assertion on `value1`\nfails, the resulting message will be similar to the following:\n\n```\nValue of: value1\n  Actual: \"Hi, world!\"\nExpected: starts with \"Hello\"\n```\n\nGoogleTest provides a built-in library of matchers—see the\n[Matchers Reference](matchers.md). It is also possible to write your own\nmatchers—see [Writing New Matchers Quickly](../gmock_cook_book.md#NewMatchers).\nThe use of matchers makes `EXPECT_THAT` a powerful, extensible assertion.\n\n*The idea for this assertion was borrowed from Joe Walnes' Hamcrest project,\nwhich adds `assertThat()` to JUnit.*\n\n## Boolean Conditions {#boolean}\n\nThe following assertions test Boolean conditions.\n\n### EXPECT_TRUE {#EXPECT_TRUE}\n\n`EXPECT_TRUE(`*`condition`*`)` \\\n`ASSERT_TRUE(`*`condition`*`)`\n\nVerifies that *`condition`* is true.\n\n### EXPECT_FALSE {#EXPECT_FALSE}\n\n`EXPECT_FALSE(`*`condition`*`)` \\\n`ASSERT_FALSE(`*`condition`*`)`\n\nVerifies that *`condition`* is false.\n\n## Binary Comparison {#binary-comparison}\n\nThe following assertions compare two values. The value arguments must be\ncomparable by the assertion's comparison operator, otherwise a compiler error\nwill result.\n\nIf an argument supports the `<<` operator, it will be called to print the\nargument when the assertion fails. Otherwise, GoogleTest will attempt to print\nthem in the best way it can—see\n[Teaching GoogleTest How to Print Your Values](../advanced.md#teaching-googletest-how-to-print-your-values).\n\nArguments are always evaluated exactly once, so it's OK for the arguments to\nhave side effects. However, the argument evaluation order is undefined and\nprograms should not depend on any particular argument evaluation order.\n\nThese assertions work with both narrow and wide string objects (`string` and\n`wstring`).\n\nSee also the [Floating-Point Comparison](#floating-point) assertions to compare\nfloating-point numbers and avoid problems caused by rounding.\n\n### EXPECT_EQ {#EXPECT_EQ}\n\n`EXPECT_EQ(`*`val1`*`,`*`val2`*`)` \\\n`ASSERT_EQ(`*`val1`*`,`*`val2`*`)`\n\nVerifies that *`val1`*`==`*`val2`*.\n\nDoes pointer equality on pointers. If used on two C strings, it tests if they\nare in the same memory location, not if they have the same value. Use\n[`EXPECT_STREQ`](#EXPECT_STREQ) to compare C strings (e.g. `const char*`) by\nvalue.\n\nWhen comparing a pointer to `NULL`, use `EXPECT_EQ(`*`ptr`*`, nullptr)` instead\nof `EXPECT_EQ(`*`ptr`*`, NULL)`.\n\n### EXPECT_NE {#EXPECT_NE}\n\n`EXPECT_NE(`*`val1`*`,`*`val2`*`)` \\\n`ASSERT_NE(`*`val1`*`,`*`val2`*`)`\n\nVerifies that *`val1`*`!=`*`val2`*.\n\nDoes pointer equality on pointers. If used on two C strings, it tests if they\nare in different memory locations, not if they have different values. Use\n[`EXPECT_STRNE`](#EXPECT_STRNE) to compare C strings (e.g. `const char*`) by\nvalue.\n\nWhen comparing a pointer to `NULL`, use `EXPECT_NE(`*`ptr`*`, nullptr)` instead\nof `EXPECT_NE(`*`ptr`*`, NULL)`.\n\n### EXPECT_LT {#EXPECT_LT}\n\n`EXPECT_LT(`*`val1`*`,`*`val2`*`)` \\\n`ASSERT_LT(`*`val1`*`,`*`val2`*`)`\n\nVerifies that *`val1`*`<`*`val2`*.\n\n### EXPECT_LE {#EXPECT_LE}\n\n`EXPECT_LE(`*`val1`*`,`*`val2`*`)` \\\n`ASSERT_LE(`*`val1`*`,`*`val2`*`)`\n\nVerifies that *`val1`*`<=`*`val2`*.\n\n### EXPECT_GT {#EXPECT_GT}\n\n`EXPECT_GT(`*`val1`*`,`*`val2`*`)` \\\n`ASSERT_GT(`*`val1`*`,`*`val2`*`)`\n\nVerifies that *`val1`*`>`*`val2`*.\n\n### EXPECT_GE {#EXPECT_GE}\n\n`EXPECT_GE(`*`val1`*`,`*`val2`*`)` \\\n`ASSERT_GE(`*`val1`*`,`*`val2`*`)`\n\nVerifies that *`val1`*`>=`*`val2`*.\n\n## String Comparison {#c-strings}\n\nThe following assertions compare two **C strings**. To compare two `string`\nobjects, use [`EXPECT_EQ`](#EXPECT_EQ) or [`EXPECT_NE`](#EXPECT_NE) instead.\n\nThese assertions also accept wide C strings (`wchar_t*`). If a comparison of two\nwide strings fails, their values will be printed as UTF-8 narrow strings.\n\nTo compare a C string with `NULL`, use `EXPECT_EQ(`*`c_string`*`, nullptr)` or\n`EXPECT_NE(`*`c_string`*`, nullptr)`.\n\n### EXPECT_STREQ {#EXPECT_STREQ}\n\n`EXPECT_STREQ(`*`str1`*`,`*`str2`*`)` \\\n`ASSERT_STREQ(`*`str1`*`,`*`str2`*`)`\n\nVerifies that the two C strings *`str1`* and *`str2`* have the same contents.\n\n### EXPECT_STRNE {#EXPECT_STRNE}\n\n`EXPECT_STRNE(`*`str1`*`,`*`str2`*`)` \\\n`ASSERT_STRNE(`*`str1`*`,`*`str2`*`)`\n\nVerifies that the two C strings *`str1`* and *`str2`* have different contents.\n\n### EXPECT_STRCASEEQ {#EXPECT_STRCASEEQ}\n\n`EXPECT_STRCASEEQ(`*`str1`*`,`*`str2`*`)` \\\n`ASSERT_STRCASEEQ(`*`str1`*`,`*`str2`*`)`\n\nVerifies that the two C strings *`str1`* and *`str2`* have the same contents,\nignoring case.\n\n### EXPECT_STRCASENE {#EXPECT_STRCASENE}\n\n`EXPECT_STRCASENE(`*`str1`*`,`*`str2`*`)` \\\n`ASSERT_STRCASENE(`*`str1`*`,`*`str2`*`)`\n\nVerifies that the two C strings *`str1`* and *`str2`* have different contents,\nignoring case.\n\n## Floating-Point Comparison {#floating-point}\n\nThe following assertions compare two floating-point values.\n\nDue to rounding errors, it is very unlikely that two floating-point values will\nmatch exactly, so `EXPECT_EQ` is not suitable. In general, for floating-point\ncomparison to make sense, the user needs to carefully choose the error bound.\n\nGoogleTest also provides assertions that use a default error bound based on\nUnits in the Last Place (ULPs). To learn more about ULPs, see the article\n[Comparing Floating Point Numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).\n\n### EXPECT_FLOAT_EQ {#EXPECT_FLOAT_EQ}\n\n`EXPECT_FLOAT_EQ(`*`val1`*`,`*`val2`*`)` \\\n`ASSERT_FLOAT_EQ(`*`val1`*`,`*`val2`*`)`\n\nVerifies that the two `float` values *`val1`* and *`val2`* are approximately\nequal, to within 4 ULPs from each other.\n\n### EXPECT_DOUBLE_EQ {#EXPECT_DOUBLE_EQ}\n\n`EXPECT_DOUBLE_EQ(`*`val1`*`,`*`val2`*`)` \\\n`ASSERT_DOUBLE_EQ(`*`val1`*`,`*`val2`*`)`\n\nVerifies that the two `double` values *`val1`* and *`val2`* are approximately\nequal, to within 4 ULPs from each other.\n\n### EXPECT_NEAR {#EXPECT_NEAR}\n\n`EXPECT_NEAR(`*`val1`*`,`*`val2`*`,`*`abs_error`*`)` \\\n`ASSERT_NEAR(`*`val1`*`,`*`val2`*`,`*`abs_error`*`)`\n\nVerifies that the difference between *`val1`* and *`val2`* does not exceed the\nabsolute error bound *`abs_error`*.\n\n## Exception Assertions {#exceptions}\n\nThe following assertions verify that a piece of code throws, or does not throw,\nan exception. Usage requires exceptions to be enabled in the build environment.\n\nNote that the piece of code under test can be a compound statement, for example:\n\n```cpp\nEXPECT_NO_THROW({\n  int n = 5;\n  DoSomething(&n);\n});\n```\n\n### EXPECT_THROW {#EXPECT_THROW}\n\n`EXPECT_THROW(`*`statement`*`,`*`exception_type`*`)` \\\n`ASSERT_THROW(`*`statement`*`,`*`exception_type`*`)`\n\nVerifies that *`statement`* throws an exception of type *`exception_type`*.\n\n### EXPECT_ANY_THROW {#EXPECT_ANY_THROW}\n\n`EXPECT_ANY_THROW(`*`statement`*`)` \\\n`ASSERT_ANY_THROW(`*`statement`*`)`\n\nVerifies that *`statement`* throws an exception of any type.\n\n### EXPECT_NO_THROW {#EXPECT_NO_THROW}\n\n`EXPECT_NO_THROW(`*`statement`*`)` \\\n`ASSERT_NO_THROW(`*`statement`*`)`\n\nVerifies that *`statement`* does not throw any exception.\n\n## Predicate Assertions {#predicates}\n\nThe following assertions enable more complex predicates to be verified while\nprinting a more clear failure message than if `EXPECT_TRUE` were used alone.\n\n### EXPECT_PRED* {#EXPECT_PRED}\n\n`EXPECT_PRED1(`*`pred`*`,`*`val1`*`)` \\\n`EXPECT_PRED2(`*`pred`*`,`*`val1`*`,`*`val2`*`)` \\\n`EXPECT_PRED3(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \\\n`EXPECT_PRED4(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` \\\n`EXPECT_PRED5(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)`\n\n`ASSERT_PRED1(`*`pred`*`,`*`val1`*`)` \\\n`ASSERT_PRED2(`*`pred`*`,`*`val1`*`,`*`val2`*`)` \\\n`ASSERT_PRED3(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \\\n`ASSERT_PRED4(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)` \\\n`ASSERT_PRED5(`*`pred`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)`\n\nVerifies that the predicate *`pred`* returns `true` when passed the given values\nas arguments.\n\nThe parameter *`pred`* is a function or functor that accepts as many arguments\nas the corresponding macro accepts values. If *`pred`* returns `true` for the\ngiven arguments, the assertion succeeds, otherwise the assertion fails.\n\nWhen the assertion fails, it prints the value of each argument. Arguments are\nalways evaluated exactly once.\n\nAs an example, see the following code:\n\n```cpp\n// Returns true if m and n have no common divisors except 1.\nbool MutuallyPrime(int m, int n) { ... }\n...\nconst int a = 3;\nconst int b = 4;\nconst int c = 10;\n...\nEXPECT_PRED2(MutuallyPrime, a, b);  // Succeeds\nEXPECT_PRED2(MutuallyPrime, b, c);  // Fails\n```\n\nIn the above example, the first assertion succeeds, and the second fails with\nthe following message:\n\n```\nMutuallyPrime(b, c) is false, where\nb is 4\nc is 10\n```\n\nNote that if the given predicate is an overloaded function or a function\ntemplate, the assertion macro might not be able to determine which version to\nuse, and it might be necessary to explicitly specify the type of the function.\nFor example, for a Boolean function `IsPositive()` overloaded to take either a\nsingle `int` or `double` argument, it would be necessary to write one of the\nfollowing:\n\n```cpp\nEXPECT_PRED1(static_cast<bool (*)(int)>(IsPositive), 5);\nEXPECT_PRED1(static_cast<bool (*)(double)>(IsPositive), 3.14);\n```\n\nWriting simply `EXPECT_PRED1(IsPositive, 5);` would result in a compiler error.\nSimilarly, to use a template function, specify the template arguments:\n\n```cpp\ntemplate <typename T>\nbool IsNegative(T x) {\n  return x < 0;\n}\n...\nEXPECT_PRED1(IsNegative<int>, -5);  // Must specify type for IsNegative\n```\n\nIf a template has multiple parameters, wrap the predicate in parentheses so the\nmacro arguments are parsed correctly:\n\n```cpp\nASSERT_PRED2((MyPredicate<int, int>), 5, 0);\n```\n\n### EXPECT_PRED_FORMAT* {#EXPECT_PRED_FORMAT}\n\n`EXPECT_PRED_FORMAT1(`*`pred_formatter`*`,`*`val1`*`)` \\\n`EXPECT_PRED_FORMAT2(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`)` \\\n`EXPECT_PRED_FORMAT3(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \\\n`EXPECT_PRED_FORMAT4(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)`\n\\\n`EXPECT_PRED_FORMAT5(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)`\n\n`ASSERT_PRED_FORMAT1(`*`pred_formatter`*`,`*`val1`*`)` \\\n`ASSERT_PRED_FORMAT2(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`)` \\\n`ASSERT_PRED_FORMAT3(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`)` \\\n`ASSERT_PRED_FORMAT4(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`)`\n\\\n`ASSERT_PRED_FORMAT5(`*`pred_formatter`*`,`*`val1`*`,`*`val2`*`,`*`val3`*`,`*`val4`*`,`*`val5`*`)`\n\nVerifies that the predicate *`pred_formatter`* succeeds when passed the given\nvalues as arguments.\n\nThe parameter *`pred_formatter`* is a *predicate-formatter*, which is a function\nor functor with the signature:\n\n```cpp\ntesting::AssertionResult PredicateFormatter(const char* expr1,\n                                            const char* expr2,\n                                            ...\n                                            const char* exprn,\n                                            T1 val1,\n                                            T2 val2,\n                                            ...\n                                            Tn valn);\n```\n\nwhere *`val1`*, *`val2`*, ..., *`valn`* are the values of the predicate\narguments, and *`expr1`*, *`expr2`*, ..., *`exprn`* are the corresponding\nexpressions as they appear in the source code. The types `T1`, `T2`, ..., `Tn`\ncan be either value types or reference types; if an argument has type `T`, it\ncan be declared as either `T` or `const T&`, whichever is appropriate. For more\nabout the return type `testing::AssertionResult`, see\n[Using a Function That Returns an AssertionResult](../advanced.md#using-a-function-that-returns-an-assertionresult).\n\nAs an example, see the following code:\n\n```cpp\n// Returns the smallest prime common divisor of m and n,\n// or 1 when m and n are mutually prime.\nint SmallestPrimeCommonDivisor(int m, int n) { ... }\n\n// Returns true if m and n have no common divisors except 1.\nbool MutuallyPrime(int m, int n) { ... }\n\n// A predicate-formatter for asserting that two integers are mutually prime.\ntesting::AssertionResult AssertMutuallyPrime(const char* m_expr,\n                                             const char* n_expr,\n                                             int m,\n                                             int n) {\n  if (MutuallyPrime(m, n)) return testing::AssertionSuccess();\n\n  return testing::AssertionFailure() << m_expr << \" and \" << n_expr\n      << \" (\" << m << \" and \" << n << \") are not mutually prime, \"\n      << \"as they have a common divisor \" << SmallestPrimeCommonDivisor(m, n);\n}\n\n...\nconst int a = 3;\nconst int b = 4;\nconst int c = 10;\n...\nEXPECT_PRED_FORMAT2(AssertMutuallyPrime, a, b);  // Succeeds\nEXPECT_PRED_FORMAT2(AssertMutuallyPrime, b, c);  // Fails\n```\n\nIn the above example, the final assertion fails and the predicate-formatter\nproduces the following failure message:\n\n```\nb and c (4 and 10) are not mutually prime, as they have a common divisor 2\n```\n\n## Windows HRESULT Assertions {#HRESULT}\n\nThe following assertions test for `HRESULT` success or failure. For example:\n\n```cpp\nCComPtr<IShellDispatch2> shell;\nASSERT_HRESULT_SUCCEEDED(shell.CoCreateInstance(L\"Shell.Application\"));\nCComVariant empty;\nASSERT_HRESULT_SUCCEEDED(shell->ShellExecute(CComBSTR(url), empty, empty, empty, empty));\n```\n\nThe generated output contains the human-readable error message associated with\nthe returned `HRESULT` code.\n\n### EXPECT_HRESULT_SUCCEEDED {#EXPECT_HRESULT_SUCCEEDED}\n\n`EXPECT_HRESULT_SUCCEEDED(`*`expression`*`)` \\\n`ASSERT_HRESULT_SUCCEEDED(`*`expression`*`)`\n\nVerifies that *`expression`* is a success `HRESULT`.\n\n### EXPECT_HRESULT_FAILED {#EXPECT_HRESULT_FAILED}\n\n`EXPECT_HRESULT_FAILED(`*`expression`*`)` \\\n`EXPECT_HRESULT_FAILED(`*`expression`*`)`\n\nVerifies that *`expression`* is a failure `HRESULT`.\n\n## Death Assertions {#death}\n\nThe following assertions verify that a piece of code causes the process to\nterminate. For context, see [Death Tests](../advanced.md#death-tests).\n\nThese assertions spawn a new process and execute the code under test in that\nprocess. How that happens depends on the platform and the variable\n`::testing::GTEST_FLAG(death_test_style)`, which is initialized from the\ncommand-line flag `--gtest_death_test_style`.\n\n*   On POSIX systems, `fork()` (or `clone()` on Linux) is used to spawn the\n    child, after which:\n    *   If the variable's value is `\"fast\"`, the death test statement is\n        immediately executed.\n    *   If the variable's value is `\"threadsafe\"`, the child process re-executes\n        the unit test binary just as it was originally invoked, but with some\n        extra flags to cause just the single death test under consideration to\n        be run.\n*   On Windows, the child is spawned using the `CreateProcess()` API, and\n    re-executes the binary to cause just the single death test under\n    consideration to be run - much like the `\"threadsafe\"` mode on POSIX.\n\nOther values for the variable are illegal and will cause the death test to fail.\nCurrently, the flag's default value is\n**`\"fast\"`**.\n\nIf the death test statement runs to completion without dying, the child process\nwill nonetheless terminate, and the assertion fails.\n\nNote that the piece of code under test can be a compound statement, for example:\n\n```cpp\nEXPECT_DEATH({\n  int n = 5;\n  DoSomething(&n);\n}, \"Error on line .* of DoSomething()\");\n```\n\n### EXPECT_DEATH {#EXPECT_DEATH}\n\n`EXPECT_DEATH(`*`statement`*`,`*`matcher`*`)` \\\n`ASSERT_DEATH(`*`statement`*`,`*`matcher`*`)`\n\nVerifies that *`statement`* causes the process to terminate with a nonzero exit\nstatus and produces `stderr` output that matches *`matcher`*.\n\nThe parameter *`matcher`* is either a [matcher](matchers.md) for a `const\nstd::string&`, or a regular expression (see\n[Regular Expression Syntax](../advanced.md#regular-expression-syntax))—a bare\nstring *`s`* (with no matcher) is treated as\n[`ContainsRegex(s)`](matchers.md#string-matchers), **not**\n[`Eq(s)`](matchers.md#generic-comparison).\n\nFor example, the following code verifies that calling `DoSomething(42)` causes\nthe process to die with an error message that contains the text `My error`:\n\n```cpp\nEXPECT_DEATH(DoSomething(42), \"My error\");\n```\n\n### EXPECT_DEATH_IF_SUPPORTED {#EXPECT_DEATH_IF_SUPPORTED}\n\n`EXPECT_DEATH_IF_SUPPORTED(`*`statement`*`,`*`matcher`*`)` \\\n`ASSERT_DEATH_IF_SUPPORTED(`*`statement`*`,`*`matcher`*`)`\n\nIf death tests are supported, behaves the same as\n[`EXPECT_DEATH`](#EXPECT_DEATH). Otherwise, verifies nothing.\n\n### EXPECT_DEBUG_DEATH {#EXPECT_DEBUG_DEATH}\n\n`EXPECT_DEBUG_DEATH(`*`statement`*`,`*`matcher`*`)` \\\n`ASSERT_DEBUG_DEATH(`*`statement`*`,`*`matcher`*`)`\n\nIn debug mode, behaves the same as [`EXPECT_DEATH`](#EXPECT_DEATH). When not in\ndebug mode (i.e. `NDEBUG` is defined), just executes *`statement`*.\n\n### EXPECT_EXIT {#EXPECT_EXIT}\n\n`EXPECT_EXIT(`*`statement`*`,`*`predicate`*`,`*`matcher`*`)` \\\n`ASSERT_EXIT(`*`statement`*`,`*`predicate`*`,`*`matcher`*`)`\n\nVerifies that *`statement`* causes the process to terminate with an exit status\nthat satisfies *`predicate`*, and produces `stderr` output that matches\n*`matcher`*.\n\nThe parameter *`predicate`* is a function or functor that accepts an `int` exit\nstatus and returns a `bool`. GoogleTest provides two predicates to handle common\ncases:\n\n```cpp\n// Returns true if the program exited normally with the given exit status code.\n::testing::ExitedWithCode(exit_code);\n\n// Returns true if the program was killed by the given signal.\n// Not available on Windows.\n::testing::KilledBySignal(signal_number);\n```\n\nThe parameter *`matcher`* is either a [matcher](matchers.md) for a `const\nstd::string&`, or a regular expression (see\n[Regular Expression Syntax](../advanced.md#regular-expression-syntax))—a bare\nstring *`s`* (with no matcher) is treated as\n[`ContainsRegex(s)`](matchers.md#string-matchers), **not**\n[`Eq(s)`](matchers.md#generic-comparison).\n\nFor example, the following code verifies that calling `NormalExit()` causes the\nprocess to print a message containing the text `Success` to `stderr` and exit\nwith exit status code 0:\n\n```cpp\nEXPECT_EXIT(NormalExit(), testing::ExitedWithCode(0), \"Success\");\n```\n"
  },
  {
    "path": "3rd/googletest-1.12.1/docs/reference/matchers.md",
    "content": "# Matchers Reference\n\nA **matcher** matches a *single* argument. You can use it inside `ON_CALL()` or\n`EXPECT_CALL()`, or use it to validate a value directly using two macros:\n\n| Macro                                | Description                           |\n| :----------------------------------- | :------------------------------------ |\n| `EXPECT_THAT(actual_value, matcher)` | Asserts that `actual_value` matches `matcher`. |\n| `ASSERT_THAT(actual_value, matcher)` | The same as `EXPECT_THAT(actual_value, matcher)`, except that it generates a **fatal** failure. |\n\n{: .callout .warning}\n**WARNING:** Equality matching via `EXPECT_THAT(actual_value, expected_value)`\nis supported, however note that implicit conversions can cause surprising\nresults. For example, `EXPECT_THAT(some_bool, \"some string\")` will compile and\nmay pass unintentionally.\n\n**BEST PRACTICE:** Prefer to make the comparison explicit via\n`EXPECT_THAT(actual_value, Eq(expected_value))` or `EXPECT_EQ(actual_value,\nexpected_value)`.\n\nBuilt-in matchers (where `argument` is the function argument, e.g.\n`actual_value` in the example above, or when used in the context of\n`EXPECT_CALL(mock_object, method(matchers))`, the arguments of `method`) are\ndivided into several categories. All matchers are defined in the `::testing`\nnamespace unless otherwise noted.\n\n## Wildcard\n\nMatcher                     | Description\n:-------------------------- | :-----------------------------------------------\n`_`                         | `argument` can be any value of the correct type.\n`A<type>()` or `An<type>()` | `argument` can be any value of type `type`.\n\n## Generic Comparison\n\n| Matcher                | Description                                         |\n| :--------------------- | :-------------------------------------------------- |\n| `Eq(value)` or `value` | `argument == value`                                 |\n| `Ge(value)`            | `argument >= value`                                 |\n| `Gt(value)`            | `argument > value`                                  |\n| `Le(value)`            | `argument <= value`                                 |\n| `Lt(value)`            | `argument < value`                                  |\n| `Ne(value)`            | `argument != value`                                 |\n| `IsFalse()`            | `argument` evaluates to `false` in a Boolean context. |\n| `IsTrue()`             | `argument` evaluates to `true` in a Boolean context. |\n| `IsNull()`             | `argument` is a `NULL` pointer (raw or smart).      |\n| `NotNull()`            | `argument` is a non-null pointer (raw or smart).    |\n| `Optional(m)`          | `argument` is `optional<>` that contains a value matching `m`. (For testing whether an `optional<>` is set, check for equality with `nullopt`. You may need to use `Eq(nullopt)` if the inner type doesn't have `==`.)|\n| `VariantWith<T>(m)`    | `argument` is `variant<>` that holds the alternative of type T with a value matching `m`. |\n| `Ref(variable)`        | `argument` is a reference to `variable`.            |\n| `TypedEq<type>(value)` | `argument` has type `type` and is equal to `value`. You may need to use this instead of `Eq(value)` when the mock function is overloaded. |\n\nExcept `Ref()`, these matchers make a *copy* of `value` in case it's modified or\ndestructed later. If the compiler complains that `value` doesn't have a public\ncopy constructor, try wrap it in `std::ref()`, e.g.\n`Eq(std::ref(non_copyable_value))`. If you do that, make sure\n`non_copyable_value` is not changed afterwards, or the meaning of your matcher\nwill be changed.\n\n`IsTrue` and `IsFalse` are useful when you need to use a matcher, or for types\nthat can be explicitly converted to Boolean, but are not implicitly converted to\nBoolean. In other cases, you can use the basic\n[`EXPECT_TRUE` and `EXPECT_FALSE`](assertions.md#boolean) assertions.\n\n## Floating-Point Matchers {#FpMatchers}\n\n| Matcher                          | Description                        |\n| :------------------------------- | :--------------------------------- |\n| `DoubleEq(a_double)`             | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as unequal. |\n| `FloatEq(a_float)`               | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as unequal. |\n| `NanSensitiveDoubleEq(a_double)` | `argument` is a `double` value approximately equal to `a_double`, treating two NaNs as equal. |\n| `NanSensitiveFloatEq(a_float)`   | `argument` is a `float` value approximately equal to `a_float`, treating two NaNs as equal. |\n| `IsNan()`   | `argument` is any floating-point type with a NaN value. |\n\nThe above matchers use ULP-based comparison (the same as used in googletest).\nThey automatically pick a reasonable error bound based on the absolute value of\nthe expected value. `DoubleEq()` and `FloatEq()` conform to the IEEE standard,\nwhich requires comparing two NaNs for equality to return false. The\n`NanSensitive*` version instead treats two NaNs as equal, which is often what a\nuser wants.\n\n| Matcher                                           | Description              |\n| :------------------------------------------------ | :----------------------- |\n| `DoubleNear(a_double, max_abs_error)`             | `argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as unequal. |\n| `FloatNear(a_float, max_abs_error)`               | `argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as unequal. |\n| `NanSensitiveDoubleNear(a_double, max_abs_error)` | `argument` is a `double` value close to `a_double` (absolute error <= `max_abs_error`), treating two NaNs as equal. |\n| `NanSensitiveFloatNear(a_float, max_abs_error)`   | `argument` is a `float` value close to `a_float` (absolute error <= `max_abs_error`), treating two NaNs as equal. |\n\n## String Matchers\n\nThe `argument` can be either a C string or a C++ string object:\n\n| Matcher                 | Description                                        |\n| :---------------------- | :------------------------------------------------- |\n| `ContainsRegex(string)`  | `argument` matches the given regular expression.  |\n| `EndsWith(suffix)`       | `argument` ends with string `suffix`.             |\n| `HasSubstr(string)`      | `argument` contains `string` as a sub-string.     |\n| `IsEmpty()`              | `argument` is an empty string.                    |\n| `MatchesRegex(string)`   | `argument` matches the given regular expression with the match starting at the first character and ending at the last character. |\n| `StartsWith(prefix)`     | `argument` starts with string `prefix`.           |\n| `StrCaseEq(string)`      | `argument` is equal to `string`, ignoring case.   |\n| `StrCaseNe(string)`      | `argument` is not equal to `string`, ignoring case. |\n| `StrEq(string)`          | `argument` is equal to `string`.                  |\n| `StrNe(string)`          | `argument` is not equal to `string`.              |\n| `WhenBase64Unescaped(m)` | `argument` is a base-64 escaped string whose unescaped string matches `m`. |\n\n`ContainsRegex()` and `MatchesRegex()` take ownership of the `RE` object. They\nuse the regular expression syntax defined\n[here](../advanced.md#regular-expression-syntax). All of these matchers, except\n`ContainsRegex()` and `MatchesRegex()` work for wide strings as well.\n\n## Container Matchers\n\nMost STL-style containers support `==`, so you can use `Eq(expected_container)`\nor simply `expected_container` to match a container exactly. If you want to\nwrite the elements in-line, match them more flexibly, or get more informative\nmessages, you can use:\n\n| Matcher                                   | Description                      |\n| :---------------------------------------- | :------------------------------- |\n| `BeginEndDistanceIs(m)` | `argument` is a container whose `begin()` and `end()` iterators are separated by a number of increments matching `m`. E.g. `BeginEndDistanceIs(2)` or `BeginEndDistanceIs(Lt(2))`. For containers that define a `size()` method, `SizeIs(m)` may be more efficient. |\n| `ContainerEq(container)` | The same as `Eq(container)` except that the failure message also includes which elements are in one container but not the other. |\n| `Contains(e)` | `argument` contains an element that matches `e`, which can be either a value or a matcher. |\n| `Contains(e).Times(n)` | `argument` contains elements that match `e`, which can be either a value or a matcher, and the number of matches is `n`, which can be either a value or a matcher. Unlike the plain `Contains` and `Each` this allows to check for arbitrary occurrences including testing for absence with `Contains(e).Times(0)`. |\n| `Each(e)` | `argument` is a container where *every* element matches `e`, which can be either a value or a matcher. |\n| `ElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, where the *i*-th element matches `ei`, which can be a value or a matcher. |\n| `ElementsAreArray({e0, e1, ..., en})`, `ElementsAreArray(a_container)`, `ElementsAreArray(begin, end)`, `ElementsAreArray(array)`, or `ElementsAreArray(array, count)` | The same as `ElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, iterator range, or C-style array. |\n| `IsEmpty()` | `argument` is an empty container (`container.empty()`). |\n| `IsSubsetOf({e0, e1, ..., en})`, `IsSubsetOf(a_container)`, `IsSubsetOf(begin, end)`, `IsSubsetOf(array)`, or `IsSubsetOf(array, count)` | `argument` matches `UnorderedElementsAre(x0, x1, ..., xk)` for some subset `{x0, x1, ..., xk}` of the expected matchers. |\n| `IsSupersetOf({e0, e1, ..., en})`, `IsSupersetOf(a_container)`, `IsSupersetOf(begin, end)`, `IsSupersetOf(array)`, or `IsSupersetOf(array, count)` | Some subset of `argument` matches `UnorderedElementsAre(`expected matchers`)`. |\n| `Pointwise(m, container)`, `Pointwise(m, {e0, e1, ..., en})` | `argument` contains the same number of elements as in `container`, and for all i, (the i-th element in `argument`, the i-th element in `container`) match `m`, which is a matcher on 2-tuples. E.g. `Pointwise(Le(), upper_bounds)` verifies that each element in `argument` doesn't exceed the corresponding element in `upper_bounds`. See more detail below. |\n| `SizeIs(m)` | `argument` is a container whose size matches `m`. E.g. `SizeIs(2)` or `SizeIs(Lt(2))`. |\n| `UnorderedElementsAre(e0, e1, ..., en)` | `argument` has `n + 1` elements, and under *some* permutation of the elements, each element matches an `ei` (for a different `i`), which can be a value or a matcher. |\n| `UnorderedElementsAreArray({e0, e1, ..., en})`, `UnorderedElementsAreArray(a_container)`, `UnorderedElementsAreArray(begin, end)`, `UnorderedElementsAreArray(array)`, or `UnorderedElementsAreArray(array, count)` | The same as `UnorderedElementsAre()` except that the expected element values/matchers come from an initializer list, STL-style container, iterator range, or C-style array. |\n| `UnorderedPointwise(m, container)`, `UnorderedPointwise(m, {e0, e1, ..., en})` | Like `Pointwise(m, container)`, but ignores the order of elements. |\n| `WhenSorted(m)` | When `argument` is sorted using the `<` operator, it matches container matcher `m`. E.g. `WhenSorted(ElementsAre(1, 2, 3))` verifies that `argument` contains elements 1, 2, and 3, ignoring order. |\n| `WhenSortedBy(comparator, m)` | The same as `WhenSorted(m)`, except that the given comparator instead of `<` is used to sort `argument`. E.g. `WhenSortedBy(std::greater(), ElementsAre(3, 2, 1))`. |\n\n**Notes:**\n\n*   These matchers can also match:\n    1.  a native array passed by reference (e.g. in `Foo(const int (&a)[5])`),\n        and\n    2.  an array passed as a pointer and a count (e.g. in `Bar(const T* buffer,\n        int len)` -- see [Multi-argument Matchers](#MultiArgMatchers)).\n*   The array being matched may be multi-dimensional (i.e. its elements can be\n    arrays).\n*   `m` in `Pointwise(m, ...)` and `UnorderedPointwise(m, ...)` should be a\n    matcher for `::std::tuple<T, U>` where `T` and `U` are the element type of\n    the actual container and the expected container, respectively. For example,\n    to compare two `Foo` containers where `Foo` doesn't support `operator==`,\n    one might write:\n\n    ```cpp\n    MATCHER(FooEq, \"\") {\n      return std::get<0>(arg).Equals(std::get<1>(arg));\n    }\n    ...\n    EXPECT_THAT(actual_foos, Pointwise(FooEq(), expected_foos));\n    ```\n\n## Member Matchers\n\n| Matcher                         | Description                                |\n| :------------------------------ | :----------------------------------------- |\n| `Field(&class::field, m)`       | `argument.field` (or `argument->field` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. |\n| `Field(field_name, &class::field, m)` | The same as the two-parameter version, but provides a better error message. |\n| `Key(e)`                        | `argument.first` matches `e`, which can be either a value or a matcher. E.g. `Contains(Key(Le(5)))` can verify that a `map` contains a key `<= 5`. |\n| `Pair(m1, m2)`                  | `argument` is an `std::pair` whose `first` field matches `m1` and `second` field matches `m2`. |\n| `FieldsAre(m...)`                   | `argument` is a compatible object where each field matches piecewise with the matchers `m...`. A compatible object is any that supports the `std::tuple_size<Obj>`+`get<I>(obj)` protocol. In C++17 and up this also supports types compatible with structured bindings, like aggregates. |\n| `Property(&class::property, m)` | `argument.property()` (or `argument->property()` when `argument` is a plain pointer) matches matcher `m`, where `argument` is an object of type _class_. The method `property()` must take no argument and be declared as `const`. |\n| `Property(property_name, &class::property, m)` | The same as the two-parameter version, but provides a better error message.\n\n**Notes:**\n\n*   You can use `FieldsAre()` to match any type that supports structured\n    bindings, such as `std::tuple`, `std::pair`, `std::array`, and aggregate\n    types. For example:\n\n    ```cpp\n    std::tuple<int, std::string> my_tuple{7, \"hello world\"};\n    EXPECT_THAT(my_tuple, FieldsAre(Ge(0), HasSubstr(\"hello\")));\n\n    struct MyStruct {\n      int value = 42;\n      std::string greeting = \"aloha\";\n    };\n    MyStruct s;\n    EXPECT_THAT(s, FieldsAre(42, \"aloha\"));\n    ```\n\n*   Don't use `Property()` against member functions that you do not own, because\n    taking addresses of functions is fragile and generally not part of the\n    contract of the function.\n\n## Matching the Result of a Function, Functor, or Callback\n\n| Matcher          | Description                                       |\n| :--------------- | :------------------------------------------------ |\n| `ResultOf(f, m)` | `f(argument)` matches matcher `m`, where `f` is a function or functor. |\n| `ResultOf(result_description, f, m)` | The same as the two-parameter version, but provides a better error message.\n\n## Pointer Matchers\n\n| Matcher                   | Description                                     |\n| :------------------------ | :---------------------------------------------- |\n| `Address(m)`              | the result of `std::addressof(argument)` matches `m`. |\n| `Pointee(m)`              | `argument` (either a smart pointer or a raw pointer) points to a value that matches matcher `m`. |\n| `Pointer(m)`              | `argument` (either a smart pointer or a raw pointer) contains a pointer that matches `m`. `m` will match against the raw pointer regardless of the type of `argument`. |\n| `WhenDynamicCastTo<T>(m)` | when `argument` is passed through `dynamic_cast<T>()`, it matches matcher `m`. |\n\n## Multi-argument Matchers {#MultiArgMatchers}\n\nTechnically, all matchers match a *single* value. A \"multi-argument\" matcher is\njust one that matches a *tuple*. The following matchers can be used to match a\ntuple `(x, y)`:\n\nMatcher | Description\n:------ | :----------\n`Eq()`  | `x == y`\n`Ge()`  | `x >= y`\n`Gt()`  | `x > y`\n`Le()`  | `x <= y`\n`Lt()`  | `x < y`\n`Ne()`  | `x != y`\n\nYou can use the following selectors to pick a subset of the arguments (or\nreorder them) to participate in the matching:\n\n| Matcher                    | Description                                     |\n| :------------------------- | :---------------------------------------------- |\n| `AllArgs(m)`               | Equivalent to `m`. Useful as syntactic sugar in `.With(AllArgs(m))`. |\n| `Args<N1, N2, ..., Nk>(m)` | The tuple of the `k` selected (using 0-based indices) arguments matches `m`, e.g. `Args<1, 2>(Eq())`. |\n\n## Composite Matchers\n\nYou can make a matcher from one or more other matchers:\n\n| Matcher                          | Description                             |\n| :------------------------------- | :-------------------------------------- |\n| `AllOf(m1, m2, ..., mn)` | `argument` matches all of the matchers `m1` to `mn`. |\n| `AllOfArray({m0, m1, ..., mn})`, `AllOfArray(a_container)`, `AllOfArray(begin, end)`, `AllOfArray(array)`, or `AllOfArray(array, count)` | The same as `AllOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. |\n| `AnyOf(m1, m2, ..., mn)` | `argument` matches at least one of the matchers `m1` to `mn`. |\n| `AnyOfArray({m0, m1, ..., mn})`, `AnyOfArray(a_container)`, `AnyOfArray(begin, end)`, `AnyOfArray(array)`, or `AnyOfArray(array, count)` | The same as `AnyOf()` except that the matchers come from an initializer list, STL-style container, iterator range, or C-style array. |\n| `Not(m)` | `argument` doesn't match matcher `m`. |\n| `Conditional(cond, m1, m2)` | Matches matcher `m1` if `cond` evaluates to true, else matches `m2`.|\n\n## Adapters for Matchers\n\n| Matcher                 | Description                           |\n| :---------------------- | :------------------------------------ |\n| `MatcherCast<T>(m)`     | casts matcher `m` to type `Matcher<T>`. |\n| `SafeMatcherCast<T>(m)` | [safely casts](../gmock_cook_book.md#SafeMatcherCast) matcher `m` to type `Matcher<T>`. |\n| `Truly(predicate)`      | `predicate(argument)` returns something considered by C++ to be true, where `predicate` is a function or functor. |\n\n`AddressSatisfies(callback)` and `Truly(callback)` take ownership of `callback`,\nwhich must be a permanent callback.\n\n## Using Matchers as Predicates {#MatchersAsPredicatesCheat}\n\n| Matcher                       | Description                                 |\n| :---------------------------- | :------------------------------------------ |\n| `Matches(m)(value)` | evaluates to `true` if `value` matches `m`. You can use `Matches(m)` alone as a unary functor. |\n| `ExplainMatchResult(m, value, result_listener)` | evaluates to `true` if `value` matches `m`, explaining the result to `result_listener`. |\n| `Value(value, m)` | evaluates to `true` if `value` matches `m`. |\n\n## Defining Matchers\n\n| Macro                                | Description                           |\n| :----------------------------------- | :------------------------------------ |\n| `MATCHER(IsEven, \"\") { return (arg % 2) == 0; }` | Defines a matcher `IsEven()` to match an even number. |\n| `MATCHER_P(IsDivisibleBy, n, \"\") { *result_listener << \"where the remainder is \" << (arg % n); return (arg % n) == 0; }` | Defines a matcher `IsDivisibleBy(n)` to match a number divisible by `n`. |\n| `MATCHER_P2(IsBetween, a, b, absl::StrCat(negation ? \"isn't\" : \"is\", \" between \", PrintToString(a), \" and \", PrintToString(b))) { return a <= arg && arg <= b; }` | Defines a matcher `IsBetween(a, b)` to match a value in the range [`a`, `b`]. |\n\n**Notes:**\n\n1.  The `MATCHER*` macros cannot be used inside a function or class.\n2.  The matcher body must be *purely functional* (i.e. it cannot have any side\n    effect, and the result must not depend on anything other than the value\n    being matched and the matcher parameters).\n3.  You can use `PrintToString(x)` to convert a value `x` of any type to a\n    string.\n4.  You can use `ExplainMatchResult()` in a custom matcher to wrap another\n    matcher, for example:\n\n    ```cpp\n    MATCHER_P(NestedPropertyMatches, matcher, \"\") {\n      return ExplainMatchResult(matcher, arg.nested().property(), result_listener);\n    }\n    ```\n"
  },
  {
    "path": "3rd/googletest-1.12.1/docs/reference/mocking.md",
    "content": "# Mocking Reference\n\nThis page lists the facilities provided by GoogleTest for creating and working\nwith mock objects. To use them, include the header\n`gmock/gmock.h`.\n\n## Macros {#macros}\n\nGoogleTest defines the following macros for working with mocks.\n\n### MOCK_METHOD {#MOCK_METHOD}\n\n`MOCK_METHOD(`*`return_type`*`,`*`method_name`*`, (`*`args...`*`));` \\\n`MOCK_METHOD(`*`return_type`*`,`*`method_name`*`, (`*`args...`*`),\n(`*`specs...`*`));`\n\nDefines a mock method *`method_name`* with arguments `(`*`args...`*`)` and\nreturn type *`return_type`* within a mock class.\n\nThe parameters of `MOCK_METHOD` mirror the method declaration. The optional\nfourth parameter *`specs...`* is a comma-separated list of qualifiers. The\nfollowing qualifiers are accepted:\n\n| Qualifier                  | Meaning                                      |\n| -------------------------- | -------------------------------------------- |\n| `const`                    | Makes the mocked method a `const` method. Required if overriding a `const` method. |\n| `override`                 | Marks the method with `override`. Recommended if overriding a `virtual` method. |\n| `noexcept`                 | Marks the method with `noexcept`. Required if overriding a `noexcept` method. |\n| `Calltype(`*`calltype`*`)` | Sets the call type for the method, for example `Calltype(STDMETHODCALLTYPE)`. Useful on Windows. |\n| `ref(`*`qualifier`*`)`     | Marks the method with the given reference qualifier, for example `ref(&)` or `ref(&&)`. Required if overriding a method that has a reference qualifier. |\n\nNote that commas in arguments prevent `MOCK_METHOD` from parsing the arguments\ncorrectly if they are not appropriately surrounded by parentheses. See the\nfollowing example:\n\n```cpp\nclass MyMock {\n public:\n  // The following 2 lines will not compile due to commas in the arguments:\n  MOCK_METHOD(std::pair<bool, int>, GetPair, ());              // Error!\n  MOCK_METHOD(bool, CheckMap, (std::map<int, double>, bool));  // Error!\n\n  // One solution - wrap arguments that contain commas in parentheses:\n  MOCK_METHOD((std::pair<bool, int>), GetPair, ());\n  MOCK_METHOD(bool, CheckMap, ((std::map<int, double>), bool));\n\n  // Another solution - use type aliases:\n  using BoolAndInt = std::pair<bool, int>;\n  MOCK_METHOD(BoolAndInt, GetPair, ());\n  using MapIntDouble = std::map<int, double>;\n  MOCK_METHOD(bool, CheckMap, (MapIntDouble, bool));\n};\n```\n\n`MOCK_METHOD` must be used in the `public:` section of a mock class definition,\nregardless of whether the method being mocked is `public`, `protected`, or\n`private` in the base class.\n\n### EXPECT_CALL {#EXPECT_CALL}\n\n`EXPECT_CALL(`*`mock_object`*`,`*`method_name`*`(`*`matchers...`*`))`\n\nCreates an [expectation](../gmock_for_dummies.md#setting-expectations) that the\nmethod *`method_name`* of the object *`mock_object`* is called with arguments\nthat match the given matchers *`matchers...`*. `EXPECT_CALL` must precede any\ncode that exercises the mock object.\n\nThe parameter *`matchers...`* is a comma-separated list of\n[matchers](../gmock_for_dummies.md#matchers-what-arguments-do-we-expect) that\ncorrespond to each argument of the method *`method_name`*. The expectation will\napply only to calls of *`method_name`* whose arguments match all of the\nmatchers. If `(`*`matchers...`*`)` is omitted, the expectation behaves as if\neach argument's matcher were a [wildcard matcher (`_`)](matchers.md#wildcard).\nSee the [Matchers Reference](matchers.md) for a list of all built-in matchers.\n\nThe following chainable clauses can be used to modify the expectation, and they\nmust be used in the following order:\n\n```cpp\nEXPECT_CALL(mock_object, method_name(matchers...))\n    .With(multi_argument_matcher)  // Can be used at most once\n    .Times(cardinality)            // Can be used at most once\n    .InSequence(sequences...)      // Can be used any number of times\n    .After(expectations...)        // Can be used any number of times\n    .WillOnce(action)              // Can be used any number of times\n    .WillRepeatedly(action)        // Can be used at most once\n    .RetiresOnSaturation();        // Can be used at most once\n```\n\nSee details for each modifier clause below.\n\n#### With {#EXPECT_CALL.With}\n\n`.With(`*`multi_argument_matcher`*`)`\n\nRestricts the expectation to apply only to mock function calls whose arguments\nas a whole match the multi-argument matcher *`multi_argument_matcher`*.\n\nGoogleTest passes all of the arguments as one tuple into the matcher. The\nparameter *`multi_argument_matcher`* must thus be a matcher of type\n`Matcher<std::tuple<A1, ..., An>>`, where `A1, ..., An` are the types of the\nfunction arguments.\n\nFor example, the following code sets the expectation that\n`my_mock.SetPosition()` is called with any two arguments, the first argument\nbeing less than the second:\n\n```cpp\nusing ::testing::_;\nusing ::testing::Lt;\n...\nEXPECT_CALL(my_mock, SetPosition(_, _))\n    .With(Lt());\n```\n\nGoogleTest provides some built-in matchers for 2-tuples, including the `Lt()`\nmatcher above. See [Multi-argument Matchers](matchers.md#MultiArgMatchers).\n\nThe `With` clause can be used at most once on an expectation and must be the\nfirst clause.\n\n#### Times {#EXPECT_CALL.Times}\n\n`.Times(`*`cardinality`*`)`\n\nSpecifies how many times the mock function call is expected.\n\nThe parameter *`cardinality`* represents the number of expected calls and can be\none of the following, all defined in the `::testing` namespace:\n\n| Cardinality         | Meaning                                             |\n| ------------------- | --------------------------------------------------- |\n| `AnyNumber()`       | The function can be called any number of times.     |\n| `AtLeast(n)`        | The function call is expected at least *n* times.   |\n| `AtMost(n)`         | The function call is expected at most *n* times.    |\n| `Between(m, n)`     | The function call is expected between *m* and *n* times, inclusive. |\n| `Exactly(n)` or `n` | The function call is expected exactly *n* times. If *n* is 0, the call should never happen. |\n\nIf the `Times` clause is omitted, GoogleTest infers the cardinality as follows:\n\n*   If neither [`WillOnce`](#EXPECT_CALL.WillOnce) nor\n    [`WillRepeatedly`](#EXPECT_CALL.WillRepeatedly) are specified, the inferred\n    cardinality is `Times(1)`.\n*   If there are *n* `WillOnce` clauses and no `WillRepeatedly` clause, where\n    *n* >= 1, the inferred cardinality is `Times(n)`.\n*   If there are *n* `WillOnce` clauses and one `WillRepeatedly` clause, where\n    *n* >= 0, the inferred cardinality is `Times(AtLeast(n))`.\n\nThe `Times` clause can be used at most once on an expectation.\n\n#### InSequence {#EXPECT_CALL.InSequence}\n\n`.InSequence(`*`sequences...`*`)`\n\nSpecifies that the mock function call is expected in a certain sequence.\n\nThe parameter *`sequences...`* is any number of [`Sequence`](#Sequence) objects.\nExpected calls assigned to the same sequence are expected to occur in the order\nthe expectations are declared.\n\nFor example, the following code sets the expectation that the `Reset()` method\nof `my_mock` is called before both `GetSize()` and `Describe()`, and `GetSize()`\nand `Describe()` can occur in any order relative to each other:\n\n```cpp\nusing ::testing::Sequence;\nSequence s1, s2;\n...\nEXPECT_CALL(my_mock, Reset())\n    .InSequence(s1, s2);\nEXPECT_CALL(my_mock, GetSize())\n    .InSequence(s1);\nEXPECT_CALL(my_mock, Describe())\n    .InSequence(s2);\n```\n\nThe `InSequence` clause can be used any number of times on an expectation.\n\nSee also the [`InSequence` class](#InSequence).\n\n#### After {#EXPECT_CALL.After}\n\n`.After(`*`expectations...`*`)`\n\nSpecifies that the mock function call is expected to occur after one or more\nother calls.\n\nThe parameter *`expectations...`* can be up to five\n[`Expectation`](#Expectation) or [`ExpectationSet`](#ExpectationSet) objects.\nThe mock function call is expected to occur after all of the given expectations.\n\nFor example, the following code sets the expectation that the `Describe()`\nmethod of `my_mock` is called only after both `InitX()` and `InitY()` have been\ncalled.\n\n```cpp\nusing ::testing::Expectation;\n...\nExpectation init_x = EXPECT_CALL(my_mock, InitX());\nExpectation init_y = EXPECT_CALL(my_mock, InitY());\nEXPECT_CALL(my_mock, Describe())\n    .After(init_x, init_y);\n```\n\nThe `ExpectationSet` object is helpful when the number of prerequisites for an\nexpectation is large or variable, for example:\n\n```cpp\nusing ::testing::ExpectationSet;\n...\nExpectationSet all_inits;\n// Collect all expectations of InitElement() calls\nfor (int i = 0; i < element_count; i++) {\n  all_inits += EXPECT_CALL(my_mock, InitElement(i));\n}\nEXPECT_CALL(my_mock, Describe())\n    .After(all_inits);  // Expect Describe() call after all InitElement() calls\n```\n\nThe `After` clause can be used any number of times on an expectation.\n\n#### WillOnce {#EXPECT_CALL.WillOnce}\n\n`.WillOnce(`*`action`*`)`\n\nSpecifies the mock function's actual behavior when invoked, for a single\nmatching function call.\n\nThe parameter *`action`* represents the\n[action](../gmock_for_dummies.md#actions-what-should-it-do) that the function\ncall will perform. See the [Actions Reference](actions.md) for a list of\nbuilt-in actions.\n\nThe use of `WillOnce` implicitly sets a cardinality on the expectation when\n`Times` is not specified. See [`Times`](#EXPECT_CALL.Times).\n\nEach matching function call will perform the next action in the order declared.\nFor example, the following code specifies that `my_mock.GetNumber()` is expected\nto be called exactly 3 times and will return `1`, `2`, and `3` respectively on\nthe first, second, and third calls:\n\n```cpp\nusing ::testing::Return;\n...\nEXPECT_CALL(my_mock, GetNumber())\n    .WillOnce(Return(1))\n    .WillOnce(Return(2))\n    .WillOnce(Return(3));\n```\n\nThe `WillOnce` clause can be used any number of times on an expectation. Unlike\n`WillRepeatedly`, the action fed to each `WillOnce` call will be called at most\nonce, so may be a move-only type and/or have an `&&`-qualified call operator.\n\n#### WillRepeatedly {#EXPECT_CALL.WillRepeatedly}\n\n`.WillRepeatedly(`*`action`*`)`\n\nSpecifies the mock function's actual behavior when invoked, for all subsequent\nmatching function calls. Takes effect after the actions specified in the\n[`WillOnce`](#EXPECT_CALL.WillOnce) clauses, if any, have been performed.\n\nThe parameter *`action`* represents the\n[action](../gmock_for_dummies.md#actions-what-should-it-do) that the function\ncall will perform. See the [Actions Reference](actions.md) for a list of\nbuilt-in actions.\n\nThe use of `WillRepeatedly` implicitly sets a cardinality on the expectation\nwhen `Times` is not specified. See [`Times`](#EXPECT_CALL.Times).\n\nIf any `WillOnce` clauses have been specified, matching function calls will\nperform those actions before the action specified by `WillRepeatedly`. See the\nfollowing example:\n\n```cpp\nusing ::testing::Return;\n...\nEXPECT_CALL(my_mock, GetName())\n    .WillRepeatedly(Return(\"John Doe\"));  // Return \"John Doe\" on all calls\n\nEXPECT_CALL(my_mock, GetNumber())\n    .WillOnce(Return(42))        // Return 42 on the first call\n    .WillRepeatedly(Return(7));  // Return 7 on all subsequent calls\n```\n\nThe `WillRepeatedly` clause can be used at most once on an expectation.\n\n#### RetiresOnSaturation {#EXPECT_CALL.RetiresOnSaturation}\n\n`.RetiresOnSaturation()`\n\nIndicates that the expectation will no longer be active after the expected\nnumber of matching function calls has been reached.\n\nThe `RetiresOnSaturation` clause is only meaningful for expectations with an\nupper-bounded cardinality. The expectation will *retire* (no longer match any\nfunction calls) after it has been *saturated* (the upper bound has been\nreached). See the following example:\n\n```cpp\nusing ::testing::_;\nusing ::testing::AnyNumber;\n...\nEXPECT_CALL(my_mock, SetNumber(_))  // Expectation 1\n    .Times(AnyNumber());\nEXPECT_CALL(my_mock, SetNumber(7))  // Expectation 2\n    .Times(2)\n    .RetiresOnSaturation();\n```\n\nIn the above example, the first two calls to `my_mock.SetNumber(7)` match\nexpectation 2, which then becomes inactive and no longer matches any calls. A\nthird call to `my_mock.SetNumber(7)` would then match expectation 1. Without\n`RetiresOnSaturation()` on expectation 2, a third call to `my_mock.SetNumber(7)`\nwould match expectation 2 again, producing a failure since the limit of 2 calls\nwas exceeded.\n\nThe `RetiresOnSaturation` clause can be used at most once on an expectation and\nmust be the last clause.\n\n### ON_CALL {#ON_CALL}\n\n`ON_CALL(`*`mock_object`*`,`*`method_name`*`(`*`matchers...`*`))`\n\nDefines what happens when the method *`method_name`* of the object\n*`mock_object`* is called with arguments that match the given matchers\n*`matchers...`*. Requires a modifier clause to specify the method's behavior.\n*Does not* set any expectations that the method will be called.\n\nThe parameter *`matchers...`* is a comma-separated list of\n[matchers](../gmock_for_dummies.md#matchers-what-arguments-do-we-expect) that\ncorrespond to each argument of the method *`method_name`*. The `ON_CALL`\nspecification will apply only to calls of *`method_name`* whose arguments match\nall of the matchers. If `(`*`matchers...`*`)` is omitted, the behavior is as if\neach argument's matcher were a [wildcard matcher (`_`)](matchers.md#wildcard).\nSee the [Matchers Reference](matchers.md) for a list of all built-in matchers.\n\nThe following chainable clauses can be used to set the method's behavior, and\nthey must be used in the following order:\n\n```cpp\nON_CALL(mock_object, method_name(matchers...))\n    .With(multi_argument_matcher)  // Can be used at most once\n    .WillByDefault(action);        // Required\n```\n\nSee details for each modifier clause below.\n\n#### With {#ON_CALL.With}\n\n`.With(`*`multi_argument_matcher`*`)`\n\nRestricts the specification to only mock function calls whose arguments as a\nwhole match the multi-argument matcher *`multi_argument_matcher`*.\n\nGoogleTest passes all of the arguments as one tuple into the matcher. The\nparameter *`multi_argument_matcher`* must thus be a matcher of type\n`Matcher<std::tuple<A1, ..., An>>`, where `A1, ..., An` are the types of the\nfunction arguments.\n\nFor example, the following code sets the default behavior when\n`my_mock.SetPosition()` is called with any two arguments, the first argument\nbeing less than the second:\n\n```cpp\nusing ::testing::_;\nusing ::testing::Lt;\nusing ::testing::Return;\n...\nON_CALL(my_mock, SetPosition(_, _))\n    .With(Lt())\n    .WillByDefault(Return(true));\n```\n\nGoogleTest provides some built-in matchers for 2-tuples, including the `Lt()`\nmatcher above. See [Multi-argument Matchers](matchers.md#MultiArgMatchers).\n\nThe `With` clause can be used at most once with each `ON_CALL` statement.\n\n#### WillByDefault {#ON_CALL.WillByDefault}\n\n`.WillByDefault(`*`action`*`)`\n\nSpecifies the default behavior of a matching mock function call.\n\nThe parameter *`action`* represents the\n[action](../gmock_for_dummies.md#actions-what-should-it-do) that the function\ncall will perform. See the [Actions Reference](actions.md) for a list of\nbuilt-in actions.\n\nFor example, the following code specifies that by default, a call to\n`my_mock.Greet()` will return `\"hello\"`:\n\n```cpp\nusing ::testing::Return;\n...\nON_CALL(my_mock, Greet())\n    .WillByDefault(Return(\"hello\"));\n```\n\nThe action specified by `WillByDefault` is superseded by the actions specified\non a matching `EXPECT_CALL` statement, if any. See the\n[`WillOnce`](#EXPECT_CALL.WillOnce) and\n[`WillRepeatedly`](#EXPECT_CALL.WillRepeatedly) clauses of `EXPECT_CALL`.\n\nThe `WillByDefault` clause must be used exactly once with each `ON_CALL`\nstatement.\n\n## Classes {#classes}\n\nGoogleTest defines the following classes for working with mocks.\n\n### DefaultValue {#DefaultValue}\n\n`::testing::DefaultValue<T>`\n\nAllows a user to specify the default value for a type `T` that is both copyable\nand publicly destructible (i.e. anything that can be used as a function return\ntype). For mock functions with a return type of `T`, this default value is\nreturned from function calls that do not specify an action.\n\nProvides the static methods `Set()`, `SetFactory()`, and `Clear()` to manage the\ndefault value:\n\n```cpp\n// Sets the default value to be returned. T must be copy constructible.\nDefaultValue<T>::Set(value);\n\n// Sets a factory. Will be invoked on demand. T must be move constructible.\nT MakeT();\nDefaultValue<T>::SetFactory(&MakeT);\n\n// Unsets the default value.\nDefaultValue<T>::Clear();\n```\n\n### NiceMock {#NiceMock}\n\n`::testing::NiceMock<T>`\n\nRepresents a mock object that suppresses warnings on\n[uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The\ntemplate parameter `T` is any mock class, except for another `NiceMock`,\n`NaggyMock`, or `StrictMock`.\n\nUsage of `NiceMock<T>` is analogous to usage of `T`. `NiceMock<T>` is a subclass\nof `T`, so it can be used wherever an object of type `T` is accepted. In\naddition, `NiceMock<T>` can be constructed with any arguments that a constructor\nof `T` accepts.\n\nFor example, the following code suppresses warnings on the mock `my_mock` of\ntype `MockClass` if a method other than `DoSomething()` is called:\n\n```cpp\nusing ::testing::NiceMock;\n...\nNiceMock<MockClass> my_mock(\"some\", \"args\");\nEXPECT_CALL(my_mock, DoSomething());\n... code that uses my_mock ...\n```\n\n`NiceMock<T>` only works for mock methods defined using the `MOCK_METHOD` macro\ndirectly in the definition of class `T`. If a mock method is defined in a base\nclass of `T`, a warning might still be generated.\n\n`NiceMock<T>` might not work correctly if the destructor of `T` is not virtual.\n\n### NaggyMock {#NaggyMock}\n\n`::testing::NaggyMock<T>`\n\nRepresents a mock object that generates warnings on\n[uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The\ntemplate parameter `T` is any mock class, except for another `NiceMock`,\n`NaggyMock`, or `StrictMock`.\n\nUsage of `NaggyMock<T>` is analogous to usage of `T`. `NaggyMock<T>` is a\nsubclass of `T`, so it can be used wherever an object of type `T` is accepted.\nIn addition, `NaggyMock<T>` can be constructed with any arguments that a\nconstructor of `T` accepts.\n\nFor example, the following code generates warnings on the mock `my_mock` of type\n`MockClass` if a method other than `DoSomething()` is called:\n\n```cpp\nusing ::testing::NaggyMock;\n...\nNaggyMock<MockClass> my_mock(\"some\", \"args\");\nEXPECT_CALL(my_mock, DoSomething());\n... code that uses my_mock ...\n```\n\nMock objects of type `T` by default behave the same way as `NaggyMock<T>`.\n\n### StrictMock {#StrictMock}\n\n`::testing::StrictMock<T>`\n\nRepresents a mock object that generates test failures on\n[uninteresting calls](../gmock_cook_book.md#uninteresting-vs-unexpected). The\ntemplate parameter `T` is any mock class, except for another `NiceMock`,\n`NaggyMock`, or `StrictMock`.\n\nUsage of `StrictMock<T>` is analogous to usage of `T`. `StrictMock<T>` is a\nsubclass of `T`, so it can be used wherever an object of type `T` is accepted.\nIn addition, `StrictMock<T>` can be constructed with any arguments that a\nconstructor of `T` accepts.\n\nFor example, the following code generates a test failure on the mock `my_mock`\nof type `MockClass` if a method other than `DoSomething()` is called:\n\n```cpp\nusing ::testing::StrictMock;\n...\nStrictMock<MockClass> my_mock(\"some\", \"args\");\nEXPECT_CALL(my_mock, DoSomething());\n... code that uses my_mock ...\n```\n\n`StrictMock<T>` only works for mock methods defined using the `MOCK_METHOD`\nmacro directly in the definition of class `T`. If a mock method is defined in a\nbase class of `T`, a failure might not be generated.\n\n`StrictMock<T>` might not work correctly if the destructor of `T` is not\nvirtual.\n\n### Sequence {#Sequence}\n\n`::testing::Sequence`\n\nRepresents a chronological sequence of expectations. See the\n[`InSequence`](#EXPECT_CALL.InSequence) clause of `EXPECT_CALL` for usage.\n\n### InSequence {#InSequence}\n\n`::testing::InSequence`\n\nAn object of this type causes all expectations encountered in its scope to be\nput in an anonymous sequence.\n\nThis allows more convenient expression of multiple expectations in a single\nsequence:\n\n```cpp\nusing ::testing::InSequence;\n{\n  InSequence seq;\n\n  // The following are expected to occur in the order declared.\n  EXPECT_CALL(...);\n  EXPECT_CALL(...);\n  ...\n  EXPECT_CALL(...);\n}\n```\n\nThe name of the `InSequence` object does not matter.\n\n### Expectation {#Expectation}\n\n`::testing::Expectation`\n\nRepresents a mock function call expectation as created by\n[`EXPECT_CALL`](#EXPECT_CALL):\n\n```cpp\nusing ::testing::Expectation;\nExpectation my_expectation = EXPECT_CALL(...);\n```\n\nUseful for specifying sequences of expectations; see the\n[`After`](#EXPECT_CALL.After) clause of `EXPECT_CALL`.\n\n### ExpectationSet {#ExpectationSet}\n\n`::testing::ExpectationSet`\n\nRepresents a set of mock function call expectations.\n\nUse the `+=` operator to add [`Expectation`](#Expectation) objects to the set:\n\n```cpp\nusing ::testing::ExpectationSet;\nExpectationSet my_expectations;\nmy_expectations += EXPECT_CALL(...);\n```\n\nUseful for specifying sequences of expectations; see the\n[`After`](#EXPECT_CALL.After) clause of `EXPECT_CALL`.\n"
  },
  {
    "path": "3rd/googletest-1.12.1/docs/reference/testing.md",
    "content": "# Testing Reference\n\n<!--* toc_depth: 3 *-->\n\nThis page lists the facilities provided by GoogleTest for writing test programs.\nTo use them, include the header `gtest/gtest.h`.\n\n## Macros\n\nGoogleTest defines the following macros for writing tests.\n\n### TEST {#TEST}\n\n<pre>\nTEST(<em>TestSuiteName</em>, <em>TestName</em>) {\n  ... <em>statements</em> ...\n}\n</pre>\n\nDefines an individual test named *`TestName`* in the test suite\n*`TestSuiteName`*, consisting of the given statements.\n\nBoth arguments *`TestSuiteName`* and *`TestName`* must be valid C++ identifiers\nand must not contain underscores (`_`). Tests in different test suites can have\nthe same individual name.\n\nThe statements within the test body can be any code under test.\n[Assertions](assertions.md) used within the test body determine the outcome of\nthe test.\n\n### TEST_F {#TEST_F}\n\n<pre>\nTEST_F(<em>TestFixtureName</em>, <em>TestName</em>) {\n  ... <em>statements</em> ...\n}\n</pre>\n\nDefines an individual test named *`TestName`* that uses the test fixture class\n*`TestFixtureName`*. The test suite name is *`TestFixtureName`*.\n\nBoth arguments *`TestFixtureName`* and *`TestName`* must be valid C++\nidentifiers and must not contain underscores (`_`). *`TestFixtureName`* must be\nthe name of a test fixture class—see\n[Test Fixtures](../primer.md#same-data-multiple-tests).\n\nThe statements within the test body can be any code under test.\n[Assertions](assertions.md) used within the test body determine the outcome of\nthe test.\n\n### TEST_P {#TEST_P}\n\n<pre>\nTEST_P(<em>TestFixtureName</em>, <em>TestName</em>) {\n  ... <em>statements</em> ...\n}\n</pre>\n\nDefines an individual value-parameterized test named *`TestName`* that uses the\ntest fixture class *`TestFixtureName`*. The test suite name is\n*`TestFixtureName`*.\n\nBoth arguments *`TestFixtureName`* and *`TestName`* must be valid C++\nidentifiers and must not contain underscores (`_`). *`TestFixtureName`* must be\nthe name of a value-parameterized test fixture class—see\n[Value-Parameterized Tests](../advanced.md#value-parameterized-tests).\n\nThe statements within the test body can be any code under test. Within the test\nbody, the test parameter can be accessed with the `GetParam()` function (see\n[`WithParamInterface`](#WithParamInterface)). For example:\n\n```cpp\nTEST_P(MyTestSuite, DoesSomething) {\n  ...\n  EXPECT_TRUE(DoSomething(GetParam()));\n  ...\n}\n```\n\n[Assertions](assertions.md) used within the test body determine the outcome of\nthe test.\n\nSee also [`INSTANTIATE_TEST_SUITE_P`](#INSTANTIATE_TEST_SUITE_P).\n\n### INSTANTIATE_TEST_SUITE_P {#INSTANTIATE_TEST_SUITE_P}\n\n`INSTANTIATE_TEST_SUITE_P(`*`InstantiationName`*`,`*`TestSuiteName`*`,`*`param_generator`*`)`\n\\\n`INSTANTIATE_TEST_SUITE_P(`*`InstantiationName`*`,`*`TestSuiteName`*`,`*`param_generator`*`,`*`name_generator`*`)`\n\nInstantiates the value-parameterized test suite *`TestSuiteName`* (defined with\n[`TEST_P`](#TEST_P)).\n\nThe argument *`InstantiationName`* is a unique name for the instantiation of the\ntest suite, to distinguish between multiple instantiations. In test output, the\ninstantiation name is added as a prefix to the test suite name\n*`TestSuiteName`*.\n\nThe argument *`param_generator`* is one of the following GoogleTest-provided\nfunctions that generate the test parameters, all defined in the `::testing`\nnamespace:\n\n<span id=\"param-generators\"></span>\n\n| Parameter Generator | Behavior                                             |\n| ------------------- | ---------------------------------------------------- |\n| `Range(begin, end [, step])` | Yields values `{begin, begin+step, begin+step+step, ...}`. The values do not include `end`. `step` defaults to 1. |\n| `Values(v1, v2, ..., vN)`    | Yields values `{v1, v2, ..., vN}`.          |\n| `ValuesIn(container)` or `ValuesIn(begin,end)` | Yields values from a C-style array, an STL-style container, or an iterator range `[begin, end)`. |\n| `Bool()`                     | Yields sequence `{false, true}`.            |\n| `Combine(g1, g2, ..., gN)`   | Yields as `std::tuple` *n*-tuples all combinations (Cartesian product) of the values generated by the given *n* generators `g1`, `g2`, ..., `gN`. |\n\nThe optional last argument *`name_generator`* is a function or functor that\ngenerates custom test name suffixes based on the test parameters. The function\nmust accept an argument of type\n[`TestParamInfo<class ParamType>`](#TestParamInfo) and return a `std::string`.\nThe test name suffix can only contain alphanumeric characters and underscores.\nGoogleTest provides [`PrintToStringParamName`](#PrintToStringParamName), or a\ncustom function can be used for more control:\n\n```cpp\nINSTANTIATE_TEST_SUITE_P(\n    MyInstantiation, MyTestSuite,\n    ::testing::Values(...),\n    [](const ::testing::TestParamInfo<MyTestSuite::ParamType>& info) {\n      // Can use info.param here to generate the test suffix\n      std::string name = ...\n      return name;\n    });\n```\n\nFor more information, see\n[Value-Parameterized Tests](../advanced.md#value-parameterized-tests).\n\nSee also\n[`GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST`](#GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST).\n\n### TYPED_TEST_SUITE {#TYPED_TEST_SUITE}\n\n`TYPED_TEST_SUITE(`*`TestFixtureName`*`,`*`Types`*`)`\n\nDefines a typed test suite based on the test fixture *`TestFixtureName`*. The\ntest suite name is *`TestFixtureName`*.\n\nThe argument *`TestFixtureName`* is a fixture class template, parameterized by a\ntype, for example:\n\n```cpp\ntemplate <typename T>\nclass MyFixture : public ::testing::Test {\n public:\n  ...\n  using List = std::list<T>;\n  static T shared_;\n  T value_;\n};\n```\n\nThe argument *`Types`* is a [`Types`](#Types) object representing the list of\ntypes to run the tests on, for example:\n\n```cpp\nusing MyTypes = ::testing::Types<char, int, unsigned int>;\nTYPED_TEST_SUITE(MyFixture, MyTypes);\n```\n\nThe type alias (`using` or `typedef`) is necessary for the `TYPED_TEST_SUITE`\nmacro to parse correctly.\n\nSee also [`TYPED_TEST`](#TYPED_TEST) and\n[Typed Tests](../advanced.md#typed-tests) for more information.\n\n### TYPED_TEST {#TYPED_TEST}\n\n<pre>\nTYPED_TEST(<em>TestSuiteName</em>, <em>TestName</em>) {\n  ... <em>statements</em> ...\n}\n</pre>\n\nDefines an individual typed test named *`TestName`* in the typed test suite\n*`TestSuiteName`*. The test suite must be defined with\n[`TYPED_TEST_SUITE`](#TYPED_TEST_SUITE).\n\nWithin the test body, the special name `TypeParam` refers to the type parameter,\nand `TestFixture` refers to the fixture class. See the following example:\n\n```cpp\nTYPED_TEST(MyFixture, Example) {\n  // Inside a test, refer to the special name TypeParam to get the type\n  // parameter.  Since we are inside a derived class template, C++ requires\n  // us to visit the members of MyFixture via 'this'.\n  TypeParam n = this->value_;\n\n  // To visit static members of the fixture, add the 'TestFixture::'\n  // prefix.\n  n += TestFixture::shared_;\n\n  // To refer to typedefs in the fixture, add the 'typename TestFixture::'\n  // prefix. The 'typename' is required to satisfy the compiler.\n  typename TestFixture::List values;\n\n  values.push_back(n);\n  ...\n}\n```\n\nFor more information, see [Typed Tests](../advanced.md#typed-tests).\n\n### TYPED_TEST_SUITE_P {#TYPED_TEST_SUITE_P}\n\n`TYPED_TEST_SUITE_P(`*`TestFixtureName`*`)`\n\nDefines a type-parameterized test suite based on the test fixture\n*`TestFixtureName`*. The test suite name is *`TestFixtureName`*.\n\nThe argument *`TestFixtureName`* is a fixture class template, parameterized by a\ntype. See [`TYPED_TEST_SUITE`](#TYPED_TEST_SUITE) for an example.\n\nSee also [`TYPED_TEST_P`](#TYPED_TEST_P) and\n[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more\ninformation.\n\n### TYPED_TEST_P {#TYPED_TEST_P}\n\n<pre>\nTYPED_TEST_P(<em>TestSuiteName</em>, <em>TestName</em>) {\n  ... <em>statements</em> ...\n}\n</pre>\n\nDefines an individual type-parameterized test named *`TestName`* in the\ntype-parameterized test suite *`TestSuiteName`*. The test suite must be defined\nwith [`TYPED_TEST_SUITE_P`](#TYPED_TEST_SUITE_P).\n\nWithin the test body, the special name `TypeParam` refers to the type parameter,\nand `TestFixture` refers to the fixture class. See [`TYPED_TEST`](#TYPED_TEST)\nfor an example.\n\nSee also [`REGISTER_TYPED_TEST_SUITE_P`](#REGISTER_TYPED_TEST_SUITE_P) and\n[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more\ninformation.\n\n### REGISTER_TYPED_TEST_SUITE_P {#REGISTER_TYPED_TEST_SUITE_P}\n\n`REGISTER_TYPED_TEST_SUITE_P(`*`TestSuiteName`*`,`*`TestNames...`*`)`\n\nRegisters the type-parameterized tests *`TestNames...`* of the test suite\n*`TestSuiteName`*. The test suite and tests must be defined with\n[`TYPED_TEST_SUITE_P`](#TYPED_TEST_SUITE_P) and [`TYPED_TEST_P`](#TYPED_TEST_P).\n\nFor example:\n\n```cpp\n// Define the test suite and tests.\nTYPED_TEST_SUITE_P(MyFixture);\nTYPED_TEST_P(MyFixture, HasPropertyA) { ... }\nTYPED_TEST_P(MyFixture, HasPropertyB) { ... }\n\n// Register the tests in the test suite.\nREGISTER_TYPED_TEST_SUITE_P(MyFixture, HasPropertyA, HasPropertyB);\n```\n\nSee also [`INSTANTIATE_TYPED_TEST_SUITE_P`](#INSTANTIATE_TYPED_TEST_SUITE_P) and\n[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more\ninformation.\n\n### INSTANTIATE_TYPED_TEST_SUITE_P {#INSTANTIATE_TYPED_TEST_SUITE_P}\n\n`INSTANTIATE_TYPED_TEST_SUITE_P(`*`InstantiationName`*`,`*`TestSuiteName`*`,`*`Types`*`)`\n\nInstantiates the type-parameterized test suite *`TestSuiteName`*. The test suite\nmust be registered with\n[`REGISTER_TYPED_TEST_SUITE_P`](#REGISTER_TYPED_TEST_SUITE_P).\n\nThe argument *`InstantiationName`* is a unique name for the instantiation of the\ntest suite, to distinguish between multiple instantiations. In test output, the\ninstantiation name is added as a prefix to the test suite name\n*`TestSuiteName`*.\n\nThe argument *`Types`* is a [`Types`](#Types) object representing the list of\ntypes to run the tests on, for example:\n\n```cpp\nusing MyTypes = ::testing::Types<char, int, unsigned int>;\nINSTANTIATE_TYPED_TEST_SUITE_P(MyInstantiation, MyFixture, MyTypes);\n```\n\nThe type alias (`using` or `typedef`) is necessary for the\n`INSTANTIATE_TYPED_TEST_SUITE_P` macro to parse correctly.\n\nFor more information, see\n[Type-Parameterized Tests](../advanced.md#type-parameterized-tests).\n\n### FRIEND_TEST {#FRIEND_TEST}\n\n`FRIEND_TEST(`*`TestSuiteName`*`,`*`TestName`*`)`\n\nWithin a class body, declares an individual test as a friend of the class,\nenabling the test to access private class members.\n\nIf the class is defined in a namespace, then in order to be friends of the\nclass, test fixtures and tests must be defined in the exact same namespace,\nwithout inline or anonymous namespaces.\n\nFor example, if the class definition looks like the following:\n\n```cpp\nnamespace my_namespace {\n\nclass MyClass {\n  friend class MyClassTest;\n  FRIEND_TEST(MyClassTest, HasPropertyA);\n  FRIEND_TEST(MyClassTest, HasPropertyB);\n  ... definition of class MyClass ...\n};\n\n}  // namespace my_namespace\n```\n\nThen the test code should look like:\n\n```cpp\nnamespace my_namespace {\n\nclass MyClassTest : public ::testing::Test {\n  ...\n};\n\nTEST_F(MyClassTest, HasPropertyA) { ... }\nTEST_F(MyClassTest, HasPropertyB) { ... }\n\n}  // namespace my_namespace\n```\n\nSee [Testing Private Code](../advanced.md#testing-private-code) for more\ninformation.\n\n### SCOPED_TRACE {#SCOPED_TRACE}\n\n`SCOPED_TRACE(`*`message`*`)`\n\nCauses the current file name, line number, and the given message *`message`* to\nbe added to the failure message for each assertion failure that occurs in the\nscope.\n\nFor more information, see\n[Adding Traces to Assertions](../advanced.md#adding-traces-to-assertions).\n\nSee also the [`ScopedTrace` class](#ScopedTrace).\n\n### GTEST_SKIP {#GTEST_SKIP}\n\n`GTEST_SKIP()`\n\nPrevents further test execution at runtime.\n\nCan be used in individual test cases or in the `SetUp()` methods of test\nenvironments or test fixtures (classes derived from the\n[`Environment`](#Environment) or [`Test`](#Test) classes). If used in a global\ntest environment `SetUp()` method, it skips all tests in the test program. If\nused in a test fixture `SetUp()` method, it skips all tests in the corresponding\ntest suite.\n\nSimilar to assertions, `GTEST_SKIP` allows streaming a custom message into it.\n\nSee [Skipping Test Execution](../advanced.md#skipping-test-execution) for more\ninformation.\n\n### GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST {#GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST}\n\n`GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(`*`TestSuiteName`*`)`\n\nAllows the value-parameterized test suite *`TestSuiteName`* to be\nuninstantiated.\n\nBy default, every [`TEST_P`](#TEST_P) call without a corresponding\n[`INSTANTIATE_TEST_SUITE_P`](#INSTANTIATE_TEST_SUITE_P) call causes a failing\ntest in the test suite `GoogleTestVerification`.\n`GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST` suppresses this failure for the\ngiven test suite.\n\n## Classes and types\n\nGoogleTest defines the following classes and types to help with writing tests.\n\n### AssertionResult {#AssertionResult}\n\n`::testing::AssertionResult`\n\nA class for indicating whether an assertion was successful.\n\nWhen the assertion wasn't successful, the `AssertionResult` object stores a\nnon-empty failure message that can be retrieved with the object's `message()`\nmethod.\n\nTo create an instance of this class, use one of the factory functions\n[`AssertionSuccess()`](#AssertionSuccess) or\n[`AssertionFailure()`](#AssertionFailure).\n\n### AssertionException {#AssertionException}\n\n`::testing::AssertionException`\n\nException which can be thrown from\n[`TestEventListener::OnTestPartResult`](#TestEventListener::OnTestPartResult).\n\n### EmptyTestEventListener {#EmptyTestEventListener}\n\n`::testing::EmptyTestEventListener`\n\nProvides an empty implementation of all methods in the\n[`TestEventListener`](#TestEventListener) interface, such that a subclass only\nneeds to override the methods it cares about.\n\n### Environment {#Environment}\n\n`::testing::Environment`\n\nRepresents a global test environment. See\n[Global Set-Up and Tear-Down](../advanced.md#global-set-up-and-tear-down).\n\n#### Protected Methods {#Environment-protected}\n\n##### SetUp {#Environment::SetUp}\n\n`virtual void Environment::SetUp()`\n\nOverride this to define how to set up the environment.\n\n##### TearDown {#Environment::TearDown}\n\n`virtual void Environment::TearDown()`\n\nOverride this to define how to tear down the environment.\n\n### ScopedTrace {#ScopedTrace}\n\n`::testing::ScopedTrace`\n\nAn instance of this class causes a trace to be included in every test failure\nmessage generated by code in the scope of the lifetime of the `ScopedTrace`\ninstance. The effect is undone with the destruction of the instance.\n\nThe `ScopedTrace` constructor has the following form:\n\n```cpp\ntemplate <typename T>\nScopedTrace(const char* file, int line, const T& message)\n```\n\nExample usage:\n\n```cpp\n::testing::ScopedTrace trace(\"file.cc\", 123, \"message\");\n```\n\nThe resulting trace includes the given source file path and line number, and the\ngiven message. The `message` argument can be anything streamable to\n`std::ostream`.\n\nSee also [`SCOPED_TRACE`](#SCOPED_TRACE).\n\n### Test {#Test}\n\n`::testing::Test`\n\nThe abstract class that all tests inherit from. `Test` is not copyable.\n\n#### Public Methods {#Test-public}\n\n##### SetUpTestSuite {#Test::SetUpTestSuite}\n\n`static void Test::SetUpTestSuite()`\n\nPerforms shared setup for all tests in the test suite. GoogleTest calls\n`SetUpTestSuite()` before running the first test in the test suite.\n\n##### TearDownTestSuite {#Test::TearDownTestSuite}\n\n`static void Test::TearDownTestSuite()`\n\nPerforms shared teardown for all tests in the test suite. GoogleTest calls\n`TearDownTestSuite()` after running the last test in the test suite.\n\n##### HasFatalFailure {#Test::HasFatalFailure}\n\n`static bool Test::HasFatalFailure()`\n\nReturns true if and only if the current test has a fatal failure.\n\n##### HasNonfatalFailure {#Test::HasNonfatalFailure}\n\n`static bool Test::HasNonfatalFailure()`\n\nReturns true if and only if the current test has a nonfatal failure.\n\n##### HasFailure {#Test::HasFailure}\n\n`static bool Test::HasFailure()`\n\nReturns true if and only if the current test has any failure, either fatal or\nnonfatal.\n\n##### IsSkipped {#Test::IsSkipped}\n\n`static bool Test::IsSkipped()`\n\nReturns true if and only if the current test was skipped.\n\n##### RecordProperty {#Test::RecordProperty}\n\n`static void Test::RecordProperty(const std::string& key, const std::string&\nvalue)` \\\n`static void Test::RecordProperty(const std::string& key, int value)`\n\nLogs a property for the current test, test suite, or entire invocation of the\ntest program. Only the last value for a given key is logged.\n\nThe key must be a valid XML attribute name, and cannot conflict with the ones\nalready used by GoogleTest (`name`, `file`, `line`, `status`, `time`,\n`classname`, `type_param`, and `value_param`).\n\n`RecordProperty` is `public static` so it can be called from utility functions\nthat are not members of the test fixture.\n\nCalls to `RecordProperty` made during the lifespan of the test (from the moment\nits constructor starts to the moment its destructor finishes) are output in XML\nas attributes of the `<testcase>` element. Properties recorded from a fixture's\n`SetUpTestSuite` or `TearDownTestSuite` methods are logged as attributes of the\ncorresponding `<testsuite>` element. Calls to `RecordProperty` made in the\nglobal context (before or after invocation of `RUN_ALL_TESTS` or from the\n`SetUp`/`TearDown` methods of registered `Environment` objects) are output as\nattributes of the `<testsuites>` element.\n\n#### Protected Methods {#Test-protected}\n\n##### SetUp {#Test::SetUp}\n\n`virtual void Test::SetUp()`\n\nOverride this to perform test fixture setup. GoogleTest calls `SetUp()` before\nrunning each individual test.\n\n##### TearDown {#Test::TearDown}\n\n`virtual void Test::TearDown()`\n\nOverride this to perform test fixture teardown. GoogleTest calls `TearDown()`\nafter running each individual test.\n\n### TestWithParam {#TestWithParam}\n\n`::testing::TestWithParam<T>`\n\nA convenience class which inherits from both [`Test`](#Test) and\n[`WithParamInterface<T>`](#WithParamInterface).\n\n### TestSuite {#TestSuite}\n\nRepresents a test suite. `TestSuite` is not copyable.\n\n#### Public Methods {#TestSuite-public}\n\n##### name {#TestSuite::name}\n\n`const char* TestSuite::name() const`\n\nGets the name of the test suite.\n\n##### type_param {#TestSuite::type_param}\n\n`const char* TestSuite::type_param() const`\n\nReturns the name of the parameter type, or `NULL` if this is not a typed or\ntype-parameterized test suite. See [Typed Tests](../advanced.md#typed-tests) and\n[Type-Parameterized Tests](../advanced.md#type-parameterized-tests).\n\n##### should_run {#TestSuite::should_run}\n\n`bool TestSuite::should_run() const`\n\nReturns true if any test in this test suite should run.\n\n##### successful_test_count {#TestSuite::successful_test_count}\n\n`int TestSuite::successful_test_count() const`\n\nGets the number of successful tests in this test suite.\n\n##### skipped_test_count {#TestSuite::skipped_test_count}\n\n`int TestSuite::skipped_test_count() const`\n\nGets the number of skipped tests in this test suite.\n\n##### failed_test_count {#TestSuite::failed_test_count}\n\n`int TestSuite::failed_test_count() const`\n\nGets the number of failed tests in this test suite.\n\n##### reportable_disabled_test_count {#TestSuite::reportable_disabled_test_count}\n\n`int TestSuite::reportable_disabled_test_count() const`\n\nGets the number of disabled tests that will be reported in the XML report.\n\n##### disabled_test_count {#TestSuite::disabled_test_count}\n\n`int TestSuite::disabled_test_count() const`\n\nGets the number of disabled tests in this test suite.\n\n##### reportable_test_count {#TestSuite::reportable_test_count}\n\n`int TestSuite::reportable_test_count() const`\n\nGets the number of tests to be printed in the XML report.\n\n##### test_to_run_count {#TestSuite::test_to_run_count}\n\n`int TestSuite::test_to_run_count() const`\n\nGet the number of tests in this test suite that should run.\n\n##### total_test_count {#TestSuite::total_test_count}\n\n`int TestSuite::total_test_count() const`\n\nGets the number of all tests in this test suite.\n\n##### Passed {#TestSuite::Passed}\n\n`bool TestSuite::Passed() const`\n\nReturns true if and only if the test suite passed.\n\n##### Failed {#TestSuite::Failed}\n\n`bool TestSuite::Failed() const`\n\nReturns true if and only if the test suite failed.\n\n##### elapsed_time {#TestSuite::elapsed_time}\n\n`TimeInMillis TestSuite::elapsed_time() const`\n\nReturns the elapsed time, in milliseconds.\n\n##### start_timestamp {#TestSuite::start_timestamp}\n\n`TimeInMillis TestSuite::start_timestamp() const`\n\nGets the time of the test suite start, in ms from the start of the UNIX epoch.\n\n##### GetTestInfo {#TestSuite::GetTestInfo}\n\n`const TestInfo* TestSuite::GetTestInfo(int i) const`\n\nReturns the [`TestInfo`](#TestInfo) for the `i`-th test among all the tests. `i`\ncan range from 0 to `total_test_count() - 1`. If `i` is not in that range,\nreturns `NULL`.\n\n##### ad_hoc_test_result {#TestSuite::ad_hoc_test_result}\n\n`const TestResult& TestSuite::ad_hoc_test_result() const`\n\nReturns the [`TestResult`](#TestResult) that holds test properties recorded\nduring execution of `SetUpTestSuite` and `TearDownTestSuite`.\n\n### TestInfo {#TestInfo}\n\n`::testing::TestInfo`\n\nStores information about a test.\n\n#### Public Methods {#TestInfo-public}\n\n##### test_suite_name {#TestInfo::test_suite_name}\n\n`const char* TestInfo::test_suite_name() const`\n\nReturns the test suite name.\n\n##### name {#TestInfo::name}\n\n`const char* TestInfo::name() const`\n\nReturns the test name.\n\n##### type_param {#TestInfo::type_param}\n\n`const char* TestInfo::type_param() const`\n\nReturns the name of the parameter type, or `NULL` if this is not a typed or\ntype-parameterized test. See [Typed Tests](../advanced.md#typed-tests) and\n[Type-Parameterized Tests](../advanced.md#type-parameterized-tests).\n\n##### value_param {#TestInfo::value_param}\n\n`const char* TestInfo::value_param() const`\n\nReturns the text representation of the value parameter, or `NULL` if this is not\na value-parameterized test. See\n[Value-Parameterized Tests](../advanced.md#value-parameterized-tests).\n\n##### file {#TestInfo::file}\n\n`const char* TestInfo::file() const`\n\nReturns the file name where this test is defined.\n\n##### line {#TestInfo::line}\n\n`int TestInfo::line() const`\n\nReturns the line where this test is defined.\n\n##### is_in_another_shard {#TestInfo::is_in_another_shard}\n\n`bool TestInfo::is_in_another_shard() const`\n\nReturns true if this test should not be run because it's in another shard.\n\n##### should_run {#TestInfo::should_run}\n\n`bool TestInfo::should_run() const`\n\nReturns true if this test should run, that is if the test is not disabled (or it\nis disabled but the `also_run_disabled_tests` flag has been specified) and its\nfull name matches the user-specified filter.\n\nGoogleTest allows the user to filter the tests by their full names. Only the\ntests that match the filter will run. See\n[Running a Subset of the Tests](../advanced.md#running-a-subset-of-the-tests)\nfor more information.\n\n##### is_reportable {#TestInfo::is_reportable}\n\n`bool TestInfo::is_reportable() const`\n\nReturns true if and only if this test will appear in the XML report.\n\n##### result {#TestInfo::result}\n\n`const TestResult* TestInfo::result() const`\n\nReturns the result of the test. See [`TestResult`](#TestResult).\n\n### TestParamInfo {#TestParamInfo}\n\n`::testing::TestParamInfo<T>`\n\nDescribes a parameter to a value-parameterized test. The type `T` is the type of\nthe parameter.\n\nContains the fields `param` and `index` which hold the value of the parameter\nand its integer index respectively.\n\n### UnitTest {#UnitTest}\n\n`::testing::UnitTest`\n\nThis class contains information about the test program.\n\n`UnitTest` is a singleton class. The only instance is created when\n`UnitTest::GetInstance()` is first called. This instance is never deleted.\n\n`UnitTest` is not copyable.\n\n#### Public Methods {#UnitTest-public}\n\n##### GetInstance {#UnitTest::GetInstance}\n\n`static UnitTest* UnitTest::GetInstance()`\n\nGets the singleton `UnitTest` object. The first time this method is called, a\n`UnitTest` object is constructed and returned. Consecutive calls will return the\nsame object.\n\n##### original_working_dir {#UnitTest::original_working_dir}\n\n`const char* UnitTest::original_working_dir() const`\n\nReturns the working directory when the first [`TEST()`](#TEST) or\n[`TEST_F()`](#TEST_F) was executed. The `UnitTest` object owns the string.\n\n##### current_test_suite {#UnitTest::current_test_suite}\n\n`const TestSuite* UnitTest::current_test_suite() const`\n\nReturns the [`TestSuite`](#TestSuite) object for the test that's currently\nrunning, or `NULL` if no test is running.\n\n##### current_test_info {#UnitTest::current_test_info}\n\n`const TestInfo* UnitTest::current_test_info() const`\n\nReturns the [`TestInfo`](#TestInfo) object for the test that's currently\nrunning, or `NULL` if no test is running.\n\n##### random_seed {#UnitTest::random_seed}\n\n`int UnitTest::random_seed() const`\n\nReturns the random seed used at the start of the current test run.\n\n##### successful_test_suite_count {#UnitTest::successful_test_suite_count}\n\n`int UnitTest::successful_test_suite_count() const`\n\nGets the number of successful test suites.\n\n##### failed_test_suite_count {#UnitTest::failed_test_suite_count}\n\n`int UnitTest::failed_test_suite_count() const`\n\nGets the number of failed test suites.\n\n##### total_test_suite_count {#UnitTest::total_test_suite_count}\n\n`int UnitTest::total_test_suite_count() const`\n\nGets the number of all test suites.\n\n##### test_suite_to_run_count {#UnitTest::test_suite_to_run_count}\n\n`int UnitTest::test_suite_to_run_count() const`\n\nGets the number of all test suites that contain at least one test that should\nrun.\n\n##### successful_test_count {#UnitTest::successful_test_count}\n\n`int UnitTest::successful_test_count() const`\n\nGets the number of successful tests.\n\n##### skipped_test_count {#UnitTest::skipped_test_count}\n\n`int UnitTest::skipped_test_count() const`\n\nGets the number of skipped tests.\n\n##### failed_test_count {#UnitTest::failed_test_count}\n\n`int UnitTest::failed_test_count() const`\n\nGets the number of failed tests.\n\n##### reportable_disabled_test_count {#UnitTest::reportable_disabled_test_count}\n\n`int UnitTest::reportable_disabled_test_count() const`\n\nGets the number of disabled tests that will be reported in the XML report.\n\n##### disabled_test_count {#UnitTest::disabled_test_count}\n\n`int UnitTest::disabled_test_count() const`\n\nGets the number of disabled tests.\n\n##### reportable_test_count {#UnitTest::reportable_test_count}\n\n`int UnitTest::reportable_test_count() const`\n\nGets the number of tests to be printed in the XML report.\n\n##### total_test_count {#UnitTest::total_test_count}\n\n`int UnitTest::total_test_count() const`\n\nGets the number of all tests.\n\n##### test_to_run_count {#UnitTest::test_to_run_count}\n\n`int UnitTest::test_to_run_count() const`\n\nGets the number of tests that should run.\n\n##### start_timestamp {#UnitTest::start_timestamp}\n\n`TimeInMillis UnitTest::start_timestamp() const`\n\nGets the time of the test program start, in ms from the start of the UNIX epoch.\n\n##### elapsed_time {#UnitTest::elapsed_time}\n\n`TimeInMillis UnitTest::elapsed_time() const`\n\nGets the elapsed time, in milliseconds.\n\n##### Passed {#UnitTest::Passed}\n\n`bool UnitTest::Passed() const`\n\nReturns true if and only if the unit test passed (i.e. all test suites passed).\n\n##### Failed {#UnitTest::Failed}\n\n`bool UnitTest::Failed() const`\n\nReturns true if and only if the unit test failed (i.e. some test suite failed or\nsomething outside of all tests failed).\n\n##### GetTestSuite {#UnitTest::GetTestSuite}\n\n`const TestSuite* UnitTest::GetTestSuite(int i) const`\n\nGets the [`TestSuite`](#TestSuite) object for the `i`-th test suite among all\nthe test suites. `i` can range from 0 to `total_test_suite_count() - 1`. If `i`\nis not in that range, returns `NULL`.\n\n##### ad_hoc_test_result {#UnitTest::ad_hoc_test_result}\n\n`const TestResult& UnitTest::ad_hoc_test_result() const`\n\nReturns the [`TestResult`](#TestResult) containing information on test failures\nand properties logged outside of individual test suites.\n\n##### listeners {#UnitTest::listeners}\n\n`TestEventListeners& UnitTest::listeners()`\n\nReturns the list of event listeners that can be used to track events inside\nGoogleTest. See [`TestEventListeners`](#TestEventListeners).\n\n### TestEventListener {#TestEventListener}\n\n`::testing::TestEventListener`\n\nThe interface for tracing execution of tests. The methods below are listed in\nthe order the corresponding events are fired.\n\n#### Public Methods {#TestEventListener-public}\n\n##### OnTestProgramStart {#TestEventListener::OnTestProgramStart}\n\n`virtual void TestEventListener::OnTestProgramStart(const UnitTest& unit_test)`\n\nFired before any test activity starts.\n\n##### OnTestIterationStart {#TestEventListener::OnTestIterationStart}\n\n`virtual void TestEventListener::OnTestIterationStart(const UnitTest& unit_test,\nint iteration)`\n\nFired before each iteration of tests starts. There may be more than one\niteration if `GTEST_FLAG(repeat)` is set. `iteration` is the iteration index,\nstarting from 0.\n\n##### OnEnvironmentsSetUpStart {#TestEventListener::OnEnvironmentsSetUpStart}\n\n`virtual void TestEventListener::OnEnvironmentsSetUpStart(const UnitTest&\nunit_test)`\n\nFired before environment set-up for each iteration of tests starts.\n\n##### OnEnvironmentsSetUpEnd {#TestEventListener::OnEnvironmentsSetUpEnd}\n\n`virtual void TestEventListener::OnEnvironmentsSetUpEnd(const UnitTest&\nunit_test)`\n\nFired after environment set-up for each iteration of tests ends.\n\n##### OnTestSuiteStart {#TestEventListener::OnTestSuiteStart}\n\n`virtual void TestEventListener::OnTestSuiteStart(const TestSuite& test_suite)`\n\nFired before the test suite starts.\n\n##### OnTestStart {#TestEventListener::OnTestStart}\n\n`virtual void TestEventListener::OnTestStart(const TestInfo& test_info)`\n\nFired before the test starts.\n\n##### OnTestPartResult {#TestEventListener::OnTestPartResult}\n\n`virtual void TestEventListener::OnTestPartResult(const TestPartResult&\ntest_part_result)`\n\nFired after a failed assertion or a `SUCCEED()` invocation. If you want to throw\nan exception from this function to skip to the next test, it must be an\n[`AssertionException`](#AssertionException) or inherited from it.\n\n##### OnTestEnd {#TestEventListener::OnTestEnd}\n\n`virtual void TestEventListener::OnTestEnd(const TestInfo& test_info)`\n\nFired after the test ends.\n\n##### OnTestSuiteEnd {#TestEventListener::OnTestSuiteEnd}\n\n`virtual void TestEventListener::OnTestSuiteEnd(const TestSuite& test_suite)`\n\nFired after the test suite ends.\n\n##### OnEnvironmentsTearDownStart {#TestEventListener::OnEnvironmentsTearDownStart}\n\n`virtual void TestEventListener::OnEnvironmentsTearDownStart(const UnitTest&\nunit_test)`\n\nFired before environment tear-down for each iteration of tests starts.\n\n##### OnEnvironmentsTearDownEnd {#TestEventListener::OnEnvironmentsTearDownEnd}\n\n`virtual void TestEventListener::OnEnvironmentsTearDownEnd(const UnitTest&\nunit_test)`\n\nFired after environment tear-down for each iteration of tests ends.\n\n##### OnTestIterationEnd {#TestEventListener::OnTestIterationEnd}\n\n`virtual void TestEventListener::OnTestIterationEnd(const UnitTest& unit_test,\nint iteration)`\n\nFired after each iteration of tests finishes.\n\n##### OnTestProgramEnd {#TestEventListener::OnTestProgramEnd}\n\n`virtual void TestEventListener::OnTestProgramEnd(const UnitTest& unit_test)`\n\nFired after all test activities have ended.\n\n### TestEventListeners {#TestEventListeners}\n\n`::testing::TestEventListeners`\n\nLets users add listeners to track events in GoogleTest.\n\n#### Public Methods {#TestEventListeners-public}\n\n##### Append {#TestEventListeners::Append}\n\n`void TestEventListeners::Append(TestEventListener* listener)`\n\nAppends an event listener to the end of the list. GoogleTest assumes ownership\nof the listener (i.e. it will delete the listener when the test program\nfinishes).\n\n##### Release {#TestEventListeners::Release}\n\n`TestEventListener* TestEventListeners::Release(TestEventListener* listener)`\n\nRemoves the given event listener from the list and returns it. It then becomes\nthe caller's responsibility to delete the listener. Returns `NULL` if the\nlistener is not found in the list.\n\n##### default_result_printer {#TestEventListeners::default_result_printer}\n\n`TestEventListener* TestEventListeners::default_result_printer() const`\n\nReturns the standard listener responsible for the default console output. Can be\nremoved from the listeners list to shut down default console output. Note that\nremoving this object from the listener list with\n[`Release()`](#TestEventListeners::Release) transfers its ownership to the\ncaller and makes this function return `NULL` the next time.\n\n##### default_xml_generator {#TestEventListeners::default_xml_generator}\n\n`TestEventListener* TestEventListeners::default_xml_generator() const`\n\nReturns the standard listener responsible for the default XML output controlled\nby the `--gtest_output=xml` flag. Can be removed from the listeners list by\nusers who want to shut down the default XML output controlled by this flag and\nsubstitute it with custom one. Note that removing this object from the listener\nlist with [`Release()`](#TestEventListeners::Release) transfers its ownership to\nthe caller and makes this function return `NULL` the next time.\n\n### TestPartResult {#TestPartResult}\n\n`::testing::TestPartResult`\n\nA copyable object representing the result of a test part (i.e. an assertion or\nan explicit `FAIL()`, `ADD_FAILURE()`, or `SUCCESS()`).\n\n#### Public Methods {#TestPartResult-public}\n\n##### type {#TestPartResult::type}\n\n`Type TestPartResult::type() const`\n\nGets the outcome of the test part.\n\nThe return type `Type` is an enum defined as follows:\n\n```cpp\nenum Type {\n  kSuccess,          // Succeeded.\n  kNonFatalFailure,  // Failed but the test can continue.\n  kFatalFailure,     // Failed and the test should be terminated.\n  kSkip              // Skipped.\n};\n```\n\n##### file_name {#TestPartResult::file_name}\n\n`const char* TestPartResult::file_name() const`\n\nGets the name of the source file where the test part took place, or `NULL` if\nit's unknown.\n\n##### line_number {#TestPartResult::line_number}\n\n`int TestPartResult::line_number() const`\n\nGets the line in the source file where the test part took place, or `-1` if it's\nunknown.\n\n##### summary {#TestPartResult::summary}\n\n`const char* TestPartResult::summary() const`\n\nGets the summary of the failure message.\n\n##### message {#TestPartResult::message}\n\n`const char* TestPartResult::message() const`\n\nGets the message associated with the test part.\n\n##### skipped {#TestPartResult::skipped}\n\n`bool TestPartResult::skipped() const`\n\nReturns true if and only if the test part was skipped.\n\n##### passed {#TestPartResult::passed}\n\n`bool TestPartResult::passed() const`\n\nReturns true if and only if the test part passed.\n\n##### nonfatally_failed {#TestPartResult::nonfatally_failed}\n\n`bool TestPartResult::nonfatally_failed() const`\n\nReturns true if and only if the test part non-fatally failed.\n\n##### fatally_failed {#TestPartResult::fatally_failed}\n\n`bool TestPartResult::fatally_failed() const`\n\nReturns true if and only if the test part fatally failed.\n\n##### failed {#TestPartResult::failed}\n\n`bool TestPartResult::failed() const`\n\nReturns true if and only if the test part failed.\n\n### TestProperty {#TestProperty}\n\n`::testing::TestProperty`\n\nA copyable object representing a user-specified test property which can be\noutput as a key/value string pair.\n\n#### Public Methods {#TestProperty-public}\n\n##### key {#key}\n\n`const char* key() const`\n\nGets the user-supplied key.\n\n##### value {#value}\n\n`const char* value() const`\n\nGets the user-supplied value.\n\n##### SetValue {#SetValue}\n\n`void SetValue(const std::string& new_value)`\n\nSets a new value, overriding the previous one.\n\n### TestResult {#TestResult}\n\n`::testing::TestResult`\n\nContains information about the result of a single test.\n\n`TestResult` is not copyable.\n\n#### Public Methods {#TestResult-public}\n\n##### total_part_count {#TestResult::total_part_count}\n\n`int TestResult::total_part_count() const`\n\nGets the number of all test parts. This is the sum of the number of successful\ntest parts and the number of failed test parts.\n\n##### test_property_count {#TestResult::test_property_count}\n\n`int TestResult::test_property_count() const`\n\nReturns the number of test properties.\n\n##### Passed {#TestResult::Passed}\n\n`bool TestResult::Passed() const`\n\nReturns true if and only if the test passed (i.e. no test part failed).\n\n##### Skipped {#TestResult::Skipped}\n\n`bool TestResult::Skipped() const`\n\nReturns true if and only if the test was skipped.\n\n##### Failed {#TestResult::Failed}\n\n`bool TestResult::Failed() const`\n\nReturns true if and only if the test failed.\n\n##### HasFatalFailure {#TestResult::HasFatalFailure}\n\n`bool TestResult::HasFatalFailure() const`\n\nReturns true if and only if the test fatally failed.\n\n##### HasNonfatalFailure {#TestResult::HasNonfatalFailure}\n\n`bool TestResult::HasNonfatalFailure() const`\n\nReturns true if and only if the test has a non-fatal failure.\n\n##### elapsed_time {#TestResult::elapsed_time}\n\n`TimeInMillis TestResult::elapsed_time() const`\n\nReturns the elapsed time, in milliseconds.\n\n##### start_timestamp {#TestResult::start_timestamp}\n\n`TimeInMillis TestResult::start_timestamp() const`\n\nGets the time of the test case start, in ms from the start of the UNIX epoch.\n\n##### GetTestPartResult {#TestResult::GetTestPartResult}\n\n`const TestPartResult& TestResult::GetTestPartResult(int i) const`\n\nReturns the [`TestPartResult`](#TestPartResult) for the `i`-th test part result\namong all the results. `i` can range from 0 to `total_part_count() - 1`. If `i`\nis not in that range, aborts the program.\n\n##### GetTestProperty {#TestResult::GetTestProperty}\n\n`const TestProperty& TestResult::GetTestProperty(int i) const`\n\nReturns the [`TestProperty`](#TestProperty) object for the `i`-th test property.\n`i` can range from 0 to `test_property_count() - 1`. If `i` is not in that\nrange, aborts the program.\n\n### TimeInMillis {#TimeInMillis}\n\n`::testing::TimeInMillis`\n\nAn integer type representing time in milliseconds.\n\n### Types {#Types}\n\n`::testing::Types<T...>`\n\nRepresents a list of types for use in typed tests and type-parameterized tests.\n\nThe template argument `T...` can be any number of types, for example:\n\n```\n::testing::Types<char, int, unsigned int>\n```\n\nSee [Typed Tests](../advanced.md#typed-tests) and\n[Type-Parameterized Tests](../advanced.md#type-parameterized-tests) for more\ninformation.\n\n### WithParamInterface {#WithParamInterface}\n\n`::testing::WithParamInterface<T>`\n\nThe pure interface class that all value-parameterized tests inherit from.\n\nA value-parameterized test fixture class must inherit from both [`Test`](#Test)\nand `WithParamInterface`. In most cases that just means inheriting from\n[`TestWithParam`](#TestWithParam), but more complicated test hierarchies may\nneed to inherit from `Test` and `WithParamInterface` at different levels.\n\nThis interface defines the type alias `ParamType` for the parameter type `T` and\nhas support for accessing the test parameter value via the `GetParam()` method:\n\n```\nstatic const ParamType& GetParam()\n```\n\nFor more information, see\n[Value-Parameterized Tests](../advanced.md#value-parameterized-tests).\n\n## Functions\n\nGoogleTest defines the following functions to help with writing and running\ntests.\n\n### InitGoogleTest {#InitGoogleTest}\n\n`void ::testing::InitGoogleTest(int* argc, char** argv)` \\\n`void ::testing::InitGoogleTest(int* argc, wchar_t** argv)` \\\n`void ::testing::InitGoogleTest()`\n\nInitializes GoogleTest. This must be called before calling\n[`RUN_ALL_TESTS()`](#RUN_ALL_TESTS). In particular, it parses the command line\nfor the flags that GoogleTest recognizes. Whenever a GoogleTest flag is seen, it\nis removed from `argv`, and `*argc` is decremented.\n\nNo value is returned. Instead, the GoogleTest flag variables are updated.\n\nThe `InitGoogleTest(int* argc, wchar_t** argv)` overload can be used in Windows\nprograms compiled in `UNICODE` mode.\n\nThe argument-less `InitGoogleTest()` overload can be used on Arduino/embedded\nplatforms where there is no `argc`/`argv`.\n\n### AddGlobalTestEnvironment {#AddGlobalTestEnvironment}\n\n`Environment* ::testing::AddGlobalTestEnvironment(Environment* env)`\n\nAdds a test environment to the test program. Must be called before\n[`RUN_ALL_TESTS()`](#RUN_ALL_TESTS) is called. See\n[Global Set-Up and Tear-Down](../advanced.md#global-set-up-and-tear-down) for\nmore information.\n\nSee also [`Environment`](#Environment).\n\n### RegisterTest {#RegisterTest}\n\n```cpp\ntemplate <typename Factory>\nTestInfo* ::testing::RegisterTest(const char* test_suite_name, const char* test_name,\n                                  const char* type_param, const char* value_param,\n                                  const char* file, int line, Factory factory)\n```\n\nDynamically registers a test with the framework.\n\nThe `factory` argument is a factory callable (move-constructible) object or\nfunction pointer that creates a new instance of the `Test` object. It handles\nownership to the caller. The signature of the callable is `Fixture*()`, where\n`Fixture` is the test fixture class for the test. All tests registered with the\nsame `test_suite_name` must return the same fixture type. This is checked at\nruntime.\n\nThe framework will infer the fixture class from the factory and will call the\n`SetUpTestSuite` and `TearDownTestSuite` methods for it.\n\nMust be called before [`RUN_ALL_TESTS()`](#RUN_ALL_TESTS) is invoked, otherwise\nbehavior is undefined.\n\nSee\n[Registering tests programmatically](../advanced.md#registering-tests-programmatically)\nfor more information.\n\n### RUN_ALL_TESTS {#RUN_ALL_TESTS}\n\n`int RUN_ALL_TESTS()`\n\nUse this function in `main()` to run all tests. It returns `0` if all tests are\nsuccessful, or `1` otherwise.\n\n`RUN_ALL_TESTS()` should be invoked after the command line has been parsed by\n[`InitGoogleTest()`](#InitGoogleTest).\n\nThis function was formerly a macro; thus, it is in the global namespace and has\nan all-caps name.\n\n### AssertionSuccess {#AssertionSuccess}\n\n`AssertionResult ::testing::AssertionSuccess()`\n\nCreates a successful assertion result. See\n[`AssertionResult`](#AssertionResult).\n\n### AssertionFailure {#AssertionFailure}\n\n`AssertionResult ::testing::AssertionFailure()`\n\nCreates a failed assertion result. Use the `<<` operator to store a failure\nmessage:\n\n```cpp\n::testing::AssertionFailure() << \"My failure message\";\n```\n\nSee [`AssertionResult`](#AssertionResult).\n\n### StaticAssertTypeEq {#StaticAssertTypeEq}\n\n`::testing::StaticAssertTypeEq<T1, T2>()`\n\nCompile-time assertion for type equality. Compiles if and only if `T1` and `T2`\nare the same type. The value it returns is irrelevant.\n\nSee [Type Assertions](../advanced.md#type-assertions) for more information.\n\n### PrintToString {#PrintToString}\n\n`std::string ::testing::PrintToString(x)`\n\nPrints any value `x` using GoogleTest's value printer.\n\nSee\n[Teaching GoogleTest How to Print Your Values](../advanced.md#teaching-googletest-how-to-print-your-values)\nfor more information.\n\n### PrintToStringParamName {#PrintToStringParamName}\n\n`std::string ::testing::PrintToStringParamName(TestParamInfo<T>& info)`\n\nA built-in parameterized test name generator which returns the result of\n[`PrintToString`](#PrintToString) called on `info.param`. Does not work when the\ntest parameter is a `std::string` or C string. See\n[Specifying Names for Value-Parameterized Test Parameters](../advanced.md#specifying-names-for-value-parameterized-test-parameters)\nfor more information.\n\nSee also [`TestParamInfo`](#TestParamInfo) and\n[`INSTANTIATE_TEST_SUITE_P`](#INSTANTIATE_TEST_SUITE_P).\n"
  },
  {
    "path": "3rd/googletest-1.12.1/docs/samples.md",
    "content": "# Googletest Samples\n\nIf you're like us, you'd like to look at\n[googletest samples.](https://github.com/google/googletest/tree/master/googletest/samples)\nThe sample directory has a number of well-commented samples showing how to use a\nvariety of googletest features.\n\n*   Sample #1 shows the basic steps of using googletest to test C++ functions.\n*   Sample #2 shows a more complex unit test for a class with multiple member\n    functions.\n*   Sample #3 uses a test fixture.\n*   Sample #4 teaches you how to use googletest and `googletest.h` together to\n    get the best of both libraries.\n*   Sample #5 puts shared testing logic in a base test fixture, and reuses it in\n    derived fixtures.\n*   Sample #6 demonstrates type-parameterized tests.\n*   Sample #7 teaches the basics of value-parameterized tests.\n*   Sample #8 shows using `Combine()` in value-parameterized tests.\n*   Sample #9 shows use of the listener API to modify Google Test's console\n    output and the use of its reflection API to inspect test results.\n*   Sample #10 shows use of the listener API to implement a primitive memory\n    leak checker.\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/CMakeLists.txt",
    "content": "########################################################################\n# Note: CMake support is community-based. The maintainers do not use CMake\n# internally.\n#\n# CMake build script for Google Mock.\n#\n# To run the tests for Google Mock itself on Linux, use 'make test' or\n# ctest.  You can select which tests to run using 'ctest -R regex'.\n# For more options, run 'ctest --help'.\n\noption(gmock_build_tests \"Build all of Google Mock's own tests.\" OFF)\n\n# A directory to find Google Test sources.\nif (EXISTS \"${CMAKE_CURRENT_SOURCE_DIR}/gtest/CMakeLists.txt\")\n  set(gtest_dir gtest)\nelse()\n  set(gtest_dir ../googletest)\nendif()\n\n# Defines pre_project_set_up_hermetic_build() and set_up_hermetic_build().\ninclude(\"${gtest_dir}/cmake/hermetic_build.cmake\" OPTIONAL)\n\nif (COMMAND pre_project_set_up_hermetic_build)\n  # Google Test also calls hermetic setup functions from add_subdirectory,\n  # although its changes will not affect things at the current scope.\n  pre_project_set_up_hermetic_build()\nendif()\n\n########################################################################\n#\n# Project-wide settings\n\n# Name of the project.\n#\n# CMake files in this project can refer to the root source directory\n# as ${gmock_SOURCE_DIR} and to the root binary directory as\n# ${gmock_BINARY_DIR}.\n# Language \"C\" is required for find_package(Threads).\ncmake_minimum_required(VERSION 3.5)\ncmake_policy(SET CMP0048 NEW)\nproject(gmock VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C)\n\nif (COMMAND set_up_hermetic_build)\n  set_up_hermetic_build()\nendif()\n\n# Instructs CMake to process Google Test's CMakeLists.txt and add its\n# targets to the current scope.  We are placing Google Test's binary\n# directory in a subdirectory of our own as VC compilation may break\n# if they are the same (the default).\nadd_subdirectory(\"${gtest_dir}\" \"${gmock_BINARY_DIR}/${gtest_dir}\")\n\n\n# These commands only run if this is the main project\nif(CMAKE_PROJECT_NAME STREQUAL \"gmock\" OR CMAKE_PROJECT_NAME STREQUAL \"googletest-distribution\")\n  # BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to\n  # make it prominent in the GUI.\n  option(BUILD_SHARED_LIBS \"Build shared libraries (DLLs).\" OFF)\nelse()\n  mark_as_advanced(gmock_build_tests)\nendif()\n\n# Although Google Test's CMakeLists.txt calls this function, the\n# changes there don't affect the current scope.  Therefore we have to\n# call it again here.\nconfig_compiler_and_linker()  # from ${gtest_dir}/cmake/internal_utils.cmake\n\n# Adds Google Mock's and Google Test's header directories to the search path.\nset(gmock_build_include_dirs\n  \"${gmock_SOURCE_DIR}/include\"\n  \"${gmock_SOURCE_DIR}\"\n  \"${gtest_SOURCE_DIR}/include\"\n  # This directory is needed to build directly from Google Test sources.\n  \"${gtest_SOURCE_DIR}\")\ninclude_directories(${gmock_build_include_dirs})\n\n########################################################################\n#\n# Defines the gmock & gmock_main libraries.  User tests should link\n# with one of them.\n\n# Google Mock libraries.  We build them using more strict warnings than what\n# are used for other targets, to ensure that Google Mock can be compiled by\n# a user aggressive about warnings.\nif (MSVC)\n  cxx_library(gmock\n              \"${cxx_strict}\"\n              \"${gtest_dir}/src/gtest-all.cc\"\n              src/gmock-all.cc)\n\n  cxx_library(gmock_main\n              \"${cxx_strict}\"\n              \"${gtest_dir}/src/gtest-all.cc\"\n              src/gmock-all.cc\n              src/gmock_main.cc)\nelse()\n  cxx_library(gmock \"${cxx_strict}\" src/gmock-all.cc)\n  target_link_libraries(gmock PUBLIC gtest)\n  set_target_properties(gmock PROPERTIES VERSION ${GOOGLETEST_VERSION})\n  cxx_library(gmock_main \"${cxx_strict}\" src/gmock_main.cc)\n  target_link_libraries(gmock_main PUBLIC gmock)\n  set_target_properties(gmock_main PROPERTIES VERSION ${GOOGLETEST_VERSION})\nendif()\n# If the CMake version supports it, attach header directory information\n# to the targets for when we are part of a parent build (ie being pulled\n# in via add_subdirectory() rather than being a standalone build).\nif (DEFINED CMAKE_VERSION AND NOT \"${CMAKE_VERSION}\" VERSION_LESS \"2.8.11\")\n  string(REPLACE \";\" \"$<SEMICOLON>\" dirs \"${gmock_build_include_dirs}\")\n  target_include_directories(gmock SYSTEM INTERFACE\n    \"$<BUILD_INTERFACE:${dirs}>\"\n    \"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>\")\n  target_include_directories(gmock_main SYSTEM INTERFACE\n    \"$<BUILD_INTERFACE:${dirs}>\"\n    \"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>\")\nendif()\n\n########################################################################\n#\n# Install rules\ninstall_project(gmock gmock_main)\n\n########################################################################\n#\n# Google Mock's own tests.\n#\n# You can skip this section if you aren't interested in testing\n# Google Mock itself.\n#\n# The tests are not built by default.  To build them, set the\n# gmock_build_tests option to ON.  You can do it by running ccmake\n# or specifying the -Dgmock_build_tests=ON flag when running cmake.\n\nif (gmock_build_tests)\n  # This must be set in the root directory for the tests to be run by\n  # 'make test' or ctest.\n  enable_testing()\n\n  if (MINGW OR CYGWIN)\n    if (CMAKE_VERSION VERSION_LESS \"2.8.12\")\n      add_compile_options(\"-Wa,-mbig-obj\")\n    else()\n      add_definitions(\"-Wa,-mbig-obj\")\n    endif()\n  endif()\n\n  ############################################################\n  # C++ tests built with standard compiler flags.\n\n  cxx_test(gmock-actions_test gmock_main)\n  cxx_test(gmock-cardinalities_test gmock_main)\n  cxx_test(gmock_ex_test gmock_main)\n  cxx_test(gmock-function-mocker_test gmock_main)\n  cxx_test(gmock-internal-utils_test gmock_main)\n  cxx_test(gmock-matchers-arithmetic_test gmock_main)\n  cxx_test(gmock-matchers-comparisons_test gmock_main)\n  cxx_test(gmock-matchers-containers_test gmock_main)\n  cxx_test(gmock-matchers-misc_test gmock_main)\n  cxx_test(gmock-more-actions_test gmock_main)\n  cxx_test(gmock-nice-strict_test gmock_main)\n  cxx_test(gmock-port_test gmock_main)\n  cxx_test(gmock-spec-builders_test gmock_main)\n  cxx_test(gmock_link_test gmock_main test/gmock_link2_test.cc)\n  cxx_test(gmock_test gmock_main)\n\n  if (DEFINED GTEST_HAS_PTHREAD)\n    cxx_test(gmock_stress_test gmock)\n  endif()\n\n  # gmock_all_test is commented to save time building and running tests.\n  # Uncomment if necessary.\n  # cxx_test(gmock_all_test gmock_main)\n\n  ############################################################\n  # C++ tests built with non-standard compiler flags.\n\n  if (MSVC)\n    cxx_library(gmock_main_no_exception \"${cxx_no_exception}\"\n      \"${gtest_dir}/src/gtest-all.cc\" src/gmock-all.cc src/gmock_main.cc)\n\n    cxx_library(gmock_main_no_rtti \"${cxx_no_rtti}\"\n      \"${gtest_dir}/src/gtest-all.cc\" src/gmock-all.cc src/gmock_main.cc)\n\n  else()\n    cxx_library(gmock_main_no_exception \"${cxx_no_exception}\" src/gmock_main.cc)\n    target_link_libraries(gmock_main_no_exception PUBLIC gmock)\n\n    cxx_library(gmock_main_no_rtti \"${cxx_no_rtti}\" src/gmock_main.cc)\n    target_link_libraries(gmock_main_no_rtti PUBLIC gmock)\n  endif()\n  cxx_test_with_flags(gmock-more-actions_no_exception_test \"${cxx_no_exception}\"\n    gmock_main_no_exception test/gmock-more-actions_test.cc)\n\n  cxx_test_with_flags(gmock_no_rtti_test \"${cxx_no_rtti}\"\n    gmock_main_no_rtti test/gmock-spec-builders_test.cc)\n\n  cxx_shared_library(shared_gmock_main \"${cxx_default}\"\n    \"${gtest_dir}/src/gtest-all.cc\" src/gmock-all.cc src/gmock_main.cc)\n\n  # Tests that a binary can be built with Google Mock as a shared library.  On\n  # some system configurations, it may not possible to run the binary without\n  # knowing more details about the system configurations. We do not try to run\n  # this binary. To get a more robust shared library coverage, configure with\n  # -DBUILD_SHARED_LIBS=ON.\n  cxx_executable_with_flags(shared_gmock_test_ \"${cxx_default}\"\n    shared_gmock_main test/gmock-spec-builders_test.cc)\n  set_target_properties(shared_gmock_test_\n    PROPERTIES\n    COMPILE_DEFINITIONS \"GTEST_LINKED_AS_SHARED_LIBRARY=1\")\n\n  ############################################################\n  # Python tests.\n\n  cxx_executable(gmock_leak_test_ test gmock_main)\n  py_test(gmock_leak_test)\n\n  cxx_executable(gmock_output_test_ test gmock)\n  py_test(gmock_output_test)\nendif()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/README.md",
    "content": "# Googletest Mocking (gMock) Framework\n\n### Overview\n\nGoogle's framework for writing and using C++ mock classes. It can help you\nderive better designs of your system and write better tests.\n\nIt is inspired by:\n\n*   [jMock](http://www.jmock.org/)\n*   [EasyMock](http://www.easymock.org/)\n*   [Hamcrest](http://code.google.com/p/hamcrest/)\n\nIt is designed with C++'s specifics in mind.\n\ngMock:\n\n-   Provides a declarative syntax for defining mocks.\n-   Can define partial (hybrid) mocks, which are a cross of real and mock\n    objects.\n-   Handles functions of arbitrary types and overloaded functions.\n-   Comes with a rich set of matchers for validating function arguments.\n-   Uses an intuitive syntax for controlling the behavior of a mock.\n-   Does automatic verification of expectations (no record-and-replay needed).\n-   Allows arbitrary (partial) ordering constraints on function calls to be\n    expressed.\n-   Lets a user extend it by defining new matchers and actions.\n-   Does not use exceptions.\n-   Is easy to learn and use.\n\nDetails and examples can be found here:\n\n*   [gMock for Dummies](https://google.github.io/googletest/gmock_for_dummies.html)\n*   [Legacy gMock FAQ](https://google.github.io/googletest/gmock_faq.html)\n*   [gMock Cookbook](https://google.github.io/googletest/gmock_cook_book.html)\n*   [gMock Cheat Sheet](https://google.github.io/googletest/gmock_cheat_sheet.html)\n\nGoogleMock is a part of\n[GoogleTest C++ testing framework](http://github.com/google/googletest/) and a\nsubject to the same requirements.\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/cmake/gmock.pc.in",
    "content": "libdir=@CMAKE_INSTALL_FULL_LIBDIR@\nincludedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@\n\nName: gmock\nDescription: GoogleMock (without main() function)\nVersion: @PROJECT_VERSION@\nURL: https://github.com/google/googletest\nRequires: gtest = @PROJECT_VERSION@\nLibs: -L${libdir} -lgmock @CMAKE_THREAD_LIBS_INIT@\nCflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/cmake/gmock_main.pc.in",
    "content": "libdir=@CMAKE_INSTALL_FULL_LIBDIR@\nincludedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@\n\nName: gmock_main\nDescription: GoogleMock (with main() function)\nVersion: @PROJECT_VERSION@\nURL: https://github.com/google/googletest\nRequires: gmock = @PROJECT_VERSION@\nLibs: -L${libdir} -lgmock_main @CMAKE_THREAD_LIBS_INIT@\nCflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/docs/README.md",
    "content": "# Content Moved\n\nWe are working on updates to the GoogleTest documentation, which has moved to\nthe top-level [docs](../../docs) directory.\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/include/gmock/gmock-actions.h",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// The ACTION* family of macros can be used in a namespace scope to\n// define custom actions easily.  The syntax:\n//\n//   ACTION(name) { statements; }\n//\n// will define an action with the given name that executes the\n// statements.  The value returned by the statements will be used as\n// the return value of the action.  Inside the statements, you can\n// refer to the K-th (0-based) argument of the mock function by\n// 'argK', and refer to its type by 'argK_type'.  For example:\n//\n//   ACTION(IncrementArg1) {\n//     arg1_type temp = arg1;\n//     return ++(*temp);\n//   }\n//\n// allows you to write\n//\n//   ...WillOnce(IncrementArg1());\n//\n// You can also refer to the entire argument tuple and its type by\n// 'args' and 'args_type', and refer to the mock function type and its\n// return type by 'function_type' and 'return_type'.\n//\n// Note that you don't need to specify the types of the mock function\n// arguments.  However rest assured that your code is still type-safe:\n// you'll get a compiler error if *arg1 doesn't support the ++\n// operator, or if the type of ++(*arg1) isn't compatible with the\n// mock function's return type, for example.\n//\n// Sometimes you'll want to parameterize the action.   For that you can use\n// another macro:\n//\n//   ACTION_P(name, param_name) { statements; }\n//\n// For example:\n//\n//   ACTION_P(Add, n) { return arg0 + n; }\n//\n// will allow you to write:\n//\n//   ...WillOnce(Add(5));\n//\n// Note that you don't need to provide the type of the parameter\n// either.  If you need to reference the type of a parameter named\n// 'foo', you can write 'foo_type'.  For example, in the body of\n// ACTION_P(Add, n) above, you can write 'n_type' to refer to the type\n// of 'n'.\n//\n// We also provide ACTION_P2, ACTION_P3, ..., up to ACTION_P10 to support\n// multi-parameter actions.\n//\n// For the purpose of typing, you can view\n//\n//   ACTION_Pk(Foo, p1, ..., pk) { ... }\n//\n// as shorthand for\n//\n//   template <typename p1_type, ..., typename pk_type>\n//   FooActionPk<p1_type, ..., pk_type> Foo(p1_type p1, ..., pk_type pk) { ... }\n//\n// In particular, you can provide the template type arguments\n// explicitly when invoking Foo(), as in Foo<long, bool>(5, false);\n// although usually you can rely on the compiler to infer the types\n// for you automatically.  You can assign the result of expression\n// Foo(p1, ..., pk) to a variable of type FooActionPk<p1_type, ...,\n// pk_type>.  This can be useful when composing actions.\n//\n// You can also overload actions with different numbers of parameters:\n//\n//   ACTION_P(Plus, a) { ... }\n//   ACTION_P2(Plus, a, b) { ... }\n//\n// While it's tempting to always use the ACTION* macros when defining\n// a new action, you should also consider implementing ActionInterface\n// or using MakePolymorphicAction() instead, especially if you need to\n// use the action a lot.  While these approaches require more work,\n// they give you more control on the types of the mock function\n// arguments and the action parameters, which in general leads to\n// better compiler error messages that pay off in the long run.  They\n// also allow overloading actions based on parameter types (as opposed\n// to just based on the number of parameters).\n//\n// CAVEAT:\n//\n// ACTION*() can only be used in a namespace scope as templates cannot be\n// declared inside of a local class.\n// Users can, however, define any local functors (e.g. a lambda) that\n// can be used as actions.\n//\n// MORE INFORMATION:\n//\n// To learn more about using these macros, please search for 'ACTION' on\n// https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md\n\n// IWYU pragma: private, include \"gmock/gmock.h\"\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_\n#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_\n\n#ifndef _WIN32_WCE\n#include <errno.h>\n#endif\n\n#include <algorithm>\n#include <functional>\n#include <memory>\n#include <string>\n#include <tuple>\n#include <type_traits>\n#include <utility>\n\n#include \"gmock/internal/gmock-internal-utils.h\"\n#include \"gmock/internal/gmock-port.h\"\n#include \"gmock/internal/gmock-pp.h\"\n\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 4100)\n#endif\n\nnamespace testing {\n\n// To implement an action Foo, define:\n//   1. a class FooAction that implements the ActionInterface interface, and\n//   2. a factory function that creates an Action object from a\n//      const FooAction*.\n//\n// The two-level delegation design follows that of Matcher, providing\n// consistency for extension developers.  It also eases ownership\n// management as Action objects can now be copied like plain values.\n\nnamespace internal {\n\n// BuiltInDefaultValueGetter<T, true>::Get() returns a\n// default-constructed T value.  BuiltInDefaultValueGetter<T,\n// false>::Get() crashes with an error.\n//\n// This primary template is used when kDefaultConstructible is true.\ntemplate <typename T, bool kDefaultConstructible>\nstruct BuiltInDefaultValueGetter {\n  static T Get() { return T(); }\n};\ntemplate <typename T>\nstruct BuiltInDefaultValueGetter<T, false> {\n  static T Get() {\n    Assert(false, __FILE__, __LINE__,\n           \"Default action undefined for the function return type.\");\n    return internal::Invalid<T>();\n    // The above statement will never be reached, but is required in\n    // order for this function to compile.\n  }\n};\n\n// BuiltInDefaultValue<T>::Get() returns the \"built-in\" default value\n// for type T, which is NULL when T is a raw pointer type, 0 when T is\n// a numeric type, false when T is bool, or \"\" when T is string or\n// std::string.  In addition, in C++11 and above, it turns a\n// default-constructed T value if T is default constructible.  For any\n// other type T, the built-in default T value is undefined, and the\n// function will abort the process.\ntemplate <typename T>\nclass BuiltInDefaultValue {\n public:\n  // This function returns true if and only if type T has a built-in default\n  // value.\n  static bool Exists() { return ::std::is_default_constructible<T>::value; }\n\n  static T Get() {\n    return BuiltInDefaultValueGetter<\n        T, ::std::is_default_constructible<T>::value>::Get();\n  }\n};\n\n// This partial specialization says that we use the same built-in\n// default value for T and const T.\ntemplate <typename T>\nclass BuiltInDefaultValue<const T> {\n public:\n  static bool Exists() { return BuiltInDefaultValue<T>::Exists(); }\n  static T Get() { return BuiltInDefaultValue<T>::Get(); }\n};\n\n// This partial specialization defines the default values for pointer\n// types.\ntemplate <typename T>\nclass BuiltInDefaultValue<T*> {\n public:\n  static bool Exists() { return true; }\n  static T* Get() { return nullptr; }\n};\n\n// The following specializations define the default values for\n// specific types we care about.\n#define GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(type, value) \\\n  template <>                                                     \\\n  class BuiltInDefaultValue<type> {                               \\\n   public:                                                        \\\n    static bool Exists() { return true; }                         \\\n    static type Get() { return value; }                           \\\n  }\n\nGMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(void, );  // NOLINT\nGMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(::std::string, \"\");\nGMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(bool, false);\nGMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned char, '\\0');\nGMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed char, '\\0');\nGMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(char, '\\0');\n\n// There's no need for a default action for signed wchar_t, as that\n// type is the same as wchar_t for gcc, and invalid for MSVC.\n//\n// There's also no need for a default action for unsigned wchar_t, as\n// that type is the same as unsigned int for gcc, and invalid for\n// MSVC.\n#if GMOCK_WCHAR_T_IS_NATIVE_\nGMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(wchar_t, 0U);  // NOLINT\n#endif\n\nGMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned short, 0U);  // NOLINT\nGMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed short, 0);     // NOLINT\nGMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned int, 0U);\nGMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed int, 0);\nGMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long, 0UL);     // NOLINT\nGMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long, 0L);        // NOLINT\nGMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(unsigned long long, 0);  // NOLINT\nGMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(signed long long, 0);    // NOLINT\nGMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(float, 0);\nGMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_(double, 0);\n\n#undef GMOCK_DEFINE_DEFAULT_ACTION_FOR_RETURN_TYPE_\n\n// Partial implementations of metaprogramming types from the standard library\n// not available in C++11.\n\ntemplate <typename P>\nstruct negation\n    // NOLINTNEXTLINE\n    : std::integral_constant<bool, bool(!P::value)> {};\n\n// Base case: with zero predicates the answer is always true.\ntemplate <typename...>\nstruct conjunction : std::true_type {};\n\n// With a single predicate, the answer is that predicate.\ntemplate <typename P1>\nstruct conjunction<P1> : P1 {};\n\n// With multiple predicates the answer is the first predicate if that is false,\n// and we recurse otherwise.\ntemplate <typename P1, typename... Ps>\nstruct conjunction<P1, Ps...>\n    : std::conditional<bool(P1::value), conjunction<Ps...>, P1>::type {};\n\ntemplate <typename...>\nstruct disjunction : std::false_type {};\n\ntemplate <typename P1>\nstruct disjunction<P1> : P1 {};\n\ntemplate <typename P1, typename... Ps>\nstruct disjunction<P1, Ps...>\n    // NOLINTNEXTLINE\n    : std::conditional<!bool(P1::value), disjunction<Ps...>, P1>::type {};\n\ntemplate <typename...>\nusing void_t = void;\n\n// Detects whether an expression of type `From` can be implicitly converted to\n// `To` according to [conv]. In C++17, [conv]/3 defines this as follows:\n//\n//     An expression e can be implicitly converted to a type T if and only if\n//     the declaration T t=e; is well-formed, for some invented temporary\n//     variable t ([dcl.init]).\n//\n// [conv]/2 implies we can use function argument passing to detect whether this\n// initialization is valid.\n//\n// Note that this is distinct from is_convertible, which requires this be valid:\n//\n//     To test() {\n//       return declval<From>();\n//     }\n//\n// In particular, is_convertible doesn't give the correct answer when `To` and\n// `From` are the same non-moveable type since `declval<From>` will be an rvalue\n// reference, defeating the guaranteed copy elision that would otherwise make\n// this function work.\n//\n// REQUIRES: `From` is not cv void.\ntemplate <typename From, typename To>\nstruct is_implicitly_convertible {\n private:\n  // A function that accepts a parameter of type T. This can be called with type\n  // U successfully only if U is implicitly convertible to T.\n  template <typename T>\n  static void Accept(T);\n\n  // A function that creates a value of type T.\n  template <typename T>\n  static T Make();\n\n  // An overload be selected when implicit conversion from T to To is possible.\n  template <typename T, typename = decltype(Accept<To>(Make<T>()))>\n  static std::true_type TestImplicitConversion(int);\n\n  // A fallback overload selected in all other cases.\n  template <typename T>\n  static std::false_type TestImplicitConversion(...);\n\n public:\n  using type = decltype(TestImplicitConversion<From>(0));\n  static constexpr bool value = type::value;\n};\n\n// Like std::invoke_result_t from C++17, but works only for objects with call\n// operators (not e.g. member function pointers, which we don't need specific\n// support for in OnceAction because std::function deals with them).\ntemplate <typename F, typename... Args>\nusing call_result_t = decltype(std::declval<F>()(std::declval<Args>()...));\n\ntemplate <typename Void, typename R, typename F, typename... Args>\nstruct is_callable_r_impl : std::false_type {};\n\n// Specialize the struct for those template arguments where call_result_t is\n// well-formed. When it's not, the generic template above is chosen, resulting\n// in std::false_type.\ntemplate <typename R, typename F, typename... Args>\nstruct is_callable_r_impl<void_t<call_result_t<F, Args...>>, R, F, Args...>\n    : std::conditional<\n          std::is_void<R>::value,  //\n          std::true_type,          //\n          is_implicitly_convertible<call_result_t<F, Args...>, R>>::type {};\n\n// Like std::is_invocable_r from C++17, but works only for objects with call\n// operators. See the note on call_result_t.\ntemplate <typename R, typename F, typename... Args>\nusing is_callable_r = is_callable_r_impl<void, R, F, Args...>;\n\n// Like std::as_const from C++17.\ntemplate <typename T>\ntypename std::add_const<T>::type& as_const(T& t) {\n  return t;\n}\n\n}  // namespace internal\n\n// Specialized for function types below.\ntemplate <typename F>\nclass OnceAction;\n\n// An action that can only be used once.\n//\n// This is accepted by WillOnce, which doesn't require the underlying action to\n// be copy-constructible (only move-constructible), and promises to invoke it as\n// an rvalue reference. This allows the action to work with move-only types like\n// std::move_only_function in a type-safe manner.\n//\n// For example:\n//\n//     // Assume we have some API that needs to accept a unique pointer to some\n//     // non-copyable object Foo.\n//     void AcceptUniquePointer(std::unique_ptr<Foo> foo);\n//\n//     // We can define an action that provides a Foo to that API. Because It\n//     // has to give away its unique pointer, it must not be called more than\n//     // once, so its call operator is &&-qualified.\n//     struct ProvideFoo {\n//       std::unique_ptr<Foo> foo;\n//\n//       void operator()() && {\n//         AcceptUniquePointer(std::move(Foo));\n//       }\n//     };\n//\n//     // This action can be used with WillOnce.\n//     EXPECT_CALL(mock, Call)\n//         .WillOnce(ProvideFoo{std::make_unique<Foo>(...)});\n//\n//     // But a call to WillRepeatedly will fail to compile. This is correct,\n//     // since the action cannot correctly be used repeatedly.\n//     EXPECT_CALL(mock, Call)\n//         .WillRepeatedly(ProvideFoo{std::make_unique<Foo>(...)});\n//\n// A less-contrived example would be an action that returns an arbitrary type,\n// whose &&-qualified call operator is capable of dealing with move-only types.\ntemplate <typename Result, typename... Args>\nclass OnceAction<Result(Args...)> final {\n private:\n  // True iff we can use the given callable type (or lvalue reference) directly\n  // via StdFunctionAdaptor.\n  template <typename Callable>\n  using IsDirectlyCompatible = internal::conjunction<\n      // It must be possible to capture the callable in StdFunctionAdaptor.\n      std::is_constructible<typename std::decay<Callable>::type, Callable>,\n      // The callable must be compatible with our signature.\n      internal::is_callable_r<Result, typename std::decay<Callable>::type,\n                              Args...>>;\n\n  // True iff we can use the given callable type via StdFunctionAdaptor once we\n  // ignore incoming arguments.\n  template <typename Callable>\n  using IsCompatibleAfterIgnoringArguments = internal::conjunction<\n      // It must be possible to capture the callable in a lambda.\n      std::is_constructible<typename std::decay<Callable>::type, Callable>,\n      // The callable must be invocable with zero arguments, returning something\n      // convertible to Result.\n      internal::is_callable_r<Result, typename std::decay<Callable>::type>>;\n\n public:\n  // Construct from a callable that is directly compatible with our mocked\n  // signature: it accepts our function type's arguments and returns something\n  // convertible to our result type.\n  template <typename Callable,\n            typename std::enable_if<\n                internal::conjunction<\n                    // Teach clang on macOS that we're not talking about a\n                    // copy/move constructor here. Otherwise it gets confused\n                    // when checking the is_constructible requirement of our\n                    // traits above.\n                    internal::negation<std::is_same<\n                        OnceAction, typename std::decay<Callable>::type>>,\n                    IsDirectlyCompatible<Callable>>  //\n                ::value,\n                int>::type = 0>\n  OnceAction(Callable&& callable)  // NOLINT\n      : function_(StdFunctionAdaptor<typename std::decay<Callable>::type>(\n            {}, std::forward<Callable>(callable))) {}\n\n  // As above, but for a callable that ignores the mocked function's arguments.\n  template <typename Callable,\n            typename std::enable_if<\n                internal::conjunction<\n                    // Teach clang on macOS that we're not talking about a\n                    // copy/move constructor here. Otherwise it gets confused\n                    // when checking the is_constructible requirement of our\n                    // traits above.\n                    internal::negation<std::is_same<\n                        OnceAction, typename std::decay<Callable>::type>>,\n                    // Exclude callables for which the overload above works.\n                    // We'd rather provide the arguments if possible.\n                    internal::negation<IsDirectlyCompatible<Callable>>,\n                    IsCompatibleAfterIgnoringArguments<Callable>>::value,\n                int>::type = 0>\n  OnceAction(Callable&& callable)  // NOLINT\n                                   // Call the constructor above with a callable\n                                   // that ignores the input arguments.\n      : OnceAction(IgnoreIncomingArguments<typename std::decay<Callable>::type>{\n            std::forward<Callable>(callable)}) {}\n\n  // We are naturally copyable because we store only an std::function, but\n  // semantically we should not be copyable.\n  OnceAction(const OnceAction&) = delete;\n  OnceAction& operator=(const OnceAction&) = delete;\n  OnceAction(OnceAction&&) = default;\n\n  // Invoke the underlying action callable with which we were constructed,\n  // handing it the supplied arguments.\n  Result Call(Args... args) && {\n    return function_(std::forward<Args>(args)...);\n  }\n\n private:\n  // An adaptor that wraps a callable that is compatible with our signature and\n  // being invoked as an rvalue reference so that it can be used as an\n  // StdFunctionAdaptor. This throws away type safety, but that's fine because\n  // this is only used by WillOnce, which we know calls at most once.\n  //\n  // Once we have something like std::move_only_function from C++23, we can do\n  // away with this.\n  template <typename Callable>\n  class StdFunctionAdaptor final {\n   public:\n    // A tag indicating that the (otherwise universal) constructor is accepting\n    // the callable itself, instead of e.g. stealing calls for the move\n    // constructor.\n    struct CallableTag final {};\n\n    template <typename F>\n    explicit StdFunctionAdaptor(CallableTag, F&& callable)\n        : callable_(std::make_shared<Callable>(std::forward<F>(callable))) {}\n\n    // Rather than explicitly returning Result, we return whatever the wrapped\n    // callable returns. This allows for compatibility with existing uses like\n    // the following, when the mocked function returns void:\n    //\n    //     EXPECT_CALL(mock_fn_, Call)\n    //         .WillOnce([&] {\n    //            [...]\n    //            return 0;\n    //         });\n    //\n    // Such a callable can be turned into std::function<void()>. If we use an\n    // explicit return type of Result here then it *doesn't* work with\n    // std::function, because we'll get a \"void function should not return a\n    // value\" error.\n    //\n    // We need not worry about incompatible result types because the SFINAE on\n    // OnceAction already checks this for us. std::is_invocable_r_v itself makes\n    // the same allowance for void result types.\n    template <typename... ArgRefs>\n    internal::call_result_t<Callable, ArgRefs...> operator()(\n        ArgRefs&&... args) const {\n      return std::move(*callable_)(std::forward<ArgRefs>(args)...);\n    }\n\n   private:\n    // We must put the callable on the heap so that we are copyable, which\n    // std::function needs.\n    std::shared_ptr<Callable> callable_;\n  };\n\n  // An adaptor that makes a callable that accepts zero arguments callable with\n  // our mocked arguments.\n  template <typename Callable>\n  struct IgnoreIncomingArguments {\n    internal::call_result_t<Callable> operator()(Args&&...) {\n      return std::move(callable)();\n    }\n\n    Callable callable;\n  };\n\n  std::function<Result(Args...)> function_;\n};\n\n// When an unexpected function call is encountered, Google Mock will\n// let it return a default value if the user has specified one for its\n// return type, or if the return type has a built-in default value;\n// otherwise Google Mock won't know what value to return and will have\n// to abort the process.\n//\n// The DefaultValue<T> class allows a user to specify the\n// default value for a type T that is both copyable and publicly\n// destructible (i.e. anything that can be used as a function return\n// type).  The usage is:\n//\n//   // Sets the default value for type T to be foo.\n//   DefaultValue<T>::Set(foo);\ntemplate <typename T>\nclass DefaultValue {\n public:\n  // Sets the default value for type T; requires T to be\n  // copy-constructable and have a public destructor.\n  static void Set(T x) {\n    delete producer_;\n    producer_ = new FixedValueProducer(x);\n  }\n\n  // Provides a factory function to be called to generate the default value.\n  // This method can be used even if T is only move-constructible, but it is not\n  // limited to that case.\n  typedef T (*FactoryFunction)();\n  static void SetFactory(FactoryFunction factory) {\n    delete producer_;\n    producer_ = new FactoryValueProducer(factory);\n  }\n\n  // Unsets the default value for type T.\n  static void Clear() {\n    delete producer_;\n    producer_ = nullptr;\n  }\n\n  // Returns true if and only if the user has set the default value for type T.\n  static bool IsSet() { return producer_ != nullptr; }\n\n  // Returns true if T has a default return value set by the user or there\n  // exists a built-in default value.\n  static bool Exists() {\n    return IsSet() || internal::BuiltInDefaultValue<T>::Exists();\n  }\n\n  // Returns the default value for type T if the user has set one;\n  // otherwise returns the built-in default value. Requires that Exists()\n  // is true, which ensures that the return value is well-defined.\n  static T Get() {\n    return producer_ == nullptr ? internal::BuiltInDefaultValue<T>::Get()\n                                : producer_->Produce();\n  }\n\n private:\n  class ValueProducer {\n   public:\n    virtual ~ValueProducer() {}\n    virtual T Produce() = 0;\n  };\n\n  class FixedValueProducer : public ValueProducer {\n   public:\n    explicit FixedValueProducer(T value) : value_(value) {}\n    T Produce() override { return value_; }\n\n   private:\n    const T value_;\n    FixedValueProducer(const FixedValueProducer&) = delete;\n    FixedValueProducer& operator=(const FixedValueProducer&) = delete;\n  };\n\n  class FactoryValueProducer : public ValueProducer {\n   public:\n    explicit FactoryValueProducer(FactoryFunction factory)\n        : factory_(factory) {}\n    T Produce() override { return factory_(); }\n\n   private:\n    const FactoryFunction factory_;\n    FactoryValueProducer(const FactoryValueProducer&) = delete;\n    FactoryValueProducer& operator=(const FactoryValueProducer&) = delete;\n  };\n\n  static ValueProducer* producer_;\n};\n\n// This partial specialization allows a user to set default values for\n// reference types.\ntemplate <typename T>\nclass DefaultValue<T&> {\n public:\n  // Sets the default value for type T&.\n  static void Set(T& x) {  // NOLINT\n    address_ = &x;\n  }\n\n  // Unsets the default value for type T&.\n  static void Clear() { address_ = nullptr; }\n\n  // Returns true if and only if the user has set the default value for type T&.\n  static bool IsSet() { return address_ != nullptr; }\n\n  // Returns true if T has a default return value set by the user or there\n  // exists a built-in default value.\n  static bool Exists() {\n    return IsSet() || internal::BuiltInDefaultValue<T&>::Exists();\n  }\n\n  // Returns the default value for type T& if the user has set one;\n  // otherwise returns the built-in default value if there is one;\n  // otherwise aborts the process.\n  static T& Get() {\n    return address_ == nullptr ? internal::BuiltInDefaultValue<T&>::Get()\n                               : *address_;\n  }\n\n private:\n  static T* address_;\n};\n\n// This specialization allows DefaultValue<void>::Get() to\n// compile.\ntemplate <>\nclass DefaultValue<void> {\n public:\n  static bool Exists() { return true; }\n  static void Get() {}\n};\n\n// Points to the user-set default value for type T.\ntemplate <typename T>\ntypename DefaultValue<T>::ValueProducer* DefaultValue<T>::producer_ = nullptr;\n\n// Points to the user-set default value for type T&.\ntemplate <typename T>\nT* DefaultValue<T&>::address_ = nullptr;\n\n// Implement this interface to define an action for function type F.\ntemplate <typename F>\nclass ActionInterface {\n public:\n  typedef typename internal::Function<F>::Result Result;\n  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;\n\n  ActionInterface() {}\n  virtual ~ActionInterface() {}\n\n  // Performs the action.  This method is not const, as in general an\n  // action can have side effects and be stateful.  For example, a\n  // get-the-next-element-from-the-collection action will need to\n  // remember the current element.\n  virtual Result Perform(const ArgumentTuple& args) = 0;\n\n private:\n  ActionInterface(const ActionInterface&) = delete;\n  ActionInterface& operator=(const ActionInterface&) = delete;\n};\n\ntemplate <typename F>\nclass Action;\n\n// An Action<R(Args...)> is a copyable and IMMUTABLE (except by assignment)\n// object that represents an action to be taken when a mock function of type\n// R(Args...) is called. The implementation of Action<T> is just a\n// std::shared_ptr to const ActionInterface<T>. Don't inherit from Action! You\n// can view an object implementing ActionInterface<F> as a concrete action\n// (including its current state), and an Action<F> object as a handle to it.\ntemplate <typename R, typename... Args>\nclass Action<R(Args...)> {\n private:\n  using F = R(Args...);\n\n  // Adapter class to allow constructing Action from a legacy ActionInterface.\n  // New code should create Actions from functors instead.\n  struct ActionAdapter {\n    // Adapter must be copyable to satisfy std::function requirements.\n    ::std::shared_ptr<ActionInterface<F>> impl_;\n\n    template <typename... InArgs>\n    typename internal::Function<F>::Result operator()(InArgs&&... args) {\n      return impl_->Perform(\n          ::std::forward_as_tuple(::std::forward<InArgs>(args)...));\n    }\n  };\n\n  template <typename G>\n  using IsCompatibleFunctor = std::is_constructible<std::function<F>, G>;\n\n public:\n  typedef typename internal::Function<F>::Result Result;\n  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;\n\n  // Constructs a null Action.  Needed for storing Action objects in\n  // STL containers.\n  Action() {}\n\n  // Construct an Action from a specified callable.\n  // This cannot take std::function directly, because then Action would not be\n  // directly constructible from lambda (it would require two conversions).\n  template <\n      typename G,\n      typename = typename std::enable_if<internal::disjunction<\n          IsCompatibleFunctor<G>, std::is_constructible<std::function<Result()>,\n                                                        G>>::value>::type>\n  Action(G&& fun) {  // NOLINT\n    Init(::std::forward<G>(fun), IsCompatibleFunctor<G>());\n  }\n\n  // Constructs an Action from its implementation.\n  explicit Action(ActionInterface<F>* impl)\n      : fun_(ActionAdapter{::std::shared_ptr<ActionInterface<F>>(impl)}) {}\n\n  // This constructor allows us to turn an Action<Func> object into an\n  // Action<F>, as long as F's arguments can be implicitly converted\n  // to Func's and Func's return type can be implicitly converted to F's.\n  template <typename Func>\n  Action(const Action<Func>& action)  // NOLINT\n      : fun_(action.fun_) {}\n\n  // Returns true if and only if this is the DoDefault() action.\n  bool IsDoDefault() const { return fun_ == nullptr; }\n\n  // Performs the action.  Note that this method is const even though\n  // the corresponding method in ActionInterface is not.  The reason\n  // is that a const Action<F> means that it cannot be re-bound to\n  // another concrete action, not that the concrete action it binds to\n  // cannot change state.  (Think of the difference between a const\n  // pointer and a pointer to const.)\n  Result Perform(ArgumentTuple args) const {\n    if (IsDoDefault()) {\n      internal::IllegalDoDefault(__FILE__, __LINE__);\n    }\n    return internal::Apply(fun_, ::std::move(args));\n  }\n\n  // An action can be used as a OnceAction, since it's obviously safe to call it\n  // once.\n  operator OnceAction<F>() const {  // NOLINT\n    // Return a OnceAction-compatible callable that calls Perform with the\n    // arguments it is provided. We could instead just return fun_, but then\n    // we'd need to handle the IsDoDefault() case separately.\n    struct OA {\n      Action<F> action;\n\n      R operator()(Args... args) && {\n        return action.Perform(\n            std::forward_as_tuple(std::forward<Args>(args)...));\n      }\n    };\n\n    return OA{*this};\n  }\n\n private:\n  template <typename G>\n  friend class Action;\n\n  template <typename G>\n  void Init(G&& g, ::std::true_type) {\n    fun_ = ::std::forward<G>(g);\n  }\n\n  template <typename G>\n  void Init(G&& g, ::std::false_type) {\n    fun_ = IgnoreArgs<typename ::std::decay<G>::type>{::std::forward<G>(g)};\n  }\n\n  template <typename FunctionImpl>\n  struct IgnoreArgs {\n    template <typename... InArgs>\n    Result operator()(const InArgs&...) const {\n      return function_impl();\n    }\n\n    FunctionImpl function_impl;\n  };\n\n  // fun_ is an empty function if and only if this is the DoDefault() action.\n  ::std::function<F> fun_;\n};\n\n// The PolymorphicAction class template makes it easy to implement a\n// polymorphic action (i.e. an action that can be used in mock\n// functions of than one type, e.g. Return()).\n//\n// To define a polymorphic action, a user first provides a COPYABLE\n// implementation class that has a Perform() method template:\n//\n//   class FooAction {\n//    public:\n//     template <typename Result, typename ArgumentTuple>\n//     Result Perform(const ArgumentTuple& args) const {\n//       // Processes the arguments and returns a result, using\n//       // std::get<N>(args) to get the N-th (0-based) argument in the tuple.\n//     }\n//     ...\n//   };\n//\n// Then the user creates the polymorphic action using\n// MakePolymorphicAction(object) where object has type FooAction.  See\n// the definition of Return(void) and SetArgumentPointee<N>(value) for\n// complete examples.\ntemplate <typename Impl>\nclass PolymorphicAction {\n public:\n  explicit PolymorphicAction(const Impl& impl) : impl_(impl) {}\n\n  template <typename F>\n  operator Action<F>() const {\n    return Action<F>(new MonomorphicImpl<F>(impl_));\n  }\n\n private:\n  template <typename F>\n  class MonomorphicImpl : public ActionInterface<F> {\n   public:\n    typedef typename internal::Function<F>::Result Result;\n    typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;\n\n    explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}\n\n    Result Perform(const ArgumentTuple& args) override {\n      return impl_.template Perform<Result>(args);\n    }\n\n   private:\n    Impl impl_;\n  };\n\n  Impl impl_;\n};\n\n// Creates an Action from its implementation and returns it.  The\n// created Action object owns the implementation.\ntemplate <typename F>\nAction<F> MakeAction(ActionInterface<F>* impl) {\n  return Action<F>(impl);\n}\n\n// Creates a polymorphic action from its implementation.  This is\n// easier to use than the PolymorphicAction<Impl> constructor as it\n// doesn't require you to explicitly write the template argument, e.g.\n//\n//   MakePolymorphicAction(foo);\n// vs\n//   PolymorphicAction<TypeOfFoo>(foo);\ntemplate <typename Impl>\ninline PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl) {\n  return PolymorphicAction<Impl>(impl);\n}\n\nnamespace internal {\n\n// Helper struct to specialize ReturnAction to execute a move instead of a copy\n// on return. Useful for move-only types, but could be used on any type.\ntemplate <typename T>\nstruct ByMoveWrapper {\n  explicit ByMoveWrapper(T value) : payload(std::move(value)) {}\n  T payload;\n};\n\n// The general implementation of Return(R). Specializations follow below.\ntemplate <typename R>\nclass ReturnAction final {\n public:\n  explicit ReturnAction(R value) : value_(std::move(value)) {}\n\n  template <typename U, typename... Args,\n            typename = typename std::enable_if<conjunction<\n                // See the requirements documented on Return.\n                negation<std::is_same<void, U>>,  //\n                negation<std::is_reference<U>>,   //\n                std::is_convertible<R, U>,        //\n                std::is_move_constructible<U>>::value>::type>\n  operator OnceAction<U(Args...)>() && {  // NOLINT\n    return Impl<U>(std::move(value_));\n  }\n\n  template <typename U, typename... Args,\n            typename = typename std::enable_if<conjunction<\n                // See the requirements documented on Return.\n                negation<std::is_same<void, U>>,   //\n                negation<std::is_reference<U>>,    //\n                std::is_convertible<const R&, U>,  //\n                std::is_copy_constructible<U>>::value>::type>\n  operator Action<U(Args...)>() const {  // NOLINT\n    return Impl<U>(value_);\n  }\n\n private:\n  // Implements the Return(x) action for a mock function that returns type U.\n  template <typename U>\n  class Impl final {\n   public:\n    // The constructor used when the return value is allowed to move from the\n    // input value (i.e. we are converting to OnceAction).\n    explicit Impl(R&& input_value)\n        : state_(new State(std::move(input_value))) {}\n\n    // The constructor used when the return value is not allowed to move from\n    // the input value (i.e. we are converting to Action).\n    explicit Impl(const R& input_value) : state_(new State(input_value)) {}\n\n    U operator()() && { return std::move(state_->value); }\n    U operator()() const& { return state_->value; }\n\n   private:\n    // We put our state on the heap so that the compiler-generated copy/move\n    // constructors work correctly even when U is a reference-like type. This is\n    // necessary only because we eagerly create State::value (see the note on\n    // that symbol for details). If we instead had only the input value as a\n    // member then the default constructors would work fine.\n    //\n    // For example, when R is std::string and U is std::string_view, value is a\n    // reference to the string backed by input_value. The copy constructor would\n    // copy both, so that we wind up with a new input_value object (with the\n    // same contents) and a reference to the *old* input_value object rather\n    // than the new one.\n    struct State {\n      explicit State(const R& input_value_in)\n          : input_value(input_value_in),\n            // Make an implicit conversion to Result before initializing the U\n            // object we store, avoiding calling any explicit constructor of U\n            // from R.\n            //\n            // This simulates the language rules: a function with return type U\n            // that does `return R()` requires R to be implicitly convertible to\n            // U, and uses that path for the conversion, even U Result has an\n            // explicit constructor from R.\n            value(ImplicitCast_<U>(internal::as_const(input_value))) {}\n\n      // As above, but for the case where we're moving from the ReturnAction\n      // object because it's being used as a OnceAction.\n      explicit State(R&& input_value_in)\n          : input_value(std::move(input_value_in)),\n            // For the same reason as above we make an implicit conversion to U\n            // before initializing the value.\n            //\n            // Unlike above we provide the input value as an rvalue to the\n            // implicit conversion because this is a OnceAction: it's fine if it\n            // wants to consume the input value.\n            value(ImplicitCast_<U>(std::move(input_value))) {}\n\n      // A copy of the value originally provided by the user. We retain this in\n      // addition to the value of the mock function's result type below in case\n      // the latter is a reference-like type. See the std::string_view example\n      // in the documentation on Return.\n      R input_value;\n\n      // The value we actually return, as the type returned by the mock function\n      // itself.\n      //\n      // We eagerly initialize this here, rather than lazily doing the implicit\n      // conversion automatically each time Perform is called, for historical\n      // reasons: in 2009-11, commit a070cbd91c (Google changelist 13540126)\n      // made the Action<U()> conversion operator eagerly convert the R value to\n      // U, but without keeping the R alive. This broke the use case discussed\n      // in the documentation for Return, making reference-like types such as\n      // std::string_view not safe to use as U where the input type R is a\n      // value-like type such as std::string.\n      //\n      // The example the commit gave was not very clear, nor was the issue\n      // thread (https://github.com/google/googlemock/issues/86), but it seems\n      // the worry was about reference-like input types R that flatten to a\n      // value-like type U when being implicitly converted. An example of this\n      // is std::vector<bool>::reference, which is often a proxy type with an\n      // reference to the underlying vector:\n      //\n      //     // Helper method: have the mock function return bools according\n      //     // to the supplied script.\n      //     void SetActions(MockFunction<bool(size_t)>& mock,\n      //                     const std::vector<bool>& script) {\n      //       for (size_t i = 0; i < script.size(); ++i) {\n      //         EXPECT_CALL(mock, Call(i)).WillOnce(Return(script[i]));\n      //       }\n      //     }\n      //\n      //     TEST(Foo, Bar) {\n      //       // Set actions using a temporary vector, whose operator[]\n      //       // returns proxy objects that references that will be\n      //       // dangling once the call to SetActions finishes and the\n      //       // vector is destroyed.\n      //       MockFunction<bool(size_t)> mock;\n      //       SetActions(mock, {false, true});\n      //\n      //       EXPECT_FALSE(mock.AsStdFunction()(0));\n      //       EXPECT_TRUE(mock.AsStdFunction()(1));\n      //     }\n      //\n      // This eager conversion helps with a simple case like this, but doesn't\n      // fully make these types work in general. For example the following still\n      // uses a dangling reference:\n      //\n      //     TEST(Foo, Baz) {\n      //       MockFunction<std::vector<std::string>()> mock;\n      //\n      //       // Return the same vector twice, and then the empty vector\n      //       // thereafter.\n      //       auto action = Return(std::initializer_list<std::string>{\n      //           \"taco\", \"burrito\",\n      //       });\n      //\n      //       EXPECT_CALL(mock, Call)\n      //           .WillOnce(action)\n      //           .WillOnce(action)\n      //           .WillRepeatedly(Return(std::vector<std::string>{}));\n      //\n      //       EXPECT_THAT(mock.AsStdFunction()(),\n      //                   ElementsAre(\"taco\", \"burrito\"));\n      //       EXPECT_THAT(mock.AsStdFunction()(),\n      //                   ElementsAre(\"taco\", \"burrito\"));\n      //       EXPECT_THAT(mock.AsStdFunction()(), IsEmpty());\n      //     }\n      //\n      U value;\n    };\n\n    const std::shared_ptr<State> state_;\n  };\n\n  R value_;\n};\n\n// A specialization of ReturnAction<R> when R is ByMoveWrapper<T> for some T.\n//\n// This version applies the type system-defeating hack of moving from T even in\n// the const call operator, checking at runtime that it isn't called more than\n// once, since the user has declared their intent to do so by using ByMove.\ntemplate <typename T>\nclass ReturnAction<ByMoveWrapper<T>> final {\n public:\n  explicit ReturnAction(ByMoveWrapper<T> wrapper)\n      : state_(new State(std::move(wrapper.payload))) {}\n\n  T operator()() const {\n    GTEST_CHECK_(!state_->called)\n        << \"A ByMove() action must be performed at most once.\";\n\n    state_->called = true;\n    return std::move(state_->value);\n  }\n\n private:\n  // We store our state on the heap so that we are copyable as required by\n  // Action, despite the fact that we are stateful and T may not be copyable.\n  struct State {\n    explicit State(T&& value_in) : value(std::move(value_in)) {}\n\n    T value;\n    bool called = false;\n  };\n\n  const std::shared_ptr<State> state_;\n};\n\n// Implements the ReturnNull() action.\nclass ReturnNullAction {\n public:\n  // Allows ReturnNull() to be used in any pointer-returning function. In C++11\n  // this is enforced by returning nullptr, and in non-C++11 by asserting a\n  // pointer type on compile time.\n  template <typename Result, typename ArgumentTuple>\n  static Result Perform(const ArgumentTuple&) {\n    return nullptr;\n  }\n};\n\n// Implements the Return() action.\nclass ReturnVoidAction {\n public:\n  // Allows Return() to be used in any void-returning function.\n  template <typename Result, typename ArgumentTuple>\n  static void Perform(const ArgumentTuple&) {\n    static_assert(std::is_void<Result>::value, \"Result should be void.\");\n  }\n};\n\n// Implements the polymorphic ReturnRef(x) action, which can be used\n// in any function that returns a reference to the type of x,\n// regardless of the argument types.\ntemplate <typename T>\nclass ReturnRefAction {\n public:\n  // Constructs a ReturnRefAction object from the reference to be returned.\n  explicit ReturnRefAction(T& ref) : ref_(ref) {}  // NOLINT\n\n  // This template type conversion operator allows ReturnRef(x) to be\n  // used in ANY function that returns a reference to x's type.\n  template <typename F>\n  operator Action<F>() const {\n    typedef typename Function<F>::Result Result;\n    // Asserts that the function return type is a reference.  This\n    // catches the user error of using ReturnRef(x) when Return(x)\n    // should be used, and generates some helpful error message.\n    static_assert(std::is_reference<Result>::value,\n                  \"use Return instead of ReturnRef to return a value\");\n    return Action<F>(new Impl<F>(ref_));\n  }\n\n private:\n  // Implements the ReturnRef(x) action for a particular function type F.\n  template <typename F>\n  class Impl : public ActionInterface<F> {\n   public:\n    typedef typename Function<F>::Result Result;\n    typedef typename Function<F>::ArgumentTuple ArgumentTuple;\n\n    explicit Impl(T& ref) : ref_(ref) {}  // NOLINT\n\n    Result Perform(const ArgumentTuple&) override { return ref_; }\n\n   private:\n    T& ref_;\n  };\n\n  T& ref_;\n};\n\n// Implements the polymorphic ReturnRefOfCopy(x) action, which can be\n// used in any function that returns a reference to the type of x,\n// regardless of the argument types.\ntemplate <typename T>\nclass ReturnRefOfCopyAction {\n public:\n  // Constructs a ReturnRefOfCopyAction object from the reference to\n  // be returned.\n  explicit ReturnRefOfCopyAction(const T& value) : value_(value) {}  // NOLINT\n\n  // This template type conversion operator allows ReturnRefOfCopy(x) to be\n  // used in ANY function that returns a reference to x's type.\n  template <typename F>\n  operator Action<F>() const {\n    typedef typename Function<F>::Result Result;\n    // Asserts that the function return type is a reference.  This\n    // catches the user error of using ReturnRefOfCopy(x) when Return(x)\n    // should be used, and generates some helpful error message.\n    static_assert(std::is_reference<Result>::value,\n                  \"use Return instead of ReturnRefOfCopy to return a value\");\n    return Action<F>(new Impl<F>(value_));\n  }\n\n private:\n  // Implements the ReturnRefOfCopy(x) action for a particular function type F.\n  template <typename F>\n  class Impl : public ActionInterface<F> {\n   public:\n    typedef typename Function<F>::Result Result;\n    typedef typename Function<F>::ArgumentTuple ArgumentTuple;\n\n    explicit Impl(const T& value) : value_(value) {}  // NOLINT\n\n    Result Perform(const ArgumentTuple&) override { return value_; }\n\n   private:\n    T value_;\n  };\n\n  const T value_;\n};\n\n// Implements the polymorphic ReturnRoundRobin(v) action, which can be\n// used in any function that returns the element_type of v.\ntemplate <typename T>\nclass ReturnRoundRobinAction {\n public:\n  explicit ReturnRoundRobinAction(std::vector<T> values) {\n    GTEST_CHECK_(!values.empty())\n        << \"ReturnRoundRobin requires at least one element.\";\n    state_->values = std::move(values);\n  }\n\n  template <typename... Args>\n  T operator()(Args&&...) const {\n    return state_->Next();\n  }\n\n private:\n  struct State {\n    T Next() {\n      T ret_val = values[i++];\n      if (i == values.size()) i = 0;\n      return ret_val;\n    }\n\n    std::vector<T> values;\n    size_t i = 0;\n  };\n  std::shared_ptr<State> state_ = std::make_shared<State>();\n};\n\n// Implements the polymorphic DoDefault() action.\nclass DoDefaultAction {\n public:\n  // This template type conversion operator allows DoDefault() to be\n  // used in any function.\n  template <typename F>\n  operator Action<F>() const {\n    return Action<F>();\n  }  // NOLINT\n};\n\n// Implements the Assign action to set a given pointer referent to a\n// particular value.\ntemplate <typename T1, typename T2>\nclass AssignAction {\n public:\n  AssignAction(T1* ptr, T2 value) : ptr_(ptr), value_(value) {}\n\n  template <typename Result, typename ArgumentTuple>\n  void Perform(const ArgumentTuple& /* args */) const {\n    *ptr_ = value_;\n  }\n\n private:\n  T1* const ptr_;\n  const T2 value_;\n};\n\n#if !GTEST_OS_WINDOWS_MOBILE\n\n// Implements the SetErrnoAndReturn action to simulate return from\n// various system calls and libc functions.\ntemplate <typename T>\nclass SetErrnoAndReturnAction {\n public:\n  SetErrnoAndReturnAction(int errno_value, T result)\n      : errno_(errno_value), result_(result) {}\n  template <typename Result, typename ArgumentTuple>\n  Result Perform(const ArgumentTuple& /* args */) const {\n    errno = errno_;\n    return result_;\n  }\n\n private:\n  const int errno_;\n  const T result_;\n};\n\n#endif  // !GTEST_OS_WINDOWS_MOBILE\n\n// Implements the SetArgumentPointee<N>(x) action for any function\n// whose N-th argument (0-based) is a pointer to x's type.\ntemplate <size_t N, typename A, typename = void>\nstruct SetArgumentPointeeAction {\n  A value;\n\n  template <typename... Args>\n  void operator()(const Args&... args) const {\n    *::std::get<N>(std::tie(args...)) = value;\n  }\n};\n\n// Implements the Invoke(object_ptr, &Class::Method) action.\ntemplate <class Class, typename MethodPtr>\nstruct InvokeMethodAction {\n  Class* const obj_ptr;\n  const MethodPtr method_ptr;\n\n  template <typename... Args>\n  auto operator()(Args&&... args) const\n      -> decltype((obj_ptr->*method_ptr)(std::forward<Args>(args)...)) {\n    return (obj_ptr->*method_ptr)(std::forward<Args>(args)...);\n  }\n};\n\n// Implements the InvokeWithoutArgs(f) action.  The template argument\n// FunctionImpl is the implementation type of f, which can be either a\n// function pointer or a functor.  InvokeWithoutArgs(f) can be used as an\n// Action<F> as long as f's type is compatible with F.\ntemplate <typename FunctionImpl>\nstruct InvokeWithoutArgsAction {\n  FunctionImpl function_impl;\n\n  // Allows InvokeWithoutArgs(f) to be used as any action whose type is\n  // compatible with f.\n  template <typename... Args>\n  auto operator()(const Args&...) -> decltype(function_impl()) {\n    return function_impl();\n  }\n};\n\n// Implements the InvokeWithoutArgs(object_ptr, &Class::Method) action.\ntemplate <class Class, typename MethodPtr>\nstruct InvokeMethodWithoutArgsAction {\n  Class* const obj_ptr;\n  const MethodPtr method_ptr;\n\n  using ReturnType =\n      decltype((std::declval<Class*>()->*std::declval<MethodPtr>())());\n\n  template <typename... Args>\n  ReturnType operator()(const Args&...) const {\n    return (obj_ptr->*method_ptr)();\n  }\n};\n\n// Implements the IgnoreResult(action) action.\ntemplate <typename A>\nclass IgnoreResultAction {\n public:\n  explicit IgnoreResultAction(const A& action) : action_(action) {}\n\n  template <typename F>\n  operator Action<F>() const {\n    // Assert statement belongs here because this is the best place to verify\n    // conditions on F. It produces the clearest error messages\n    // in most compilers.\n    // Impl really belongs in this scope as a local class but can't\n    // because MSVC produces duplicate symbols in different translation units\n    // in this case. Until MS fixes that bug we put Impl into the class scope\n    // and put the typedef both here (for use in assert statement) and\n    // in the Impl class. But both definitions must be the same.\n    typedef typename internal::Function<F>::Result Result;\n\n    // Asserts at compile time that F returns void.\n    static_assert(std::is_void<Result>::value, \"Result type should be void.\");\n\n    return Action<F>(new Impl<F>(action_));\n  }\n\n private:\n  template <typename F>\n  class Impl : public ActionInterface<F> {\n   public:\n    typedef typename internal::Function<F>::Result Result;\n    typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;\n\n    explicit Impl(const A& action) : action_(action) {}\n\n    void Perform(const ArgumentTuple& args) override {\n      // Performs the action and ignores its result.\n      action_.Perform(args);\n    }\n\n   private:\n    // Type OriginalFunction is the same as F except that its return\n    // type is IgnoredValue.\n    typedef\n        typename internal::Function<F>::MakeResultIgnoredValue OriginalFunction;\n\n    const Action<OriginalFunction> action_;\n  };\n\n  const A action_;\n};\n\ntemplate <typename InnerAction, size_t... I>\nstruct WithArgsAction {\n  InnerAction inner_action;\n\n  // The signature of the function as seen by the inner action, given an out\n  // action with the given result and argument types.\n  template <typename R, typename... Args>\n  using InnerSignature =\n      R(typename std::tuple_element<I, std::tuple<Args...>>::type...);\n\n  // Rather than a call operator, we must define conversion operators to\n  // particular action types. This is necessary for embedded actions like\n  // DoDefault(), which rely on an action conversion operators rather than\n  // providing a call operator because even with a particular set of arguments\n  // they don't have a fixed return type.\n\n  template <typename R, typename... Args,\n            typename std::enable_if<\n                std::is_convertible<\n                    InnerAction,\n                    // Unfortunately we can't use the InnerSignature alias here;\n                    // MSVC complains about the I parameter pack not being\n                    // expanded (error C3520) despite it being expanded in the\n                    // type alias.\n                    OnceAction<R(typename std::tuple_element<\n                                 I, std::tuple<Args...>>::type...)>>::value,\n                int>::type = 0>\n  operator OnceAction<R(Args...)>() && {  // NOLINT\n    struct OA {\n      OnceAction<InnerSignature<R, Args...>> inner_action;\n\n      R operator()(Args&&... args) && {\n        return std::move(inner_action)\n            .Call(std::get<I>(\n                std::forward_as_tuple(std::forward<Args>(args)...))...);\n      }\n    };\n\n    return OA{std::move(inner_action)};\n  }\n\n  template <typename R, typename... Args,\n            typename std::enable_if<\n                std::is_convertible<\n                    const InnerAction&,\n                    // Unfortunately we can't use the InnerSignature alias here;\n                    // MSVC complains about the I parameter pack not being\n                    // expanded (error C3520) despite it being expanded in the\n                    // type alias.\n                    Action<R(typename std::tuple_element<\n                             I, std::tuple<Args...>>::type...)>>::value,\n                int>::type = 0>\n  operator Action<R(Args...)>() const {  // NOLINT\n    Action<InnerSignature<R, Args...>> converted(inner_action);\n\n    return [converted](Args&&... args) -> R {\n      return converted.Perform(std::forward_as_tuple(\n          std::get<I>(std::forward_as_tuple(std::forward<Args>(args)...))...));\n    };\n  }\n};\n\ntemplate <typename... Actions>\nclass DoAllAction;\n\n// Base case: only a single action.\ntemplate <typename FinalAction>\nclass DoAllAction<FinalAction> {\n public:\n  struct UserConstructorTag {};\n\n  template <typename T>\n  explicit DoAllAction(UserConstructorTag, T&& action)\n      : final_action_(std::forward<T>(action)) {}\n\n  // Rather than a call operator, we must define conversion operators to\n  // particular action types. This is necessary for embedded actions like\n  // DoDefault(), which rely on an action conversion operators rather than\n  // providing a call operator because even with a particular set of arguments\n  // they don't have a fixed return type.\n\n  template <typename R, typename... Args,\n            typename std::enable_if<\n                std::is_convertible<FinalAction, OnceAction<R(Args...)>>::value,\n                int>::type = 0>\n  operator OnceAction<R(Args...)>() && {  // NOLINT\n    return std::move(final_action_);\n  }\n\n  template <\n      typename R, typename... Args,\n      typename std::enable_if<\n          std::is_convertible<const FinalAction&, Action<R(Args...)>>::value,\n          int>::type = 0>\n  operator Action<R(Args...)>() const {  // NOLINT\n    return final_action_;\n  }\n\n private:\n  FinalAction final_action_;\n};\n\n// Recursive case: support N actions by calling the initial action and then\n// calling through to the base class containing N-1 actions.\ntemplate <typename InitialAction, typename... OtherActions>\nclass DoAllAction<InitialAction, OtherActions...>\n    : private DoAllAction<OtherActions...> {\n private:\n  using Base = DoAllAction<OtherActions...>;\n\n  // The type of reference that should be provided to an initial action for a\n  // mocked function parameter of type T.\n  //\n  // There are two quirks here:\n  //\n  //  *  Unlike most forwarding functions, we pass scalars through by value.\n  //     This isn't strictly necessary because an lvalue reference would work\n  //     fine too and be consistent with other non-reference types, but it's\n  //     perhaps less surprising.\n  //\n  //     For example if the mocked function has signature void(int), then it\n  //     might seem surprising for the user's initial action to need to be\n  //     convertible to Action<void(const int&)>. This is perhaps less\n  //     surprising for a non-scalar type where there may be a performance\n  //     impact, or it might even be impossible, to pass by value.\n  //\n  //  *  More surprisingly, `const T&` is often not a const reference type.\n  //     By the reference collapsing rules in C++17 [dcl.ref]/6, if T refers to\n  //     U& or U&& for some non-scalar type U, then InitialActionArgType<T> is\n  //     U&. In other words, we may hand over a non-const reference.\n  //\n  //     So for example, given some non-scalar type Obj we have the following\n  //     mappings:\n  //\n  //            T               InitialActionArgType<T>\n  //         -------            -----------------------\n  //         Obj                const Obj&\n  //         Obj&               Obj&\n  //         Obj&&              Obj&\n  //         const Obj          const Obj&\n  //         const Obj&         const Obj&\n  //         const Obj&&        const Obj&\n  //\n  //     In other words, the initial actions get a mutable view of an non-scalar\n  //     argument if and only if the mock function itself accepts a non-const\n  //     reference type. They are never given an rvalue reference to an\n  //     non-scalar type.\n  //\n  //     This situation makes sense if you imagine use with a matcher that is\n  //     designed to write through a reference. For example, if the caller wants\n  //     to fill in a reference argument and then return a canned value:\n  //\n  //         EXPECT_CALL(mock, Call)\n  //             .WillOnce(DoAll(SetArgReferee<0>(17), Return(19)));\n  //\n  template <typename T>\n  using InitialActionArgType =\n      typename std::conditional<std::is_scalar<T>::value, T, const T&>::type;\n\n public:\n  struct UserConstructorTag {};\n\n  template <typename T, typename... U>\n  explicit DoAllAction(UserConstructorTag, T&& initial_action,\n                       U&&... other_actions)\n      : Base({}, std::forward<U>(other_actions)...),\n        initial_action_(std::forward<T>(initial_action)) {}\n\n  template <typename R, typename... Args,\n            typename std::enable_if<\n                conjunction<\n                    // Both the initial action and the rest must support\n                    // conversion to OnceAction.\n                    std::is_convertible<\n                        InitialAction,\n                        OnceAction<void(InitialActionArgType<Args>...)>>,\n                    std::is_convertible<Base, OnceAction<R(Args...)>>>::value,\n                int>::type = 0>\n  operator OnceAction<R(Args...)>() && {  // NOLINT\n    // Return an action that first calls the initial action with arguments\n    // filtered through InitialActionArgType, then forwards arguments directly\n    // to the base class to deal with the remaining actions.\n    struct OA {\n      OnceAction<void(InitialActionArgType<Args>...)> initial_action;\n      OnceAction<R(Args...)> remaining_actions;\n\n      R operator()(Args... args) && {\n        std::move(initial_action)\n            .Call(static_cast<InitialActionArgType<Args>>(args)...);\n\n        return std::move(remaining_actions).Call(std::forward<Args>(args)...);\n      }\n    };\n\n    return OA{\n        std::move(initial_action_),\n        std::move(static_cast<Base&>(*this)),\n    };\n  }\n\n  template <\n      typename R, typename... Args,\n      typename std::enable_if<\n          conjunction<\n              // Both the initial action and the rest must support conversion to\n              // Action.\n              std::is_convertible<const InitialAction&,\n                                  Action<void(InitialActionArgType<Args>...)>>,\n              std::is_convertible<const Base&, Action<R(Args...)>>>::value,\n          int>::type = 0>\n  operator Action<R(Args...)>() const {  // NOLINT\n    // Return an action that first calls the initial action with arguments\n    // filtered through InitialActionArgType, then forwards arguments directly\n    // to the base class to deal with the remaining actions.\n    struct OA {\n      Action<void(InitialActionArgType<Args>...)> initial_action;\n      Action<R(Args...)> remaining_actions;\n\n      R operator()(Args... args) const {\n        initial_action.Perform(std::forward_as_tuple(\n            static_cast<InitialActionArgType<Args>>(args)...));\n\n        return remaining_actions.Perform(\n            std::forward_as_tuple(std::forward<Args>(args)...));\n      }\n    };\n\n    return OA{\n        initial_action_,\n        static_cast<const Base&>(*this),\n    };\n  }\n\n private:\n  InitialAction initial_action_;\n};\n\ntemplate <typename T, typename... Params>\nstruct ReturnNewAction {\n  T* operator()() const {\n    return internal::Apply(\n        [](const Params&... unpacked_params) {\n          return new T(unpacked_params...);\n        },\n        params);\n  }\n  std::tuple<Params...> params;\n};\n\ntemplate <size_t k>\nstruct ReturnArgAction {\n  template <typename... Args,\n            typename = typename std::enable_if<(k < sizeof...(Args))>::type>\n  auto operator()(Args&&... args) const -> decltype(std::get<k>(\n      std::forward_as_tuple(std::forward<Args>(args)...))) {\n    return std::get<k>(std::forward_as_tuple(std::forward<Args>(args)...));\n  }\n};\n\ntemplate <size_t k, typename Ptr>\nstruct SaveArgAction {\n  Ptr pointer;\n\n  template <typename... Args>\n  void operator()(const Args&... args) const {\n    *pointer = std::get<k>(std::tie(args...));\n  }\n};\n\ntemplate <size_t k, typename Ptr>\nstruct SaveArgPointeeAction {\n  Ptr pointer;\n\n  template <typename... Args>\n  void operator()(const Args&... args) const {\n    *pointer = *std::get<k>(std::tie(args...));\n  }\n};\n\ntemplate <size_t k, typename T>\nstruct SetArgRefereeAction {\n  T value;\n\n  template <typename... Args>\n  void operator()(Args&&... args) const {\n    using argk_type =\n        typename ::std::tuple_element<k, std::tuple<Args...>>::type;\n    static_assert(std::is_lvalue_reference<argk_type>::value,\n                  \"Argument must be a reference type.\");\n    std::get<k>(std::tie(args...)) = value;\n  }\n};\n\ntemplate <size_t k, typename I1, typename I2>\nstruct SetArrayArgumentAction {\n  I1 first;\n  I2 last;\n\n  template <typename... Args>\n  void operator()(const Args&... args) const {\n    auto value = std::get<k>(std::tie(args...));\n    for (auto it = first; it != last; ++it, (void)++value) {\n      *value = *it;\n    }\n  }\n};\n\ntemplate <size_t k>\nstruct DeleteArgAction {\n  template <typename... Args>\n  void operator()(const Args&... args) const {\n    delete std::get<k>(std::tie(args...));\n  }\n};\n\ntemplate <typename Ptr>\nstruct ReturnPointeeAction {\n  Ptr pointer;\n  template <typename... Args>\n  auto operator()(const Args&...) const -> decltype(*pointer) {\n    return *pointer;\n  }\n};\n\n#if GTEST_HAS_EXCEPTIONS\ntemplate <typename T>\nstruct ThrowAction {\n  T exception;\n  // We use a conversion operator to adapt to any return type.\n  template <typename R, typename... Args>\n  operator Action<R(Args...)>() const {  // NOLINT\n    T copy = exception;\n    return [copy](Args...) -> R { throw copy; };\n  }\n};\n#endif  // GTEST_HAS_EXCEPTIONS\n\n}  // namespace internal\n\n// An Unused object can be implicitly constructed from ANY value.\n// This is handy when defining actions that ignore some or all of the\n// mock function arguments.  For example, given\n//\n//   MOCK_METHOD3(Foo, double(const string& label, double x, double y));\n//   MOCK_METHOD3(Bar, double(int index, double x, double y));\n//\n// instead of\n//\n//   double DistanceToOriginWithLabel(const string& label, double x, double y) {\n//     return sqrt(x*x + y*y);\n//   }\n//   double DistanceToOriginWithIndex(int index, double x, double y) {\n//     return sqrt(x*x + y*y);\n//   }\n//   ...\n//   EXPECT_CALL(mock, Foo(\"abc\", _, _))\n//       .WillOnce(Invoke(DistanceToOriginWithLabel));\n//   EXPECT_CALL(mock, Bar(5, _, _))\n//       .WillOnce(Invoke(DistanceToOriginWithIndex));\n//\n// you could write\n//\n//   // We can declare any uninteresting argument as Unused.\n//   double DistanceToOrigin(Unused, double x, double y) {\n//     return sqrt(x*x + y*y);\n//   }\n//   ...\n//   EXPECT_CALL(mock, Foo(\"abc\", _, _)).WillOnce(Invoke(DistanceToOrigin));\n//   EXPECT_CALL(mock, Bar(5, _, _)).WillOnce(Invoke(DistanceToOrigin));\ntypedef internal::IgnoredValue Unused;\n\n// Creates an action that does actions a1, a2, ..., sequentially in\n// each invocation. All but the last action will have a readonly view of the\n// arguments.\ntemplate <typename... Action>\ninternal::DoAllAction<typename std::decay<Action>::type...> DoAll(\n    Action&&... action) {\n  return internal::DoAllAction<typename std::decay<Action>::type...>(\n      {}, std::forward<Action>(action)...);\n}\n\n// WithArg<k>(an_action) creates an action that passes the k-th\n// (0-based) argument of the mock function to an_action and performs\n// it.  It adapts an action accepting one argument to one that accepts\n// multiple arguments.  For convenience, we also provide\n// WithArgs<k>(an_action) (defined below) as a synonym.\ntemplate <size_t k, typename InnerAction>\ninternal::WithArgsAction<typename std::decay<InnerAction>::type, k> WithArg(\n    InnerAction&& action) {\n  return {std::forward<InnerAction>(action)};\n}\n\n// WithArgs<N1, N2, ..., Nk>(an_action) creates an action that passes\n// the selected arguments of the mock function to an_action and\n// performs it.  It serves as an adaptor between actions with\n// different argument lists.\ntemplate <size_t k, size_t... ks, typename InnerAction>\ninternal::WithArgsAction<typename std::decay<InnerAction>::type, k, ks...>\nWithArgs(InnerAction&& action) {\n  return {std::forward<InnerAction>(action)};\n}\n\n// WithoutArgs(inner_action) can be used in a mock function with a\n// non-empty argument list to perform inner_action, which takes no\n// argument.  In other words, it adapts an action accepting no\n// argument to one that accepts (and ignores) arguments.\ntemplate <typename InnerAction>\ninternal::WithArgsAction<typename std::decay<InnerAction>::type> WithoutArgs(\n    InnerAction&& action) {\n  return {std::forward<InnerAction>(action)};\n}\n\n// Creates an action that returns a value.\n//\n// The returned type can be used with a mock function returning a non-void,\n// non-reference type U as follows:\n//\n//  *  If R is convertible to U and U is move-constructible, then the action can\n//     be used with WillOnce.\n//\n//  *  If const R& is convertible to U and U is copy-constructible, then the\n//     action can be used with both WillOnce and WillRepeatedly.\n//\n// The mock expectation contains the R value from which the U return value is\n// constructed (a move/copy of the argument to Return). This means that the R\n// value will survive at least until the mock object's expectations are cleared\n// or the mock object is destroyed, meaning that U can safely be a\n// reference-like type such as std::string_view:\n//\n//     // The mock function returns a view of a copy of the string fed to\n//     // Return. The view is valid even after the action is performed.\n//     MockFunction<std::string_view()> mock;\n//     EXPECT_CALL(mock, Call).WillOnce(Return(std::string(\"taco\")));\n//     const std::string_view result = mock.AsStdFunction()();\n//     EXPECT_EQ(\"taco\", result);\n//\ntemplate <typename R>\ninternal::ReturnAction<R> Return(R value) {\n  return internal::ReturnAction<R>(std::move(value));\n}\n\n// Creates an action that returns NULL.\ninline PolymorphicAction<internal::ReturnNullAction> ReturnNull() {\n  return MakePolymorphicAction(internal::ReturnNullAction());\n}\n\n// Creates an action that returns from a void function.\ninline PolymorphicAction<internal::ReturnVoidAction> Return() {\n  return MakePolymorphicAction(internal::ReturnVoidAction());\n}\n\n// Creates an action that returns the reference to a variable.\ntemplate <typename R>\ninline internal::ReturnRefAction<R> ReturnRef(R& x) {  // NOLINT\n  return internal::ReturnRefAction<R>(x);\n}\n\n// Prevent using ReturnRef on reference to temporary.\ntemplate <typename R, R* = nullptr>\ninternal::ReturnRefAction<R> ReturnRef(R&&) = delete;\n\n// Creates an action that returns the reference to a copy of the\n// argument.  The copy is created when the action is constructed and\n// lives as long as the action.\ntemplate <typename R>\ninline internal::ReturnRefOfCopyAction<R> ReturnRefOfCopy(const R& x) {\n  return internal::ReturnRefOfCopyAction<R>(x);\n}\n\n// DEPRECATED: use Return(x) directly with WillOnce.\n//\n// Modifies the parent action (a Return() action) to perform a move of the\n// argument instead of a copy.\n// Return(ByMove()) actions can only be executed once and will assert this\n// invariant.\ntemplate <typename R>\ninternal::ByMoveWrapper<R> ByMove(R x) {\n  return internal::ByMoveWrapper<R>(std::move(x));\n}\n\n// Creates an action that returns an element of `vals`. Calling this action will\n// repeatedly return the next value from `vals` until it reaches the end and\n// will restart from the beginning.\ntemplate <typename T>\ninternal::ReturnRoundRobinAction<T> ReturnRoundRobin(std::vector<T> vals) {\n  return internal::ReturnRoundRobinAction<T>(std::move(vals));\n}\n\n// Creates an action that returns an element of `vals`. Calling this action will\n// repeatedly return the next value from `vals` until it reaches the end and\n// will restart from the beginning.\ntemplate <typename T>\ninternal::ReturnRoundRobinAction<T> ReturnRoundRobin(\n    std::initializer_list<T> vals) {\n  return internal::ReturnRoundRobinAction<T>(std::vector<T>(vals));\n}\n\n// Creates an action that does the default action for the give mock function.\ninline internal::DoDefaultAction DoDefault() {\n  return internal::DoDefaultAction();\n}\n\n// Creates an action that sets the variable pointed by the N-th\n// (0-based) function argument to 'value'.\ntemplate <size_t N, typename T>\ninternal::SetArgumentPointeeAction<N, T> SetArgPointee(T value) {\n  return {std::move(value)};\n}\n\n// The following version is DEPRECATED.\ntemplate <size_t N, typename T>\ninternal::SetArgumentPointeeAction<N, T> SetArgumentPointee(T value) {\n  return {std::move(value)};\n}\n\n// Creates an action that sets a pointer referent to a given value.\ntemplate <typename T1, typename T2>\nPolymorphicAction<internal::AssignAction<T1, T2>> Assign(T1* ptr, T2 val) {\n  return MakePolymorphicAction(internal::AssignAction<T1, T2>(ptr, val));\n}\n\n#if !GTEST_OS_WINDOWS_MOBILE\n\n// Creates an action that sets errno and returns the appropriate error.\ntemplate <typename T>\nPolymorphicAction<internal::SetErrnoAndReturnAction<T>> SetErrnoAndReturn(\n    int errval, T result) {\n  return MakePolymorphicAction(\n      internal::SetErrnoAndReturnAction<T>(errval, result));\n}\n\n#endif  // !GTEST_OS_WINDOWS_MOBILE\n\n// Various overloads for Invoke().\n\n// Legacy function.\n// Actions can now be implicitly constructed from callables. No need to create\n// wrapper objects.\n// This function exists for backwards compatibility.\ntemplate <typename FunctionImpl>\ntypename std::decay<FunctionImpl>::type Invoke(FunctionImpl&& function_impl) {\n  return std::forward<FunctionImpl>(function_impl);\n}\n\n// Creates an action that invokes the given method on the given object\n// with the mock function's arguments.\ntemplate <class Class, typename MethodPtr>\ninternal::InvokeMethodAction<Class, MethodPtr> Invoke(Class* obj_ptr,\n                                                      MethodPtr method_ptr) {\n  return {obj_ptr, method_ptr};\n}\n\n// Creates an action that invokes 'function_impl' with no argument.\ntemplate <typename FunctionImpl>\ninternal::InvokeWithoutArgsAction<typename std::decay<FunctionImpl>::type>\nInvokeWithoutArgs(FunctionImpl function_impl) {\n  return {std::move(function_impl)};\n}\n\n// Creates an action that invokes the given method on the given object\n// with no argument.\ntemplate <class Class, typename MethodPtr>\ninternal::InvokeMethodWithoutArgsAction<Class, MethodPtr> InvokeWithoutArgs(\n    Class* obj_ptr, MethodPtr method_ptr) {\n  return {obj_ptr, method_ptr};\n}\n\n// Creates an action that performs an_action and throws away its\n// result.  In other words, it changes the return type of an_action to\n// void.  an_action MUST NOT return void, or the code won't compile.\ntemplate <typename A>\ninline internal::IgnoreResultAction<A> IgnoreResult(const A& an_action) {\n  return internal::IgnoreResultAction<A>(an_action);\n}\n\n// Creates a reference wrapper for the given L-value.  If necessary,\n// you can explicitly specify the type of the reference.  For example,\n// suppose 'derived' is an object of type Derived, ByRef(derived)\n// would wrap a Derived&.  If you want to wrap a const Base& instead,\n// where Base is a base class of Derived, just write:\n//\n//   ByRef<const Base>(derived)\n//\n// N.B. ByRef is redundant with std::ref, std::cref and std::reference_wrapper.\n// However, it may still be used for consistency with ByMove().\ntemplate <typename T>\ninline ::std::reference_wrapper<T> ByRef(T& l_value) {  // NOLINT\n  return ::std::reference_wrapper<T>(l_value);\n}\n\n// The ReturnNew<T>(a1, a2, ..., a_k) action returns a pointer to a new\n// instance of type T, constructed on the heap with constructor arguments\n// a1, a2, ..., and a_k. The caller assumes ownership of the returned value.\ntemplate <typename T, typename... Params>\ninternal::ReturnNewAction<T, typename std::decay<Params>::type...> ReturnNew(\n    Params&&... params) {\n  return {std::forward_as_tuple(std::forward<Params>(params)...)};\n}\n\n// Action ReturnArg<k>() returns the k-th argument of the mock function.\ntemplate <size_t k>\ninternal::ReturnArgAction<k> ReturnArg() {\n  return {};\n}\n\n// Action SaveArg<k>(pointer) saves the k-th (0-based) argument of the\n// mock function to *pointer.\ntemplate <size_t k, typename Ptr>\ninternal::SaveArgAction<k, Ptr> SaveArg(Ptr pointer) {\n  return {pointer};\n}\n\n// Action SaveArgPointee<k>(pointer) saves the value pointed to\n// by the k-th (0-based) argument of the mock function to *pointer.\ntemplate <size_t k, typename Ptr>\ninternal::SaveArgPointeeAction<k, Ptr> SaveArgPointee(Ptr pointer) {\n  return {pointer};\n}\n\n// Action SetArgReferee<k>(value) assigns 'value' to the variable\n// referenced by the k-th (0-based) argument of the mock function.\ntemplate <size_t k, typename T>\ninternal::SetArgRefereeAction<k, typename std::decay<T>::type> SetArgReferee(\n    T&& value) {\n  return {std::forward<T>(value)};\n}\n\n// Action SetArrayArgument<k>(first, last) copies the elements in\n// source range [first, last) to the array pointed to by the k-th\n// (0-based) argument, which can be either a pointer or an\n// iterator. The action does not take ownership of the elements in the\n// source range.\ntemplate <size_t k, typename I1, typename I2>\ninternal::SetArrayArgumentAction<k, I1, I2> SetArrayArgument(I1 first,\n                                                             I2 last) {\n  return {first, last};\n}\n\n// Action DeleteArg<k>() deletes the k-th (0-based) argument of the mock\n// function.\ntemplate <size_t k>\ninternal::DeleteArgAction<k> DeleteArg() {\n  return {};\n}\n\n// This action returns the value pointed to by 'pointer'.\ntemplate <typename Ptr>\ninternal::ReturnPointeeAction<Ptr> ReturnPointee(Ptr pointer) {\n  return {pointer};\n}\n\n// Action Throw(exception) can be used in a mock function of any type\n// to throw the given exception.  Any copyable value can be thrown.\n#if GTEST_HAS_EXCEPTIONS\ntemplate <typename T>\ninternal::ThrowAction<typename std::decay<T>::type> Throw(T&& exception) {\n  return {std::forward<T>(exception)};\n}\n#endif  // GTEST_HAS_EXCEPTIONS\n\nnamespace internal {\n\n// A macro from the ACTION* family (defined later in gmock-generated-actions.h)\n// defines an action that can be used in a mock function.  Typically,\n// these actions only care about a subset of the arguments of the mock\n// function.  For example, if such an action only uses the second\n// argument, it can be used in any mock function that takes >= 2\n// arguments where the type of the second argument is compatible.\n//\n// Therefore, the action implementation must be prepared to take more\n// arguments than it needs.  The ExcessiveArg type is used to\n// represent those excessive arguments.  In order to keep the compiler\n// error messages tractable, we define it in the testing namespace\n// instead of testing::internal.  However, this is an INTERNAL TYPE\n// and subject to change without notice, so a user MUST NOT USE THIS\n// TYPE DIRECTLY.\nstruct ExcessiveArg {};\n\n// Builds an implementation of an Action<> for some particular signature, using\n// a class defined by an ACTION* macro.\ntemplate <typename F, typename Impl>\nstruct ActionImpl;\n\ntemplate <typename Impl>\nstruct ImplBase {\n  struct Holder {\n    // Allows each copy of the Action<> to get to the Impl.\n    explicit operator const Impl&() const { return *ptr; }\n    std::shared_ptr<Impl> ptr;\n  };\n  using type = typename std::conditional<std::is_constructible<Impl>::value,\n                                         Impl, Holder>::type;\n};\n\ntemplate <typename R, typename... Args, typename Impl>\nstruct ActionImpl<R(Args...), Impl> : ImplBase<Impl>::type {\n  using Base = typename ImplBase<Impl>::type;\n  using function_type = R(Args...);\n  using args_type = std::tuple<Args...>;\n\n  ActionImpl() = default;  // Only defined if appropriate for Base.\n  explicit ActionImpl(std::shared_ptr<Impl> impl) : Base{std::move(impl)} {}\n\n  R operator()(Args&&... arg) const {\n    static constexpr size_t kMaxArgs =\n        sizeof...(Args) <= 10 ? sizeof...(Args) : 10;\n    return Apply(MakeIndexSequence<kMaxArgs>{},\n                 MakeIndexSequence<10 - kMaxArgs>{},\n                 args_type{std::forward<Args>(arg)...});\n  }\n\n  template <std::size_t... arg_id, std::size_t... excess_id>\n  R Apply(IndexSequence<arg_id...>, IndexSequence<excess_id...>,\n          const args_type& args) const {\n    // Impl need not be specific to the signature of action being implemented;\n    // only the implementing function body needs to have all of the specific\n    // types instantiated.  Up to 10 of the args that are provided by the\n    // args_type get passed, followed by a dummy of unspecified type for the\n    // remainder up to 10 explicit args.\n    static constexpr ExcessiveArg kExcessArg{};\n    return static_cast<const Impl&>(*this)\n        .template gmock_PerformImpl<\n            /*function_type=*/function_type, /*return_type=*/R,\n            /*args_type=*/args_type,\n            /*argN_type=*/\n            typename std::tuple_element<arg_id, args_type>::type...>(\n            /*args=*/args, std::get<arg_id>(args)...,\n            ((void)excess_id, kExcessArg)...);\n  }\n};\n\n// Stores a default-constructed Impl as part of the Action<>'s\n// std::function<>. The Impl should be trivial to copy.\ntemplate <typename F, typename Impl>\n::testing::Action<F> MakeAction() {\n  return ::testing::Action<F>(ActionImpl<F, Impl>());\n}\n\n// Stores just the one given instance of Impl.\ntemplate <typename F, typename Impl>\n::testing::Action<F> MakeAction(std::shared_ptr<Impl> impl) {\n  return ::testing::Action<F>(ActionImpl<F, Impl>(std::move(impl)));\n}\n\n#define GMOCK_INTERNAL_ARG_UNUSED(i, data, el) \\\n  , const arg##i##_type& arg##i GTEST_ATTRIBUTE_UNUSED_\n#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_                 \\\n  const args_type& args GTEST_ATTRIBUTE_UNUSED_ GMOCK_PP_REPEAT( \\\n      GMOCK_INTERNAL_ARG_UNUSED, , 10)\n\n#define GMOCK_INTERNAL_ARG(i, data, el) , const arg##i##_type& arg##i\n#define GMOCK_ACTION_ARG_TYPES_AND_NAMES_ \\\n  const args_type& args GMOCK_PP_REPEAT(GMOCK_INTERNAL_ARG, , 10)\n\n#define GMOCK_INTERNAL_TEMPLATE_ARG(i, data, el) , typename arg##i##_type\n#define GMOCK_ACTION_TEMPLATE_ARGS_NAMES_ \\\n  GMOCK_PP_TAIL(GMOCK_PP_REPEAT(GMOCK_INTERNAL_TEMPLATE_ARG, , 10))\n\n#define GMOCK_INTERNAL_TYPENAME_PARAM(i, data, param) , typename param##_type\n#define GMOCK_ACTION_TYPENAME_PARAMS_(params) \\\n  GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPENAME_PARAM, , params))\n\n#define GMOCK_INTERNAL_TYPE_PARAM(i, data, param) , param##_type\n#define GMOCK_ACTION_TYPE_PARAMS_(params) \\\n  GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_PARAM, , params))\n\n#define GMOCK_INTERNAL_TYPE_GVALUE_PARAM(i, data, param) \\\n  , param##_type gmock_p##i\n#define GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params) \\\n  GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_TYPE_GVALUE_PARAM, , params))\n\n#define GMOCK_INTERNAL_GVALUE_PARAM(i, data, param) \\\n  , std::forward<param##_type>(gmock_p##i)\n#define GMOCK_ACTION_GVALUE_PARAMS_(params) \\\n  GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GVALUE_PARAM, , params))\n\n#define GMOCK_INTERNAL_INIT_PARAM(i, data, param) \\\n  , param(::std::forward<param##_type>(gmock_p##i))\n#define GMOCK_ACTION_INIT_PARAMS_(params) \\\n  GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_INIT_PARAM, , params))\n\n#define GMOCK_INTERNAL_FIELD_PARAM(i, data, param) param##_type param;\n#define GMOCK_ACTION_FIELD_PARAMS_(params) \\\n  GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_FIELD_PARAM, , params)\n\n#define GMOCK_INTERNAL_ACTION(name, full_name, params)                         \\\n  template <GMOCK_ACTION_TYPENAME_PARAMS_(params)>                             \\\n  class full_name {                                                            \\\n   public:                                                                     \\\n    explicit full_name(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params))               \\\n        : impl_(std::make_shared<gmock_Impl>(                                  \\\n              GMOCK_ACTION_GVALUE_PARAMS_(params))) {}                         \\\n    full_name(const full_name&) = default;                                     \\\n    full_name(full_name&&) noexcept = default;                                 \\\n    template <typename F>                                                      \\\n    operator ::testing::Action<F>() const {                                    \\\n      return ::testing::internal::MakeAction<F>(impl_);                        \\\n    }                                                                          \\\n                                                                               \\\n   private:                                                                    \\\n    class gmock_Impl {                                                         \\\n     public:                                                                   \\\n      explicit gmock_Impl(GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params))            \\\n          : GMOCK_ACTION_INIT_PARAMS_(params) {}                               \\\n      template <typename function_type, typename return_type,                  \\\n                typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_>         \\\n      return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const;  \\\n      GMOCK_ACTION_FIELD_PARAMS_(params)                                       \\\n    };                                                                         \\\n    std::shared_ptr<const gmock_Impl> impl_;                                   \\\n  };                                                                           \\\n  template <GMOCK_ACTION_TYPENAME_PARAMS_(params)>                             \\\n  inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name(                    \\\n      GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) GTEST_MUST_USE_RESULT_;        \\\n  template <GMOCK_ACTION_TYPENAME_PARAMS_(params)>                             \\\n  inline full_name<GMOCK_ACTION_TYPE_PARAMS_(params)> name(                    \\\n      GMOCK_ACTION_TYPE_GVALUE_PARAMS_(params)) {                              \\\n    return full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>(                       \\\n        GMOCK_ACTION_GVALUE_PARAMS_(params));                                  \\\n  }                                                                            \\\n  template <GMOCK_ACTION_TYPENAME_PARAMS_(params)>                             \\\n  template <typename function_type, typename return_type, typename args_type,  \\\n            GMOCK_ACTION_TEMPLATE_ARGS_NAMES_>                                 \\\n  return_type                                                                  \\\n  full_name<GMOCK_ACTION_TYPE_PARAMS_(params)>::gmock_Impl::gmock_PerformImpl( \\\n      GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const\n\n}  // namespace internal\n\n// Similar to GMOCK_INTERNAL_ACTION, but no bound parameters are stored.\n#define ACTION(name)                                                          \\\n  class name##Action {                                                        \\\n   public:                                                                    \\\n    explicit name##Action() noexcept {}                                       \\\n    name##Action(const name##Action&) noexcept {}                             \\\n    template <typename F>                                                     \\\n    operator ::testing::Action<F>() const {                                   \\\n      return ::testing::internal::MakeAction<F, gmock_Impl>();                \\\n    }                                                                         \\\n                                                                              \\\n   private:                                                                   \\\n    class gmock_Impl {                                                        \\\n     public:                                                                  \\\n      template <typename function_type, typename return_type,                 \\\n                typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_>        \\\n      return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const; \\\n    };                                                                        \\\n  };                                                                          \\\n  inline name##Action name() GTEST_MUST_USE_RESULT_;                          \\\n  inline name##Action name() { return name##Action(); }                       \\\n  template <typename function_type, typename return_type, typename args_type, \\\n            GMOCK_ACTION_TEMPLATE_ARGS_NAMES_>                                \\\n  return_type name##Action::gmock_Impl::gmock_PerformImpl(                    \\\n      GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_) const\n\n#define ACTION_P(name, ...) \\\n  GMOCK_INTERNAL_ACTION(name, name##ActionP, (__VA_ARGS__))\n\n#define ACTION_P2(name, ...) \\\n  GMOCK_INTERNAL_ACTION(name, name##ActionP2, (__VA_ARGS__))\n\n#define ACTION_P3(name, ...) \\\n  GMOCK_INTERNAL_ACTION(name, name##ActionP3, (__VA_ARGS__))\n\n#define ACTION_P4(name, ...) \\\n  GMOCK_INTERNAL_ACTION(name, name##ActionP4, (__VA_ARGS__))\n\n#define ACTION_P5(name, ...) \\\n  GMOCK_INTERNAL_ACTION(name, name##ActionP5, (__VA_ARGS__))\n\n#define ACTION_P6(name, ...) \\\n  GMOCK_INTERNAL_ACTION(name, name##ActionP6, (__VA_ARGS__))\n\n#define ACTION_P7(name, ...) \\\n  GMOCK_INTERNAL_ACTION(name, name##ActionP7, (__VA_ARGS__))\n\n#define ACTION_P8(name, ...) \\\n  GMOCK_INTERNAL_ACTION(name, name##ActionP8, (__VA_ARGS__))\n\n#define ACTION_P9(name, ...) \\\n  GMOCK_INTERNAL_ACTION(name, name##ActionP9, (__VA_ARGS__))\n\n#define ACTION_P10(name, ...) \\\n  GMOCK_INTERNAL_ACTION(name, name##ActionP10, (__VA_ARGS__))\n\n}  // namespace testing\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#endif  // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_ACTIONS_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/include/gmock/gmock-cardinalities.h",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file implements some commonly used cardinalities.  More\n// cardinalities can be defined by the user implementing the\n// CardinalityInterface interface if necessary.\n\n// IWYU pragma: private, include \"gmock/gmock.h\"\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_\n#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_\n\n#include <limits.h>\n\n#include <memory>\n#include <ostream>  // NOLINT\n\n#include \"gmock/internal/gmock-port.h\"\n#include \"gtest/gtest.h\"\n\nGTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \\\n/* class A needs to have dll-interface to be used by clients of class B */)\n\nnamespace testing {\n\n// To implement a cardinality Foo, define:\n//   1. a class FooCardinality that implements the\n//      CardinalityInterface interface, and\n//   2. a factory function that creates a Cardinality object from a\n//      const FooCardinality*.\n//\n// The two-level delegation design follows that of Matcher, providing\n// consistency for extension developers.  It also eases ownership\n// management as Cardinality objects can now be copied like plain values.\n\n// The implementation of a cardinality.\nclass CardinalityInterface {\n public:\n  virtual ~CardinalityInterface() {}\n\n  // Conservative estimate on the lower/upper bound of the number of\n  // calls allowed.\n  virtual int ConservativeLowerBound() const { return 0; }\n  virtual int ConservativeUpperBound() const { return INT_MAX; }\n\n  // Returns true if and only if call_count calls will satisfy this\n  // cardinality.\n  virtual bool IsSatisfiedByCallCount(int call_count) const = 0;\n\n  // Returns true if and only if call_count calls will saturate this\n  // cardinality.\n  virtual bool IsSaturatedByCallCount(int call_count) const = 0;\n\n  // Describes self to an ostream.\n  virtual void DescribeTo(::std::ostream* os) const = 0;\n};\n\n// A Cardinality is a copyable and IMMUTABLE (except by assignment)\n// object that specifies how many times a mock function is expected to\n// be called.  The implementation of Cardinality is just a std::shared_ptr\n// to const CardinalityInterface. Don't inherit from Cardinality!\nclass GTEST_API_ Cardinality {\n public:\n  // Constructs a null cardinality.  Needed for storing Cardinality\n  // objects in STL containers.\n  Cardinality() {}\n\n  // Constructs a Cardinality from its implementation.\n  explicit Cardinality(const CardinalityInterface* impl) : impl_(impl) {}\n\n  // Conservative estimate on the lower/upper bound of the number of\n  // calls allowed.\n  int ConservativeLowerBound() const { return impl_->ConservativeLowerBound(); }\n  int ConservativeUpperBound() const { return impl_->ConservativeUpperBound(); }\n\n  // Returns true if and only if call_count calls will satisfy this\n  // cardinality.\n  bool IsSatisfiedByCallCount(int call_count) const {\n    return impl_->IsSatisfiedByCallCount(call_count);\n  }\n\n  // Returns true if and only if call_count calls will saturate this\n  // cardinality.\n  bool IsSaturatedByCallCount(int call_count) const {\n    return impl_->IsSaturatedByCallCount(call_count);\n  }\n\n  // Returns true if and only if call_count calls will over-saturate this\n  // cardinality, i.e. exceed the maximum number of allowed calls.\n  bool IsOverSaturatedByCallCount(int call_count) const {\n    return impl_->IsSaturatedByCallCount(call_count) &&\n           !impl_->IsSatisfiedByCallCount(call_count);\n  }\n\n  // Describes self to an ostream\n  void DescribeTo(::std::ostream* os) const { impl_->DescribeTo(os); }\n\n  // Describes the given actual call count to an ostream.\n  static void DescribeActualCallCountTo(int actual_call_count,\n                                        ::std::ostream* os);\n\n private:\n  std::shared_ptr<const CardinalityInterface> impl_;\n};\n\n// Creates a cardinality that allows at least n calls.\nGTEST_API_ Cardinality AtLeast(int n);\n\n// Creates a cardinality that allows at most n calls.\nGTEST_API_ Cardinality AtMost(int n);\n\n// Creates a cardinality that allows any number of calls.\nGTEST_API_ Cardinality AnyNumber();\n\n// Creates a cardinality that allows between min and max calls.\nGTEST_API_ Cardinality Between(int min, int max);\n\n// Creates a cardinality that allows exactly n calls.\nGTEST_API_ Cardinality Exactly(int n);\n\n// Creates a cardinality from its implementation.\ninline Cardinality MakeCardinality(const CardinalityInterface* c) {\n  return Cardinality(c);\n}\n\n}  // namespace testing\n\nGTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251\n\n#endif  // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_CARDINALITIES_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/include/gmock/gmock-function-mocker.h",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file implements MOCK_METHOD.\n\n// IWYU pragma: private, include \"gmock/gmock.h\"\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_  // NOLINT\n#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_  // NOLINT\n\n#include <type_traits>  // IWYU pragma: keep\n#include <utility>      // IWYU pragma: keep\n\n#include \"gmock/gmock-spec-builders.h\"\n#include \"gmock/internal/gmock-internal-utils.h\"\n#include \"gmock/internal/gmock-pp.h\"\n\nnamespace testing {\nnamespace internal {\ntemplate <typename T>\nusing identity_t = T;\n\ntemplate <typename Pattern>\nstruct ThisRefAdjuster {\n  template <typename T>\n  using AdjustT = typename std::conditional<\n      std::is_const<typename std::remove_reference<Pattern>::type>::value,\n      typename std::conditional<std::is_lvalue_reference<Pattern>::value,\n                                const T&, const T&&>::type,\n      typename std::conditional<std::is_lvalue_reference<Pattern>::value, T&,\n                                T&&>::type>::type;\n\n  template <typename MockType>\n  static AdjustT<MockType> Adjust(const MockType& mock) {\n    return static_cast<AdjustT<MockType>>(const_cast<MockType&>(mock));\n  }\n};\n\nconstexpr bool PrefixOf(const char* a, const char* b) {\n  return *a == 0 || (*a == *b && internal::PrefixOf(a + 1, b + 1));\n}\n\ntemplate <int N, int M>\nconstexpr bool StartsWith(const char (&prefix)[N], const char (&str)[M]) {\n  return N <= M && internal::PrefixOf(prefix, str);\n}\n\ntemplate <int N, int M>\nconstexpr bool EndsWith(const char (&suffix)[N], const char (&str)[M]) {\n  return N <= M && internal::PrefixOf(suffix, str + M - N);\n}\n\ntemplate <int N, int M>\nconstexpr bool Equals(const char (&a)[N], const char (&b)[M]) {\n  return N == M && internal::PrefixOf(a, b);\n}\n\ntemplate <int N>\nconstexpr bool ValidateSpec(const char (&spec)[N]) {\n  return internal::Equals(\"const\", spec) ||\n         internal::Equals(\"override\", spec) ||\n         internal::Equals(\"final\", spec) ||\n         internal::Equals(\"noexcept\", spec) ||\n         (internal::StartsWith(\"noexcept(\", spec) &&\n          internal::EndsWith(\")\", spec)) ||\n         internal::Equals(\"ref(&)\", spec) ||\n         internal::Equals(\"ref(&&)\", spec) ||\n         (internal::StartsWith(\"Calltype(\", spec) &&\n          internal::EndsWith(\")\", spec));\n}\n\n}  // namespace internal\n\n// The style guide prohibits \"using\" statements in a namespace scope\n// inside a header file.  However, the FunctionMocker class template\n// is meant to be defined in the ::testing namespace.  The following\n// line is just a trick for working around a bug in MSVC 8.0, which\n// cannot handle it if we define FunctionMocker in ::testing.\nusing internal::FunctionMocker;\n}  // namespace testing\n\n#define MOCK_METHOD(...) \\\n  GMOCK_PP_VARIADIC_CALL(GMOCK_INTERNAL_MOCK_METHOD_ARG_, __VA_ARGS__)\n\n#define GMOCK_INTERNAL_MOCK_METHOD_ARG_1(...) \\\n  GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)\n\n#define GMOCK_INTERNAL_MOCK_METHOD_ARG_2(...) \\\n  GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)\n\n#define GMOCK_INTERNAL_MOCK_METHOD_ARG_3(_Ret, _MethodName, _Args) \\\n  GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, ())\n\n#define GMOCK_INTERNAL_MOCK_METHOD_ARG_4(_Ret, _MethodName, _Args, _Spec)  \\\n  GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Args);                                \\\n  GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Spec);                                \\\n  GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE(                                   \\\n      GMOCK_PP_NARG0 _Args, GMOCK_INTERNAL_SIGNATURE(_Ret, _Args));        \\\n  GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec)                                  \\\n  GMOCK_INTERNAL_MOCK_METHOD_IMPL(                                         \\\n      GMOCK_PP_NARG0 _Args, _MethodName, GMOCK_INTERNAL_HAS_CONST(_Spec),  \\\n      GMOCK_INTERNAL_HAS_OVERRIDE(_Spec), GMOCK_INTERNAL_HAS_FINAL(_Spec), \\\n      GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Spec),                             \\\n      GMOCK_INTERNAL_GET_CALLTYPE_SPEC(_Spec),                             \\\n      GMOCK_INTERNAL_GET_REF_SPEC(_Spec),                                  \\\n      (GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)))\n\n#define GMOCK_INTERNAL_MOCK_METHOD_ARG_5(...) \\\n  GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)\n\n#define GMOCK_INTERNAL_MOCK_METHOD_ARG_6(...) \\\n  GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)\n\n#define GMOCK_INTERNAL_MOCK_METHOD_ARG_7(...) \\\n  GMOCK_INTERNAL_WRONG_ARITY(__VA_ARGS__)\n\n#define GMOCK_INTERNAL_WRONG_ARITY(...)                                      \\\n  static_assert(                                                             \\\n      false,                                                                 \\\n      \"MOCK_METHOD must be called with 3 or 4 arguments. _Ret, \"             \\\n      \"_MethodName, _Args and optionally _Spec. _Args and _Spec must be \"    \\\n      \"enclosed in parentheses. If _Ret is a type with unprotected commas, \" \\\n      \"it must also be enclosed in parentheses.\")\n\n#define GMOCK_INTERNAL_ASSERT_PARENTHESIS(_Tuple) \\\n  static_assert(                                  \\\n      GMOCK_PP_IS_ENCLOSED_PARENS(_Tuple),        \\\n      GMOCK_PP_STRINGIZE(_Tuple) \" should be enclosed in parentheses.\")\n\n#define GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE(_N, ...)                 \\\n  static_assert(                                                       \\\n      std::is_function<__VA_ARGS__>::value,                            \\\n      \"Signature must be a function type, maybe return type contains \" \\\n      \"unprotected comma.\");                                           \\\n  static_assert(                                                       \\\n      ::testing::tuple_size<typename ::testing::internal::Function<    \\\n              __VA_ARGS__>::ArgumentTuple>::value == _N,               \\\n      \"This method does not take \" GMOCK_PP_STRINGIZE(                 \\\n          _N) \" arguments. Parenthesize all types with unprotected commas.\")\n\n#define GMOCK_INTERNAL_ASSERT_VALID_SPEC(_Spec) \\\n  GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT, ~, _Spec)\n\n#define GMOCK_INTERNAL_MOCK_METHOD_IMPL(_N, _MethodName, _Constness,           \\\n                                        _Override, _Final, _NoexceptSpec,      \\\n                                        _CallType, _RefSpec, _Signature)       \\\n  typename ::testing::internal::Function<GMOCK_PP_REMOVE_PARENS(               \\\n      _Signature)>::Result                                                     \\\n  GMOCK_INTERNAL_EXPAND(_CallType)                                             \\\n      _MethodName(GMOCK_PP_REPEAT(GMOCK_INTERNAL_PARAMETER, _Signature, _N))   \\\n          GMOCK_PP_IF(_Constness, const, ) _RefSpec _NoexceptSpec              \\\n          GMOCK_PP_IF(_Override, override, ) GMOCK_PP_IF(_Final, final, ) {    \\\n    GMOCK_MOCKER_(_N, _Constness, _MethodName)                                 \\\n        .SetOwnerAndName(this, #_MethodName);                                  \\\n    return GMOCK_MOCKER_(_N, _Constness, _MethodName)                          \\\n        .Invoke(GMOCK_PP_REPEAT(GMOCK_INTERNAL_FORWARD_ARG, _Signature, _N));  \\\n  }                                                                            \\\n  ::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \\\n      GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_PARAMETER, _Signature, _N))       \\\n      GMOCK_PP_IF(_Constness, const, ) _RefSpec {                              \\\n    GMOCK_MOCKER_(_N, _Constness, _MethodName).RegisterOwner(this);            \\\n    return GMOCK_MOCKER_(_N, _Constness, _MethodName)                          \\\n        .With(GMOCK_PP_REPEAT(GMOCK_INTERNAL_MATCHER_ARGUMENT, , _N));         \\\n  }                                                                            \\\n  ::testing::MockSpec<GMOCK_PP_REMOVE_PARENS(_Signature)> gmock_##_MethodName( \\\n      const ::testing::internal::WithoutMatchers&,                             \\\n      GMOCK_PP_IF(_Constness, const, )::testing::internal::Function<           \\\n          GMOCK_PP_REMOVE_PARENS(_Signature)>*) const _RefSpec _NoexceptSpec { \\\n    return ::testing::internal::ThisRefAdjuster<GMOCK_PP_IF(                   \\\n        _Constness, const, ) int _RefSpec>::Adjust(*this)                      \\\n        .gmock_##_MethodName(GMOCK_PP_REPEAT(                                  \\\n            GMOCK_INTERNAL_A_MATCHER_ARGUMENT, _Signature, _N));               \\\n  }                                                                            \\\n  mutable ::testing::FunctionMocker<GMOCK_PP_REMOVE_PARENS(_Signature)>        \\\n  GMOCK_MOCKER_(_N, _Constness, _MethodName)\n\n#define GMOCK_INTERNAL_EXPAND(...) __VA_ARGS__\n\n// Valid modifiers.\n#define GMOCK_INTERNAL_HAS_CONST(_Tuple) \\\n  GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_CONST, ~, _Tuple))\n\n#define GMOCK_INTERNAL_HAS_OVERRIDE(_Tuple) \\\n  GMOCK_PP_HAS_COMMA(                       \\\n      GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_OVERRIDE, ~, _Tuple))\n\n#define GMOCK_INTERNAL_HAS_FINAL(_Tuple) \\\n  GMOCK_PP_HAS_COMMA(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_DETECT_FINAL, ~, _Tuple))\n\n#define GMOCK_INTERNAL_GET_NOEXCEPT_SPEC(_Tuple) \\\n  GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT, ~, _Tuple)\n\n#define GMOCK_INTERNAL_NOEXCEPT_SPEC_IF_NOEXCEPT(_i, _, _elem)          \\\n  GMOCK_PP_IF(                                                          \\\n      GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)), \\\n      _elem, )\n\n#define GMOCK_INTERNAL_GET_CALLTYPE_SPEC(_Tuple) \\\n  GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_CALLTYPE_SPEC_IF_CALLTYPE, ~, _Tuple)\n\n#define GMOCK_INTERNAL_CALLTYPE_SPEC_IF_CALLTYPE(_i, _, _elem)          \\\n  GMOCK_PP_IF(                                                          \\\n      GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem)), \\\n      GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), )\n\n#define GMOCK_INTERNAL_GET_REF_SPEC(_Tuple) \\\n  GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_REF_SPEC_IF_REF, ~, _Tuple)\n\n#define GMOCK_INTERNAL_REF_SPEC_IF_REF(_i, _, _elem)                       \\\n  GMOCK_PP_IF(GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)), \\\n              GMOCK_PP_CAT(GMOCK_INTERNAL_UNPACK_, _elem), )\n\n#ifdef GMOCK_INTERNAL_STRICT_SPEC_ASSERT\n#define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem) \\\n  static_assert(                                                     \\\n      ::testing::internal::ValidateSpec(GMOCK_PP_STRINGIZE(_elem)),  \\\n      \"Token \\'\" GMOCK_PP_STRINGIZE(                                 \\\n          _elem) \"\\' cannot be recognized as a valid specification \" \\\n                 \"modifier. Is a ',' missing?\");\n#else\n#define GMOCK_INTERNAL_ASSERT_VALID_SPEC_ELEMENT(_i, _, _elem)                 \\\n  static_assert(                                                               \\\n      (GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem)) +         \\\n       GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem)) +      \\\n       GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem)) +         \\\n       GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem)) +      \\\n       GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_REF(_i, _, _elem)) +           \\\n       GMOCK_PP_HAS_COMMA(GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem))) == 1, \\\n      GMOCK_PP_STRINGIZE(                                                      \\\n          _elem) \" cannot be recognized as a valid specification modifier.\");\n#endif  // GMOCK_INTERNAL_STRICT_SPEC_ASSERT\n\n// Modifiers implementation.\n#define GMOCK_INTERNAL_DETECT_CONST(_i, _, _elem) \\\n  GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CONST_I_, _elem)\n\n#define GMOCK_INTERNAL_DETECT_CONST_I_const ,\n\n#define GMOCK_INTERNAL_DETECT_OVERRIDE(_i, _, _elem) \\\n  GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_OVERRIDE_I_, _elem)\n\n#define GMOCK_INTERNAL_DETECT_OVERRIDE_I_override ,\n\n#define GMOCK_INTERNAL_DETECT_FINAL(_i, _, _elem) \\\n  GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_FINAL_I_, _elem)\n\n#define GMOCK_INTERNAL_DETECT_FINAL_I_final ,\n\n#define GMOCK_INTERNAL_DETECT_NOEXCEPT(_i, _, _elem) \\\n  GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_NOEXCEPT_I_, _elem)\n\n#define GMOCK_INTERNAL_DETECT_NOEXCEPT_I_noexcept ,\n\n#define GMOCK_INTERNAL_DETECT_REF(_i, _, _elem) \\\n  GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_REF_I_, _elem)\n\n#define GMOCK_INTERNAL_DETECT_REF_I_ref ,\n\n#define GMOCK_INTERNAL_UNPACK_ref(x) x\n\n#define GMOCK_INTERNAL_DETECT_CALLTYPE(_i, _, _elem) \\\n  GMOCK_PP_CAT(GMOCK_INTERNAL_DETECT_CALLTYPE_I_, _elem)\n\n#define GMOCK_INTERNAL_DETECT_CALLTYPE_I_Calltype ,\n\n#define GMOCK_INTERNAL_UNPACK_Calltype(...) __VA_ARGS__\n\n// Note: The use of `identity_t` here allows _Ret to represent return types that\n// would normally need to be specified in a different way. For example, a method\n// returning a function pointer must be written as\n//\n// fn_ptr_return_t (*method(method_args_t...))(fn_ptr_args_t...)\n//\n// But we only support placing the return type at the beginning. To handle this,\n// we wrap all calls in identity_t, so that a declaration will be expanded to\n//\n// identity_t<fn_ptr_return_t (*)(fn_ptr_args_t...)> method(method_args_t...)\n//\n// This allows us to work around the syntactic oddities of function/method\n// types.\n#define GMOCK_INTERNAL_SIGNATURE(_Ret, _Args)                                 \\\n  ::testing::internal::identity_t<GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_Ret), \\\n                                              GMOCK_PP_REMOVE_PARENS,         \\\n                                              GMOCK_PP_IDENTITY)(_Ret)>(      \\\n      GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_GET_TYPE, _, _Args))\n\n#define GMOCK_INTERNAL_GET_TYPE(_i, _, _elem)                          \\\n  GMOCK_PP_COMMA_IF(_i)                                                \\\n  GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(_elem), GMOCK_PP_REMOVE_PARENS, \\\n              GMOCK_PP_IDENTITY)                                       \\\n  (_elem)\n\n#define GMOCK_INTERNAL_PARAMETER(_i, _Signature, _)            \\\n  GMOCK_PP_COMMA_IF(_i)                                        \\\n  GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \\\n  gmock_a##_i\n\n#define GMOCK_INTERNAL_FORWARD_ARG(_i, _Signature, _) \\\n  GMOCK_PP_COMMA_IF(_i)                               \\\n  ::std::forward<GMOCK_INTERNAL_ARG_O(                \\\n      _i, GMOCK_PP_REMOVE_PARENS(_Signature))>(gmock_a##_i)\n\n#define GMOCK_INTERNAL_MATCHER_PARAMETER(_i, _Signature, _)        \\\n  GMOCK_PP_COMMA_IF(_i)                                            \\\n  GMOCK_INTERNAL_MATCHER_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature)) \\\n  gmock_a##_i\n\n#define GMOCK_INTERNAL_MATCHER_ARGUMENT(_i, _1, _2) \\\n  GMOCK_PP_COMMA_IF(_i)                             \\\n  gmock_a##_i\n\n#define GMOCK_INTERNAL_A_MATCHER_ARGUMENT(_i, _Signature, _) \\\n  GMOCK_PP_COMMA_IF(_i)                                      \\\n  ::testing::A<GMOCK_INTERNAL_ARG_O(_i, GMOCK_PP_REMOVE_PARENS(_Signature))>()\n\n#define GMOCK_INTERNAL_ARG_O(_i, ...) \\\n  typename ::testing::internal::Function<__VA_ARGS__>::template Arg<_i>::type\n\n#define GMOCK_INTERNAL_MATCHER_O(_i, ...)                          \\\n  const ::testing::Matcher<typename ::testing::internal::Function< \\\n      __VA_ARGS__>::template Arg<_i>::type>&\n\n#define MOCK_METHOD0(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 0, __VA_ARGS__)\n#define MOCK_METHOD1(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 1, __VA_ARGS__)\n#define MOCK_METHOD2(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 2, __VA_ARGS__)\n#define MOCK_METHOD3(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 3, __VA_ARGS__)\n#define MOCK_METHOD4(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 4, __VA_ARGS__)\n#define MOCK_METHOD5(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 5, __VA_ARGS__)\n#define MOCK_METHOD6(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 6, __VA_ARGS__)\n#define MOCK_METHOD7(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 7, __VA_ARGS__)\n#define MOCK_METHOD8(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 8, __VA_ARGS__)\n#define MOCK_METHOD9(m, ...) GMOCK_INTERNAL_MOCK_METHODN(, , m, 9, __VA_ARGS__)\n#define MOCK_METHOD10(m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(, , m, 10, __VA_ARGS__)\n\n#define MOCK_CONST_METHOD0(m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(const, , m, 0, __VA_ARGS__)\n#define MOCK_CONST_METHOD1(m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(const, , m, 1, __VA_ARGS__)\n#define MOCK_CONST_METHOD2(m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(const, , m, 2, __VA_ARGS__)\n#define MOCK_CONST_METHOD3(m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(const, , m, 3, __VA_ARGS__)\n#define MOCK_CONST_METHOD4(m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(const, , m, 4, __VA_ARGS__)\n#define MOCK_CONST_METHOD5(m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(const, , m, 5, __VA_ARGS__)\n#define MOCK_CONST_METHOD6(m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(const, , m, 6, __VA_ARGS__)\n#define MOCK_CONST_METHOD7(m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(const, , m, 7, __VA_ARGS__)\n#define MOCK_CONST_METHOD8(m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(const, , m, 8, __VA_ARGS__)\n#define MOCK_CONST_METHOD9(m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(const, , m, 9, __VA_ARGS__)\n#define MOCK_CONST_METHOD10(m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(const, , m, 10, __VA_ARGS__)\n\n#define MOCK_METHOD0_T(m, ...) MOCK_METHOD0(m, __VA_ARGS__)\n#define MOCK_METHOD1_T(m, ...) MOCK_METHOD1(m, __VA_ARGS__)\n#define MOCK_METHOD2_T(m, ...) MOCK_METHOD2(m, __VA_ARGS__)\n#define MOCK_METHOD3_T(m, ...) MOCK_METHOD3(m, __VA_ARGS__)\n#define MOCK_METHOD4_T(m, ...) MOCK_METHOD4(m, __VA_ARGS__)\n#define MOCK_METHOD5_T(m, ...) MOCK_METHOD5(m, __VA_ARGS__)\n#define MOCK_METHOD6_T(m, ...) MOCK_METHOD6(m, __VA_ARGS__)\n#define MOCK_METHOD7_T(m, ...) MOCK_METHOD7(m, __VA_ARGS__)\n#define MOCK_METHOD8_T(m, ...) MOCK_METHOD8(m, __VA_ARGS__)\n#define MOCK_METHOD9_T(m, ...) MOCK_METHOD9(m, __VA_ARGS__)\n#define MOCK_METHOD10_T(m, ...) MOCK_METHOD10(m, __VA_ARGS__)\n\n#define MOCK_CONST_METHOD0_T(m, ...) MOCK_CONST_METHOD0(m, __VA_ARGS__)\n#define MOCK_CONST_METHOD1_T(m, ...) MOCK_CONST_METHOD1(m, __VA_ARGS__)\n#define MOCK_CONST_METHOD2_T(m, ...) MOCK_CONST_METHOD2(m, __VA_ARGS__)\n#define MOCK_CONST_METHOD3_T(m, ...) MOCK_CONST_METHOD3(m, __VA_ARGS__)\n#define MOCK_CONST_METHOD4_T(m, ...) MOCK_CONST_METHOD4(m, __VA_ARGS__)\n#define MOCK_CONST_METHOD5_T(m, ...) MOCK_CONST_METHOD5(m, __VA_ARGS__)\n#define MOCK_CONST_METHOD6_T(m, ...) MOCK_CONST_METHOD6(m, __VA_ARGS__)\n#define MOCK_CONST_METHOD7_T(m, ...) MOCK_CONST_METHOD7(m, __VA_ARGS__)\n#define MOCK_CONST_METHOD8_T(m, ...) MOCK_CONST_METHOD8(m, __VA_ARGS__)\n#define MOCK_CONST_METHOD9_T(m, ...) MOCK_CONST_METHOD9(m, __VA_ARGS__)\n#define MOCK_CONST_METHOD10_T(m, ...) MOCK_CONST_METHOD10(m, __VA_ARGS__)\n\n#define MOCK_METHOD0_WITH_CALLTYPE(ct, m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 0, __VA_ARGS__)\n#define MOCK_METHOD1_WITH_CALLTYPE(ct, m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 1, __VA_ARGS__)\n#define MOCK_METHOD2_WITH_CALLTYPE(ct, m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 2, __VA_ARGS__)\n#define MOCK_METHOD3_WITH_CALLTYPE(ct, m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 3, __VA_ARGS__)\n#define MOCK_METHOD4_WITH_CALLTYPE(ct, m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 4, __VA_ARGS__)\n#define MOCK_METHOD5_WITH_CALLTYPE(ct, m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 5, __VA_ARGS__)\n#define MOCK_METHOD6_WITH_CALLTYPE(ct, m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 6, __VA_ARGS__)\n#define MOCK_METHOD7_WITH_CALLTYPE(ct, m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 7, __VA_ARGS__)\n#define MOCK_METHOD8_WITH_CALLTYPE(ct, m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 8, __VA_ARGS__)\n#define MOCK_METHOD9_WITH_CALLTYPE(ct, m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 9, __VA_ARGS__)\n#define MOCK_METHOD10_WITH_CALLTYPE(ct, m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(, ct, m, 10, __VA_ARGS__)\n\n#define MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 0, __VA_ARGS__)\n#define MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 1, __VA_ARGS__)\n#define MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 2, __VA_ARGS__)\n#define MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 3, __VA_ARGS__)\n#define MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 4, __VA_ARGS__)\n#define MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 5, __VA_ARGS__)\n#define MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 6, __VA_ARGS__)\n#define MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 7, __VA_ARGS__)\n#define MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 8, __VA_ARGS__)\n#define MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 9, __VA_ARGS__)\n#define MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, ...) \\\n  GMOCK_INTERNAL_MOCK_METHODN(const, ct, m, 10, __VA_ARGS__)\n\n#define MOCK_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \\\n  MOCK_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__)\n#define MOCK_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \\\n  MOCK_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__)\n#define MOCK_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \\\n  MOCK_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__)\n#define MOCK_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \\\n  MOCK_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__)\n#define MOCK_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \\\n  MOCK_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__)\n#define MOCK_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \\\n  MOCK_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__)\n#define MOCK_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \\\n  MOCK_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__)\n#define MOCK_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \\\n  MOCK_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__)\n#define MOCK_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \\\n  MOCK_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__)\n#define MOCK_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \\\n  MOCK_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__)\n#define MOCK_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \\\n  MOCK_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__)\n\n#define MOCK_CONST_METHOD0_T_WITH_CALLTYPE(ct, m, ...) \\\n  MOCK_CONST_METHOD0_WITH_CALLTYPE(ct, m, __VA_ARGS__)\n#define MOCK_CONST_METHOD1_T_WITH_CALLTYPE(ct, m, ...) \\\n  MOCK_CONST_METHOD1_WITH_CALLTYPE(ct, m, __VA_ARGS__)\n#define MOCK_CONST_METHOD2_T_WITH_CALLTYPE(ct, m, ...) \\\n  MOCK_CONST_METHOD2_WITH_CALLTYPE(ct, m, __VA_ARGS__)\n#define MOCK_CONST_METHOD3_T_WITH_CALLTYPE(ct, m, ...) \\\n  MOCK_CONST_METHOD3_WITH_CALLTYPE(ct, m, __VA_ARGS__)\n#define MOCK_CONST_METHOD4_T_WITH_CALLTYPE(ct, m, ...) \\\n  MOCK_CONST_METHOD4_WITH_CALLTYPE(ct, m, __VA_ARGS__)\n#define MOCK_CONST_METHOD5_T_WITH_CALLTYPE(ct, m, ...) \\\n  MOCK_CONST_METHOD5_WITH_CALLTYPE(ct, m, __VA_ARGS__)\n#define MOCK_CONST_METHOD6_T_WITH_CALLTYPE(ct, m, ...) \\\n  MOCK_CONST_METHOD6_WITH_CALLTYPE(ct, m, __VA_ARGS__)\n#define MOCK_CONST_METHOD7_T_WITH_CALLTYPE(ct, m, ...) \\\n  MOCK_CONST_METHOD7_WITH_CALLTYPE(ct, m, __VA_ARGS__)\n#define MOCK_CONST_METHOD8_T_WITH_CALLTYPE(ct, m, ...) \\\n  MOCK_CONST_METHOD8_WITH_CALLTYPE(ct, m, __VA_ARGS__)\n#define MOCK_CONST_METHOD9_T_WITH_CALLTYPE(ct, m, ...) \\\n  MOCK_CONST_METHOD9_WITH_CALLTYPE(ct, m, __VA_ARGS__)\n#define MOCK_CONST_METHOD10_T_WITH_CALLTYPE(ct, m, ...) \\\n  MOCK_CONST_METHOD10_WITH_CALLTYPE(ct, m, __VA_ARGS__)\n\n#define GMOCK_INTERNAL_MOCK_METHODN(constness, ct, Method, args_num, ...) \\\n  GMOCK_INTERNAL_ASSERT_VALID_SIGNATURE(                                  \\\n      args_num, ::testing::internal::identity_t<__VA_ARGS__>);            \\\n  GMOCK_INTERNAL_MOCK_METHOD_IMPL(                                        \\\n      args_num, Method, GMOCK_PP_NARG0(constness), 0, 0, , ct, ,          \\\n      (::testing::internal::identity_t<__VA_ARGS__>))\n\n#define GMOCK_MOCKER_(arity, constness, Method) \\\n  GTEST_CONCAT_TOKEN_(gmock##constness##arity##_##Method##_, __LINE__)\n\n#endif  // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_FUNCTION_MOCKER_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/include/gmock/gmock-matchers.h",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// The MATCHER* family of macros can be used in a namespace scope to\n// define custom matchers easily.\n//\n// Basic Usage\n// ===========\n//\n// The syntax\n//\n//   MATCHER(name, description_string) { statements; }\n//\n// defines a matcher with the given name that executes the statements,\n// which must return a bool to indicate if the match succeeds.  Inside\n// the statements, you can refer to the value being matched by 'arg',\n// and refer to its type by 'arg_type'.\n//\n// The description string documents what the matcher does, and is used\n// to generate the failure message when the match fails.  Since a\n// MATCHER() is usually defined in a header file shared by multiple\n// C++ source files, we require the description to be a C-string\n// literal to avoid possible side effects.  It can be empty, in which\n// case we'll use the sequence of words in the matcher name as the\n// description.\n//\n// For example:\n//\n//   MATCHER(IsEven, \"\") { return (arg % 2) == 0; }\n//\n// allows you to write\n//\n//   // Expects mock_foo.Bar(n) to be called where n is even.\n//   EXPECT_CALL(mock_foo, Bar(IsEven()));\n//\n// or,\n//\n//   // Verifies that the value of some_expression is even.\n//   EXPECT_THAT(some_expression, IsEven());\n//\n// If the above assertion fails, it will print something like:\n//\n//   Value of: some_expression\n//   Expected: is even\n//     Actual: 7\n//\n// where the description \"is even\" is automatically calculated from the\n// matcher name IsEven.\n//\n// Argument Type\n// =============\n//\n// Note that the type of the value being matched (arg_type) is\n// determined by the context in which you use the matcher and is\n// supplied to you by the compiler, so you don't need to worry about\n// declaring it (nor can you).  This allows the matcher to be\n// polymorphic.  For example, IsEven() can be used to match any type\n// where the value of \"(arg % 2) == 0\" can be implicitly converted to\n// a bool.  In the \"Bar(IsEven())\" example above, if method Bar()\n// takes an int, 'arg_type' will be int; if it takes an unsigned long,\n// 'arg_type' will be unsigned long; and so on.\n//\n// Parameterizing Matchers\n// =======================\n//\n// Sometimes you'll want to parameterize the matcher.  For that you\n// can use another macro:\n//\n//   MATCHER_P(name, param_name, description_string) { statements; }\n//\n// For example:\n//\n//   MATCHER_P(HasAbsoluteValue, value, \"\") { return abs(arg) == value; }\n//\n// will allow you to write:\n//\n//   EXPECT_THAT(Blah(\"a\"), HasAbsoluteValue(n));\n//\n// which may lead to this message (assuming n is 10):\n//\n//   Value of: Blah(\"a\")\n//   Expected: has absolute value 10\n//     Actual: -9\n//\n// Note that both the matcher description and its parameter are\n// printed, making the message human-friendly.\n//\n// In the matcher definition body, you can write 'foo_type' to\n// reference the type of a parameter named 'foo'.  For example, in the\n// body of MATCHER_P(HasAbsoluteValue, value) above, you can write\n// 'value_type' to refer to the type of 'value'.\n//\n// We also provide MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P$n to\n// support multi-parameter matchers.\n//\n// Describing Parameterized Matchers\n// =================================\n//\n// The last argument to MATCHER*() is a string-typed expression.  The\n// expression can reference all of the matcher's parameters and a\n// special bool-typed variable named 'negation'.  When 'negation' is\n// false, the expression should evaluate to the matcher's description;\n// otherwise it should evaluate to the description of the negation of\n// the matcher.  For example,\n//\n//   using testing::PrintToString;\n//\n//   MATCHER_P2(InClosedRange, low, hi,\n//       std::string(negation ? \"is not\" : \"is\") + \" in range [\" +\n//       PrintToString(low) + \", \" + PrintToString(hi) + \"]\") {\n//     return low <= arg && arg <= hi;\n//   }\n//   ...\n//   EXPECT_THAT(3, InClosedRange(4, 6));\n//   EXPECT_THAT(3, Not(InClosedRange(2, 4)));\n//\n// would generate two failures that contain the text:\n//\n//   Expected: is in range [4, 6]\n//   ...\n//   Expected: is not in range [2, 4]\n//\n// If you specify \"\" as the description, the failure message will\n// contain the sequence of words in the matcher name followed by the\n// parameter values printed as a tuple.  For example,\n//\n//   MATCHER_P2(InClosedRange, low, hi, \"\") { ... }\n//   ...\n//   EXPECT_THAT(3, InClosedRange(4, 6));\n//   EXPECT_THAT(3, Not(InClosedRange(2, 4)));\n//\n// would generate two failures that contain the text:\n//\n//   Expected: in closed range (4, 6)\n//   ...\n//   Expected: not (in closed range (2, 4))\n//\n// Types of Matcher Parameters\n// ===========================\n//\n// For the purpose of typing, you can view\n//\n//   MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }\n//\n// as shorthand for\n//\n//   template <typename p1_type, ..., typename pk_type>\n//   FooMatcherPk<p1_type, ..., pk_type>\n//   Foo(p1_type p1, ..., pk_type pk) { ... }\n//\n// When you write Foo(v1, ..., vk), the compiler infers the types of\n// the parameters v1, ..., and vk for you.  If you are not happy with\n// the result of the type inference, you can specify the types by\n// explicitly instantiating the template, as in Foo<long, bool>(5,\n// false).  As said earlier, you don't get to (or need to) specify\n// 'arg_type' as that's determined by the context in which the matcher\n// is used.  You can assign the result of expression Foo(p1, ..., pk)\n// to a variable of type FooMatcherPk<p1_type, ..., pk_type>.  This\n// can be useful when composing matchers.\n//\n// While you can instantiate a matcher template with reference types,\n// passing the parameters by pointer usually makes your code more\n// readable.  If, however, you still want to pass a parameter by\n// reference, be aware that in the failure message generated by the\n// matcher you will see the value of the referenced object but not its\n// address.\n//\n// Explaining Match Results\n// ========================\n//\n// Sometimes the matcher description alone isn't enough to explain why\n// the match has failed or succeeded.  For example, when expecting a\n// long string, it can be very helpful to also print the diff between\n// the expected string and the actual one.  To achieve that, you can\n// optionally stream additional information to a special variable\n// named result_listener, whose type is a pointer to class\n// MatchResultListener:\n//\n//   MATCHER_P(EqualsLongString, str, \"\") {\n//     if (arg == str) return true;\n//\n//     *result_listener << \"the difference: \"\n///                     << DiffStrings(str, arg);\n//     return false;\n//   }\n//\n// Overloading Matchers\n// ====================\n//\n// You can overload matchers with different numbers of parameters:\n//\n//   MATCHER_P(Blah, a, description_string1) { ... }\n//   MATCHER_P2(Blah, a, b, description_string2) { ... }\n//\n// Caveats\n// =======\n//\n// When defining a new matcher, you should also consider implementing\n// MatcherInterface or using MakePolymorphicMatcher().  These\n// approaches require more work than the MATCHER* macros, but also\n// give you more control on the types of the value being matched and\n// the matcher parameters, which may leads to better compiler error\n// messages when the matcher is used wrong.  They also allow\n// overloading matchers based on parameter types (as opposed to just\n// based on the number of parameters).\n//\n// MATCHER*() can only be used in a namespace scope as templates cannot be\n// declared inside of a local class.\n//\n// More Information\n// ================\n//\n// To learn more about using these macros, please search for 'MATCHER'\n// on\n// https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md\n//\n// This file also implements some commonly used argument matchers.  More\n// matchers can be defined by the user implementing the\n// MatcherInterface<T> interface if necessary.\n//\n// See googletest/include/gtest/gtest-matchers.h for the definition of class\n// Matcher, class MatcherInterface, and others.\n\n// IWYU pragma: private, include \"gmock/gmock.h\"\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_\n#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_\n\n#include <algorithm>\n#include <cmath>\n#include <initializer_list>\n#include <iterator>\n#include <limits>\n#include <memory>\n#include <ostream>  // NOLINT\n#include <sstream>\n#include <string>\n#include <type_traits>\n#include <utility>\n#include <vector>\n\n#include \"gmock/internal/gmock-internal-utils.h\"\n#include \"gmock/internal/gmock-port.h\"\n#include \"gmock/internal/gmock-pp.h\"\n#include \"gtest/gtest.h\"\n\n// MSVC warning C5046 is new as of VS2017 version 15.8.\n#if defined(_MSC_VER) && _MSC_VER >= 1915\n#define GMOCK_MAYBE_5046_ 5046\n#else\n#define GMOCK_MAYBE_5046_\n#endif\n\nGTEST_DISABLE_MSC_WARNINGS_PUSH_(\n    4251 GMOCK_MAYBE_5046_ /* class A needs to have dll-interface to be used by\n                              clients of class B */\n    /* Symbol involving type with internal linkage not defined */)\n\nnamespace testing {\n\n// To implement a matcher Foo for type T, define:\n//   1. a class FooMatcherImpl that implements the\n//      MatcherInterface<T> interface, and\n//   2. a factory function that creates a Matcher<T> object from a\n//      FooMatcherImpl*.\n//\n// The two-level delegation design makes it possible to allow a user\n// to write \"v\" instead of \"Eq(v)\" where a Matcher is expected, which\n// is impossible if we pass matchers by pointers.  It also eases\n// ownership management as Matcher objects can now be copied like\n// plain values.\n\n// A match result listener that stores the explanation in a string.\nclass StringMatchResultListener : public MatchResultListener {\n public:\n  StringMatchResultListener() : MatchResultListener(&ss_) {}\n\n  // Returns the explanation accumulated so far.\n  std::string str() const { return ss_.str(); }\n\n  // Clears the explanation accumulated so far.\n  void Clear() { ss_.str(\"\"); }\n\n private:\n  ::std::stringstream ss_;\n\n  StringMatchResultListener(const StringMatchResultListener&) = delete;\n  StringMatchResultListener& operator=(const StringMatchResultListener&) =\n      delete;\n};\n\n// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION\n// and MUST NOT BE USED IN USER CODE!!!\nnamespace internal {\n\n// The MatcherCastImpl class template is a helper for implementing\n// MatcherCast().  We need this helper in order to partially\n// specialize the implementation of MatcherCast() (C++ allows\n// class/struct templates to be partially specialized, but not\n// function templates.).\n\n// This general version is used when MatcherCast()'s argument is a\n// polymorphic matcher (i.e. something that can be converted to a\n// Matcher but is not one yet; for example, Eq(value)) or a value (for\n// example, \"hello\").\ntemplate <typename T, typename M>\nclass MatcherCastImpl {\n public:\n  static Matcher<T> Cast(const M& polymorphic_matcher_or_value) {\n    // M can be a polymorphic matcher, in which case we want to use\n    // its conversion operator to create Matcher<T>.  Or it can be a value\n    // that should be passed to the Matcher<T>'s constructor.\n    //\n    // We can't call Matcher<T>(polymorphic_matcher_or_value) when M is a\n    // polymorphic matcher because it'll be ambiguous if T has an implicit\n    // constructor from M (this usually happens when T has an implicit\n    // constructor from any type).\n    //\n    // It won't work to unconditionally implicit_cast\n    // polymorphic_matcher_or_value to Matcher<T> because it won't trigger\n    // a user-defined conversion from M to T if one exists (assuming M is\n    // a value).\n    return CastImpl(polymorphic_matcher_or_value,\n                    std::is_convertible<M, Matcher<T>>{},\n                    std::is_convertible<M, T>{});\n  }\n\n private:\n  template <bool Ignore>\n  static Matcher<T> CastImpl(const M& polymorphic_matcher_or_value,\n                             std::true_type /* convertible_to_matcher */,\n                             std::integral_constant<bool, Ignore>) {\n    // M is implicitly convertible to Matcher<T>, which means that either\n    // M is a polymorphic matcher or Matcher<T> has an implicit constructor\n    // from M.  In both cases using the implicit conversion will produce a\n    // matcher.\n    //\n    // Even if T has an implicit constructor from M, it won't be called because\n    // creating Matcher<T> would require a chain of two user-defined conversions\n    // (first to create T from M and then to create Matcher<T> from T).\n    return polymorphic_matcher_or_value;\n  }\n\n  // M can't be implicitly converted to Matcher<T>, so M isn't a polymorphic\n  // matcher. It's a value of a type implicitly convertible to T. Use direct\n  // initialization to create a matcher.\n  static Matcher<T> CastImpl(const M& value,\n                             std::false_type /* convertible_to_matcher */,\n                             std::true_type /* convertible_to_T */) {\n    return Matcher<T>(ImplicitCast_<T>(value));\n  }\n\n  // M can't be implicitly converted to either Matcher<T> or T. Attempt to use\n  // polymorphic matcher Eq(value) in this case.\n  //\n  // Note that we first attempt to perform an implicit cast on the value and\n  // only fall back to the polymorphic Eq() matcher afterwards because the\n  // latter calls bool operator==(const Lhs& lhs, const Rhs& rhs) in the end\n  // which might be undefined even when Rhs is implicitly convertible to Lhs\n  // (e.g. std::pair<const int, int> vs. std::pair<int, int>).\n  //\n  // We don't define this method inline as we need the declaration of Eq().\n  static Matcher<T> CastImpl(const M& value,\n                             std::false_type /* convertible_to_matcher */,\n                             std::false_type /* convertible_to_T */);\n};\n\n// This more specialized version is used when MatcherCast()'s argument\n// is already a Matcher.  This only compiles when type T can be\n// statically converted to type U.\ntemplate <typename T, typename U>\nclass MatcherCastImpl<T, Matcher<U>> {\n public:\n  static Matcher<T> Cast(const Matcher<U>& source_matcher) {\n    return Matcher<T>(new Impl(source_matcher));\n  }\n\n private:\n  class Impl : public MatcherInterface<T> {\n   public:\n    explicit Impl(const Matcher<U>& source_matcher)\n        : source_matcher_(source_matcher) {}\n\n    // We delegate the matching logic to the source matcher.\n    bool MatchAndExplain(T x, MatchResultListener* listener) const override {\n      using FromType = typename std::remove_cv<typename std::remove_pointer<\n          typename std::remove_reference<T>::type>::type>::type;\n      using ToType = typename std::remove_cv<typename std::remove_pointer<\n          typename std::remove_reference<U>::type>::type>::type;\n      // Do not allow implicitly converting base*/& to derived*/&.\n      static_assert(\n          // Do not trigger if only one of them is a pointer. That implies a\n          // regular conversion and not a down_cast.\n          (std::is_pointer<typename std::remove_reference<T>::type>::value !=\n           std::is_pointer<typename std::remove_reference<U>::type>::value) ||\n              std::is_same<FromType, ToType>::value ||\n              !std::is_base_of<FromType, ToType>::value,\n          \"Can't implicitly convert from <base> to <derived>\");\n\n      // Do the cast to `U` explicitly if necessary.\n      // Otherwise, let implicit conversions do the trick.\n      using CastType =\n          typename std::conditional<std::is_convertible<T&, const U&>::value,\n                                    T&, U>::type;\n\n      return source_matcher_.MatchAndExplain(static_cast<CastType>(x),\n                                             listener);\n    }\n\n    void DescribeTo(::std::ostream* os) const override {\n      source_matcher_.DescribeTo(os);\n    }\n\n    void DescribeNegationTo(::std::ostream* os) const override {\n      source_matcher_.DescribeNegationTo(os);\n    }\n\n   private:\n    const Matcher<U> source_matcher_;\n  };\n};\n\n// This even more specialized version is used for efficiently casting\n// a matcher to its own type.\ntemplate <typename T>\nclass MatcherCastImpl<T, Matcher<T>> {\n public:\n  static Matcher<T> Cast(const Matcher<T>& matcher) { return matcher; }\n};\n\n// Template specialization for parameterless Matcher.\ntemplate <typename Derived>\nclass MatcherBaseImpl {\n public:\n  MatcherBaseImpl() = default;\n\n  template <typename T>\n  operator ::testing::Matcher<T>() const {  // NOLINT(runtime/explicit)\n    return ::testing::Matcher<T>(new\n                                 typename Derived::template gmock_Impl<T>());\n  }\n};\n\n// Template specialization for Matcher with parameters.\ntemplate <template <typename...> class Derived, typename... Ts>\nclass MatcherBaseImpl<Derived<Ts...>> {\n public:\n  // Mark the constructor explicit for single argument T to avoid implicit\n  // conversions.\n  template <typename E = std::enable_if<sizeof...(Ts) == 1>,\n            typename E::type* = nullptr>\n  explicit MatcherBaseImpl(Ts... params)\n      : params_(std::forward<Ts>(params)...) {}\n  template <typename E = std::enable_if<sizeof...(Ts) != 1>,\n            typename = typename E::type>\n  MatcherBaseImpl(Ts... params)  // NOLINT\n      : params_(std::forward<Ts>(params)...) {}\n\n  template <typename F>\n  operator ::testing::Matcher<F>() const {  // NOLINT(runtime/explicit)\n    return Apply<F>(MakeIndexSequence<sizeof...(Ts)>{});\n  }\n\n private:\n  template <typename F, std::size_t... tuple_ids>\n  ::testing::Matcher<F> Apply(IndexSequence<tuple_ids...>) const {\n    return ::testing::Matcher<F>(\n        new typename Derived<Ts...>::template gmock_Impl<F>(\n            std::get<tuple_ids>(params_)...));\n  }\n\n  const std::tuple<Ts...> params_;\n};\n\n}  // namespace internal\n\n// In order to be safe and clear, casting between different matcher\n// types is done explicitly via MatcherCast<T>(m), which takes a\n// matcher m and returns a Matcher<T>.  It compiles only when T can be\n// statically converted to the argument type of m.\ntemplate <typename T, typename M>\ninline Matcher<T> MatcherCast(const M& matcher) {\n  return internal::MatcherCastImpl<T, M>::Cast(matcher);\n}\n\n// This overload handles polymorphic matchers and values only since\n// monomorphic matchers are handled by the next one.\ntemplate <typename T, typename M>\ninline Matcher<T> SafeMatcherCast(const M& polymorphic_matcher_or_value) {\n  return MatcherCast<T>(polymorphic_matcher_or_value);\n}\n\n// This overload handles monomorphic matchers.\n//\n// In general, if type T can be implicitly converted to type U, we can\n// safely convert a Matcher<U> to a Matcher<T> (i.e. Matcher is\n// contravariant): just keep a copy of the original Matcher<U>, convert the\n// argument from type T to U, and then pass it to the underlying Matcher<U>.\n// The only exception is when U is a reference and T is not, as the\n// underlying Matcher<U> may be interested in the argument's address, which\n// is not preserved in the conversion from T to U.\ntemplate <typename T, typename U>\ninline Matcher<T> SafeMatcherCast(const Matcher<U>& matcher) {\n  // Enforce that T can be implicitly converted to U.\n  static_assert(std::is_convertible<const T&, const U&>::value,\n                \"T must be implicitly convertible to U\");\n  // Enforce that we are not converting a non-reference type T to a reference\n  // type U.\n  static_assert(std::is_reference<T>::value || !std::is_reference<U>::value,\n                \"cannot convert non reference arg to reference\");\n  // In case both T and U are arithmetic types, enforce that the\n  // conversion is not lossy.\n  typedef GTEST_REMOVE_REFERENCE_AND_CONST_(T) RawT;\n  typedef GTEST_REMOVE_REFERENCE_AND_CONST_(U) RawU;\n  constexpr bool kTIsOther = GMOCK_KIND_OF_(RawT) == internal::kOther;\n  constexpr bool kUIsOther = GMOCK_KIND_OF_(RawU) == internal::kOther;\n  static_assert(\n      kTIsOther || kUIsOther ||\n          (internal::LosslessArithmeticConvertible<RawT, RawU>::value),\n      \"conversion of arithmetic types must be lossless\");\n  return MatcherCast<T>(matcher);\n}\n\n// A<T>() returns a matcher that matches any value of type T.\ntemplate <typename T>\nMatcher<T> A();\n\n// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION\n// and MUST NOT BE USED IN USER CODE!!!\nnamespace internal {\n\n// If the explanation is not empty, prints it to the ostream.\ninline void PrintIfNotEmpty(const std::string& explanation,\n                            ::std::ostream* os) {\n  if (explanation != \"\" && os != nullptr) {\n    *os << \", \" << explanation;\n  }\n}\n\n// Returns true if the given type name is easy to read by a human.\n// This is used to decide whether printing the type of a value might\n// be helpful.\ninline bool IsReadableTypeName(const std::string& type_name) {\n  // We consider a type name readable if it's short or doesn't contain\n  // a template or function type.\n  return (type_name.length() <= 20 ||\n          type_name.find_first_of(\"<(\") == std::string::npos);\n}\n\n// Matches the value against the given matcher, prints the value and explains\n// the match result to the listener. Returns the match result.\n// 'listener' must not be NULL.\n// Value cannot be passed by const reference, because some matchers take a\n// non-const argument.\ntemplate <typename Value, typename T>\nbool MatchPrintAndExplain(Value& value, const Matcher<T>& matcher,\n                          MatchResultListener* listener) {\n  if (!listener->IsInterested()) {\n    // If the listener is not interested, we do not need to construct the\n    // inner explanation.\n    return matcher.Matches(value);\n  }\n\n  StringMatchResultListener inner_listener;\n  const bool match = matcher.MatchAndExplain(value, &inner_listener);\n\n  UniversalPrint(value, listener->stream());\n#if GTEST_HAS_RTTI\n  const std::string& type_name = GetTypeName<Value>();\n  if (IsReadableTypeName(type_name))\n    *listener->stream() << \" (of type \" << type_name << \")\";\n#endif\n  PrintIfNotEmpty(inner_listener.str(), listener->stream());\n\n  return match;\n}\n\n// An internal helper class for doing compile-time loop on a tuple's\n// fields.\ntemplate <size_t N>\nclass TuplePrefix {\n public:\n  // TuplePrefix<N>::Matches(matcher_tuple, value_tuple) returns true\n  // if and only if the first N fields of matcher_tuple matches\n  // the first N fields of value_tuple, respectively.\n  template <typename MatcherTuple, typename ValueTuple>\n  static bool Matches(const MatcherTuple& matcher_tuple,\n                      const ValueTuple& value_tuple) {\n    return TuplePrefix<N - 1>::Matches(matcher_tuple, value_tuple) &&\n           std::get<N - 1>(matcher_tuple).Matches(std::get<N - 1>(value_tuple));\n  }\n\n  // TuplePrefix<N>::ExplainMatchFailuresTo(matchers, values, os)\n  // describes failures in matching the first N fields of matchers\n  // against the first N fields of values.  If there is no failure,\n  // nothing will be streamed to os.\n  template <typename MatcherTuple, typename ValueTuple>\n  static void ExplainMatchFailuresTo(const MatcherTuple& matchers,\n                                     const ValueTuple& values,\n                                     ::std::ostream* os) {\n    // First, describes failures in the first N - 1 fields.\n    TuplePrefix<N - 1>::ExplainMatchFailuresTo(matchers, values, os);\n\n    // Then describes the failure (if any) in the (N - 1)-th (0-based)\n    // field.\n    typename std::tuple_element<N - 1, MatcherTuple>::type matcher =\n        std::get<N - 1>(matchers);\n    typedef typename std::tuple_element<N - 1, ValueTuple>::type Value;\n    const Value& value = std::get<N - 1>(values);\n    StringMatchResultListener listener;\n    if (!matcher.MatchAndExplain(value, &listener)) {\n      *os << \"  Expected arg #\" << N - 1 << \": \";\n      std::get<N - 1>(matchers).DescribeTo(os);\n      *os << \"\\n           Actual: \";\n      // We remove the reference in type Value to prevent the\n      // universal printer from printing the address of value, which\n      // isn't interesting to the user most of the time.  The\n      // matcher's MatchAndExplain() method handles the case when\n      // the address is interesting.\n      internal::UniversalPrint(value, os);\n      PrintIfNotEmpty(listener.str(), os);\n      *os << \"\\n\";\n    }\n  }\n};\n\n// The base case.\ntemplate <>\nclass TuplePrefix<0> {\n public:\n  template <typename MatcherTuple, typename ValueTuple>\n  static bool Matches(const MatcherTuple& /* matcher_tuple */,\n                      const ValueTuple& /* value_tuple */) {\n    return true;\n  }\n\n  template <typename MatcherTuple, typename ValueTuple>\n  static void ExplainMatchFailuresTo(const MatcherTuple& /* matchers */,\n                                     const ValueTuple& /* values */,\n                                     ::std::ostream* /* os */) {}\n};\n\n// TupleMatches(matcher_tuple, value_tuple) returns true if and only if\n// all matchers in matcher_tuple match the corresponding fields in\n// value_tuple.  It is a compiler error if matcher_tuple and\n// value_tuple have different number of fields or incompatible field\n// types.\ntemplate <typename MatcherTuple, typename ValueTuple>\nbool TupleMatches(const MatcherTuple& matcher_tuple,\n                  const ValueTuple& value_tuple) {\n  // Makes sure that matcher_tuple and value_tuple have the same\n  // number of fields.\n  static_assert(std::tuple_size<MatcherTuple>::value ==\n                    std::tuple_size<ValueTuple>::value,\n                \"matcher and value have different numbers of fields\");\n  return TuplePrefix<std::tuple_size<ValueTuple>::value>::Matches(matcher_tuple,\n                                                                  value_tuple);\n}\n\n// Describes failures in matching matchers against values.  If there\n// is no failure, nothing will be streamed to os.\ntemplate <typename MatcherTuple, typename ValueTuple>\nvoid ExplainMatchFailureTupleTo(const MatcherTuple& matchers,\n                                const ValueTuple& values, ::std::ostream* os) {\n  TuplePrefix<std::tuple_size<MatcherTuple>::value>::ExplainMatchFailuresTo(\n      matchers, values, os);\n}\n\n// TransformTupleValues and its helper.\n//\n// TransformTupleValuesHelper hides the internal machinery that\n// TransformTupleValues uses to implement a tuple traversal.\ntemplate <typename Tuple, typename Func, typename OutIter>\nclass TransformTupleValuesHelper {\n private:\n  typedef ::std::tuple_size<Tuple> TupleSize;\n\n public:\n  // For each member of tuple 't', taken in order, evaluates '*out++ = f(t)'.\n  // Returns the final value of 'out' in case the caller needs it.\n  static OutIter Run(Func f, const Tuple& t, OutIter out) {\n    return IterateOverTuple<Tuple, TupleSize::value>()(f, t, out);\n  }\n\n private:\n  template <typename Tup, size_t kRemainingSize>\n  struct IterateOverTuple {\n    OutIter operator()(Func f, const Tup& t, OutIter out) const {\n      *out++ = f(::std::get<TupleSize::value - kRemainingSize>(t));\n      return IterateOverTuple<Tup, kRemainingSize - 1>()(f, t, out);\n    }\n  };\n  template <typename Tup>\n  struct IterateOverTuple<Tup, 0> {\n    OutIter operator()(Func /* f */, const Tup& /* t */, OutIter out) const {\n      return out;\n    }\n  };\n};\n\n// Successively invokes 'f(element)' on each element of the tuple 't',\n// appending each result to the 'out' iterator. Returns the final value\n// of 'out'.\ntemplate <typename Tuple, typename Func, typename OutIter>\nOutIter TransformTupleValues(Func f, const Tuple& t, OutIter out) {\n  return TransformTupleValuesHelper<Tuple, Func, OutIter>::Run(f, t, out);\n}\n\n// Implements _, a matcher that matches any value of any\n// type.  This is a polymorphic matcher, so we need a template type\n// conversion operator to make it appearing as a Matcher<T> for any\n// type T.\nclass AnythingMatcher {\n public:\n  using is_gtest_matcher = void;\n\n  template <typename T>\n  bool MatchAndExplain(const T& /* x */, std::ostream* /* listener */) const {\n    return true;\n  }\n  void DescribeTo(std::ostream* os) const { *os << \"is anything\"; }\n  void DescribeNegationTo(::std::ostream* os) const {\n    // This is mostly for completeness' sake, as it's not very useful\n    // to write Not(A<bool>()).  However we cannot completely rule out\n    // such a possibility, and it doesn't hurt to be prepared.\n    *os << \"never matches\";\n  }\n};\n\n// Implements the polymorphic IsNull() matcher, which matches any raw or smart\n// pointer that is NULL.\nclass IsNullMatcher {\n public:\n  template <typename Pointer>\n  bool MatchAndExplain(const Pointer& p,\n                       MatchResultListener* /* listener */) const {\n    return p == nullptr;\n  }\n\n  void DescribeTo(::std::ostream* os) const { *os << \"is NULL\"; }\n  void DescribeNegationTo(::std::ostream* os) const { *os << \"isn't NULL\"; }\n};\n\n// Implements the polymorphic NotNull() matcher, which matches any raw or smart\n// pointer that is not NULL.\nclass NotNullMatcher {\n public:\n  template <typename Pointer>\n  bool MatchAndExplain(const Pointer& p,\n                       MatchResultListener* /* listener */) const {\n    return p != nullptr;\n  }\n\n  void DescribeTo(::std::ostream* os) const { *os << \"isn't NULL\"; }\n  void DescribeNegationTo(::std::ostream* os) const { *os << \"is NULL\"; }\n};\n\n// Ref(variable) matches any argument that is a reference to\n// 'variable'.  This matcher is polymorphic as it can match any\n// super type of the type of 'variable'.\n//\n// The RefMatcher template class implements Ref(variable).  It can\n// only be instantiated with a reference type.  This prevents a user\n// from mistakenly using Ref(x) to match a non-reference function\n// argument.  For example, the following will righteously cause a\n// compiler error:\n//\n//   int n;\n//   Matcher<int> m1 = Ref(n);   // This won't compile.\n//   Matcher<int&> m2 = Ref(n);  // This will compile.\ntemplate <typename T>\nclass RefMatcher;\n\ntemplate <typename T>\nclass RefMatcher<T&> {\n  // Google Mock is a generic framework and thus needs to support\n  // mocking any function types, including those that take non-const\n  // reference arguments.  Therefore the template parameter T (and\n  // Super below) can be instantiated to either a const type or a\n  // non-const type.\n public:\n  // RefMatcher() takes a T& instead of const T&, as we want the\n  // compiler to catch using Ref(const_value) as a matcher for a\n  // non-const reference.\n  explicit RefMatcher(T& x) : object_(x) {}  // NOLINT\n\n  template <typename Super>\n  operator Matcher<Super&>() const {\n    // By passing object_ (type T&) to Impl(), which expects a Super&,\n    // we make sure that Super is a super type of T.  In particular,\n    // this catches using Ref(const_value) as a matcher for a\n    // non-const reference, as you cannot implicitly convert a const\n    // reference to a non-const reference.\n    return MakeMatcher(new Impl<Super>(object_));\n  }\n\n private:\n  template <typename Super>\n  class Impl : public MatcherInterface<Super&> {\n   public:\n    explicit Impl(Super& x) : object_(x) {}  // NOLINT\n\n    // MatchAndExplain() takes a Super& (as opposed to const Super&)\n    // in order to match the interface MatcherInterface<Super&>.\n    bool MatchAndExplain(Super& x,\n                         MatchResultListener* listener) const override {\n      *listener << \"which is located @\" << static_cast<const void*>(&x);\n      return &x == &object_;\n    }\n\n    void DescribeTo(::std::ostream* os) const override {\n      *os << \"references the variable \";\n      UniversalPrinter<Super&>::Print(object_, os);\n    }\n\n    void DescribeNegationTo(::std::ostream* os) const override {\n      *os << \"does not reference the variable \";\n      UniversalPrinter<Super&>::Print(object_, os);\n    }\n\n   private:\n    const Super& object_;\n  };\n\n  T& object_;\n};\n\n// Polymorphic helper functions for narrow and wide string matchers.\ninline bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {\n  return String::CaseInsensitiveCStringEquals(lhs, rhs);\n}\n\ninline bool CaseInsensitiveCStringEquals(const wchar_t* lhs,\n                                         const wchar_t* rhs) {\n  return String::CaseInsensitiveWideCStringEquals(lhs, rhs);\n}\n\n// String comparison for narrow or wide strings that can have embedded NUL\n// characters.\ntemplate <typename StringType>\nbool CaseInsensitiveStringEquals(const StringType& s1, const StringType& s2) {\n  // Are the heads equal?\n  if (!CaseInsensitiveCStringEquals(s1.c_str(), s2.c_str())) {\n    return false;\n  }\n\n  // Skip the equal heads.\n  const typename StringType::value_type nul = 0;\n  const size_t i1 = s1.find(nul), i2 = s2.find(nul);\n\n  // Are we at the end of either s1 or s2?\n  if (i1 == StringType::npos || i2 == StringType::npos) {\n    return i1 == i2;\n  }\n\n  // Are the tails equal?\n  return CaseInsensitiveStringEquals(s1.substr(i1 + 1), s2.substr(i2 + 1));\n}\n\n// String matchers.\n\n// Implements equality-based string matchers like StrEq, StrCaseNe, and etc.\ntemplate <typename StringType>\nclass StrEqualityMatcher {\n public:\n  StrEqualityMatcher(StringType str, bool expect_eq, bool case_sensitive)\n      : string_(std::move(str)),\n        expect_eq_(expect_eq),\n        case_sensitive_(case_sensitive) {}\n\n#if GTEST_INTERNAL_HAS_STRING_VIEW\n  bool MatchAndExplain(const internal::StringView& s,\n                       MatchResultListener* listener) const {\n    // This should fail to compile if StringView is used with wide\n    // strings.\n    const StringType& str = std::string(s);\n    return MatchAndExplain(str, listener);\n  }\n#endif  // GTEST_INTERNAL_HAS_STRING_VIEW\n\n  // Accepts pointer types, particularly:\n  //   const char*\n  //   char*\n  //   const wchar_t*\n  //   wchar_t*\n  template <typename CharType>\n  bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {\n    if (s == nullptr) {\n      return !expect_eq_;\n    }\n    return MatchAndExplain(StringType(s), listener);\n  }\n\n  // Matches anything that can convert to StringType.\n  //\n  // This is a template, not just a plain function with const StringType&,\n  // because StringView has some interfering non-explicit constructors.\n  template <typename MatcheeStringType>\n  bool MatchAndExplain(const MatcheeStringType& s,\n                       MatchResultListener* /* listener */) const {\n    const StringType s2(s);\n    const bool eq = case_sensitive_ ? s2 == string_\n                                    : CaseInsensitiveStringEquals(s2, string_);\n    return expect_eq_ == eq;\n  }\n\n  void DescribeTo(::std::ostream* os) const {\n    DescribeToHelper(expect_eq_, os);\n  }\n\n  void DescribeNegationTo(::std::ostream* os) const {\n    DescribeToHelper(!expect_eq_, os);\n  }\n\n private:\n  void DescribeToHelper(bool expect_eq, ::std::ostream* os) const {\n    *os << (expect_eq ? \"is \" : \"isn't \");\n    *os << \"equal to \";\n    if (!case_sensitive_) {\n      *os << \"(ignoring case) \";\n    }\n    UniversalPrint(string_, os);\n  }\n\n  const StringType string_;\n  const bool expect_eq_;\n  const bool case_sensitive_;\n};\n\n// Implements the polymorphic HasSubstr(substring) matcher, which\n// can be used as a Matcher<T> as long as T can be converted to a\n// string.\ntemplate <typename StringType>\nclass HasSubstrMatcher {\n public:\n  explicit HasSubstrMatcher(const StringType& substring)\n      : substring_(substring) {}\n\n#if GTEST_INTERNAL_HAS_STRING_VIEW\n  bool MatchAndExplain(const internal::StringView& s,\n                       MatchResultListener* listener) const {\n    // This should fail to compile if StringView is used with wide\n    // strings.\n    const StringType& str = std::string(s);\n    return MatchAndExplain(str, listener);\n  }\n#endif  // GTEST_INTERNAL_HAS_STRING_VIEW\n\n  // Accepts pointer types, particularly:\n  //   const char*\n  //   char*\n  //   const wchar_t*\n  //   wchar_t*\n  template <typename CharType>\n  bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {\n    return s != nullptr && MatchAndExplain(StringType(s), listener);\n  }\n\n  // Matches anything that can convert to StringType.\n  //\n  // This is a template, not just a plain function with const StringType&,\n  // because StringView has some interfering non-explicit constructors.\n  template <typename MatcheeStringType>\n  bool MatchAndExplain(const MatcheeStringType& s,\n                       MatchResultListener* /* listener */) const {\n    return StringType(s).find(substring_) != StringType::npos;\n  }\n\n  // Describes what this matcher matches.\n  void DescribeTo(::std::ostream* os) const {\n    *os << \"has substring \";\n    UniversalPrint(substring_, os);\n  }\n\n  void DescribeNegationTo(::std::ostream* os) const {\n    *os << \"has no substring \";\n    UniversalPrint(substring_, os);\n  }\n\n private:\n  const StringType substring_;\n};\n\n// Implements the polymorphic StartsWith(substring) matcher, which\n// can be used as a Matcher<T> as long as T can be converted to a\n// string.\ntemplate <typename StringType>\nclass StartsWithMatcher {\n public:\n  explicit StartsWithMatcher(const StringType& prefix) : prefix_(prefix) {}\n\n#if GTEST_INTERNAL_HAS_STRING_VIEW\n  bool MatchAndExplain(const internal::StringView& s,\n                       MatchResultListener* listener) const {\n    // This should fail to compile if StringView is used with wide\n    // strings.\n    const StringType& str = std::string(s);\n    return MatchAndExplain(str, listener);\n  }\n#endif  // GTEST_INTERNAL_HAS_STRING_VIEW\n\n  // Accepts pointer types, particularly:\n  //   const char*\n  //   char*\n  //   const wchar_t*\n  //   wchar_t*\n  template <typename CharType>\n  bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {\n    return s != nullptr && MatchAndExplain(StringType(s), listener);\n  }\n\n  // Matches anything that can convert to StringType.\n  //\n  // This is a template, not just a plain function with const StringType&,\n  // because StringView has some interfering non-explicit constructors.\n  template <typename MatcheeStringType>\n  bool MatchAndExplain(const MatcheeStringType& s,\n                       MatchResultListener* /* listener */) const {\n    const StringType& s2(s);\n    return s2.length() >= prefix_.length() &&\n           s2.substr(0, prefix_.length()) == prefix_;\n  }\n\n  void DescribeTo(::std::ostream* os) const {\n    *os << \"starts with \";\n    UniversalPrint(prefix_, os);\n  }\n\n  void DescribeNegationTo(::std::ostream* os) const {\n    *os << \"doesn't start with \";\n    UniversalPrint(prefix_, os);\n  }\n\n private:\n  const StringType prefix_;\n};\n\n// Implements the polymorphic EndsWith(substring) matcher, which\n// can be used as a Matcher<T> as long as T can be converted to a\n// string.\ntemplate <typename StringType>\nclass EndsWithMatcher {\n public:\n  explicit EndsWithMatcher(const StringType& suffix) : suffix_(suffix) {}\n\n#if GTEST_INTERNAL_HAS_STRING_VIEW\n  bool MatchAndExplain(const internal::StringView& s,\n                       MatchResultListener* listener) const {\n    // This should fail to compile if StringView is used with wide\n    // strings.\n    const StringType& str = std::string(s);\n    return MatchAndExplain(str, listener);\n  }\n#endif  // GTEST_INTERNAL_HAS_STRING_VIEW\n\n  // Accepts pointer types, particularly:\n  //   const char*\n  //   char*\n  //   const wchar_t*\n  //   wchar_t*\n  template <typename CharType>\n  bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {\n    return s != nullptr && MatchAndExplain(StringType(s), listener);\n  }\n\n  // Matches anything that can convert to StringType.\n  //\n  // This is a template, not just a plain function with const StringType&,\n  // because StringView has some interfering non-explicit constructors.\n  template <typename MatcheeStringType>\n  bool MatchAndExplain(const MatcheeStringType& s,\n                       MatchResultListener* /* listener */) const {\n    const StringType& s2(s);\n    return s2.length() >= suffix_.length() &&\n           s2.substr(s2.length() - suffix_.length()) == suffix_;\n  }\n\n  void DescribeTo(::std::ostream* os) const {\n    *os << \"ends with \";\n    UniversalPrint(suffix_, os);\n  }\n\n  void DescribeNegationTo(::std::ostream* os) const {\n    *os << \"doesn't end with \";\n    UniversalPrint(suffix_, os);\n  }\n\n private:\n  const StringType suffix_;\n};\n\n// Implements the polymorphic WhenBase64Unescaped(matcher) matcher, which can be\n// used as a Matcher<T> as long as T can be converted to a string.\nclass WhenBase64UnescapedMatcher {\n public:\n  using is_gtest_matcher = void;\n\n  explicit WhenBase64UnescapedMatcher(\n      const Matcher<const std::string&>& internal_matcher)\n      : internal_matcher_(internal_matcher) {}\n\n  // Matches anything that can convert to std::string.\n  template <typename MatcheeStringType>\n  bool MatchAndExplain(const MatcheeStringType& s,\n                       MatchResultListener* listener) const {\n    const std::string s2(s);  // NOLINT (needed for working with string_view).\n    std::string unescaped;\n    if (!internal::Base64Unescape(s2, &unescaped)) {\n      if (listener != nullptr) {\n        *listener << \"is not a valid base64 escaped string\";\n      }\n      return false;\n    }\n    return MatchPrintAndExplain(unescaped, internal_matcher_, listener);\n  }\n\n  void DescribeTo(::std::ostream* os) const {\n    *os << \"matches after Base64Unescape \";\n    internal_matcher_.DescribeTo(os);\n  }\n\n  void DescribeNegationTo(::std::ostream* os) const {\n    *os << \"does not match after Base64Unescape \";\n    internal_matcher_.DescribeTo(os);\n  }\n\n private:\n  const Matcher<const std::string&> internal_matcher_;\n};\n\n// Implements a matcher that compares the two fields of a 2-tuple\n// using one of the ==, <=, <, etc, operators.  The two fields being\n// compared don't have to have the same type.\n//\n// The matcher defined here is polymorphic (for example, Eq() can be\n// used to match a std::tuple<int, short>, a std::tuple<const long&, double>,\n// etc).  Therefore we use a template type conversion operator in the\n// implementation.\ntemplate <typename D, typename Op>\nclass PairMatchBase {\n public:\n  template <typename T1, typename T2>\n  operator Matcher<::std::tuple<T1, T2>>() const {\n    return Matcher<::std::tuple<T1, T2>>(new Impl<const ::std::tuple<T1, T2>&>);\n  }\n  template <typename T1, typename T2>\n  operator Matcher<const ::std::tuple<T1, T2>&>() const {\n    return MakeMatcher(new Impl<const ::std::tuple<T1, T2>&>);\n  }\n\n private:\n  static ::std::ostream& GetDesc(::std::ostream& os) {  // NOLINT\n    return os << D::Desc();\n  }\n\n  template <typename Tuple>\n  class Impl : public MatcherInterface<Tuple> {\n   public:\n    bool MatchAndExplain(Tuple args,\n                         MatchResultListener* /* listener */) const override {\n      return Op()(::std::get<0>(args), ::std::get<1>(args));\n    }\n    void DescribeTo(::std::ostream* os) const override {\n      *os << \"are \" << GetDesc;\n    }\n    void DescribeNegationTo(::std::ostream* os) const override {\n      *os << \"aren't \" << GetDesc;\n    }\n  };\n};\n\nclass Eq2Matcher : public PairMatchBase<Eq2Matcher, AnyEq> {\n public:\n  static const char* Desc() { return \"an equal pair\"; }\n};\nclass Ne2Matcher : public PairMatchBase<Ne2Matcher, AnyNe> {\n public:\n  static const char* Desc() { return \"an unequal pair\"; }\n};\nclass Lt2Matcher : public PairMatchBase<Lt2Matcher, AnyLt> {\n public:\n  static const char* Desc() { return \"a pair where the first < the second\"; }\n};\nclass Gt2Matcher : public PairMatchBase<Gt2Matcher, AnyGt> {\n public:\n  static const char* Desc() { return \"a pair where the first > the second\"; }\n};\nclass Le2Matcher : public PairMatchBase<Le2Matcher, AnyLe> {\n public:\n  static const char* Desc() { return \"a pair where the first <= the second\"; }\n};\nclass Ge2Matcher : public PairMatchBase<Ge2Matcher, AnyGe> {\n public:\n  static const char* Desc() { return \"a pair where the first >= the second\"; }\n};\n\n// Implements the Not(...) matcher for a particular argument type T.\n// We do not nest it inside the NotMatcher class template, as that\n// will prevent different instantiations of NotMatcher from sharing\n// the same NotMatcherImpl<T> class.\ntemplate <typename T>\nclass NotMatcherImpl : public MatcherInterface<const T&> {\n public:\n  explicit NotMatcherImpl(const Matcher<T>& matcher) : matcher_(matcher) {}\n\n  bool MatchAndExplain(const T& x,\n                       MatchResultListener* listener) const override {\n    return !matcher_.MatchAndExplain(x, listener);\n  }\n\n  void DescribeTo(::std::ostream* os) const override {\n    matcher_.DescribeNegationTo(os);\n  }\n\n  void DescribeNegationTo(::std::ostream* os) const override {\n    matcher_.DescribeTo(os);\n  }\n\n private:\n  const Matcher<T> matcher_;\n};\n\n// Implements the Not(m) matcher, which matches a value that doesn't\n// match matcher m.\ntemplate <typename InnerMatcher>\nclass NotMatcher {\n public:\n  explicit NotMatcher(InnerMatcher matcher) : matcher_(matcher) {}\n\n  // This template type conversion operator allows Not(m) to be used\n  // to match any type m can match.\n  template <typename T>\n  operator Matcher<T>() const {\n    return Matcher<T>(new NotMatcherImpl<T>(SafeMatcherCast<T>(matcher_)));\n  }\n\n private:\n  InnerMatcher matcher_;\n};\n\n// Implements the AllOf(m1, m2) matcher for a particular argument type\n// T. We do not nest it inside the BothOfMatcher class template, as\n// that will prevent different instantiations of BothOfMatcher from\n// sharing the same BothOfMatcherImpl<T> class.\ntemplate <typename T>\nclass AllOfMatcherImpl : public MatcherInterface<const T&> {\n public:\n  explicit AllOfMatcherImpl(std::vector<Matcher<T>> matchers)\n      : matchers_(std::move(matchers)) {}\n\n  void DescribeTo(::std::ostream* os) const override {\n    *os << \"(\";\n    for (size_t i = 0; i < matchers_.size(); ++i) {\n      if (i != 0) *os << \") and (\";\n      matchers_[i].DescribeTo(os);\n    }\n    *os << \")\";\n  }\n\n  void DescribeNegationTo(::std::ostream* os) const override {\n    *os << \"(\";\n    for (size_t i = 0; i < matchers_.size(); ++i) {\n      if (i != 0) *os << \") or (\";\n      matchers_[i].DescribeNegationTo(os);\n    }\n    *os << \")\";\n  }\n\n  bool MatchAndExplain(const T& x,\n                       MatchResultListener* listener) const override {\n    // If either matcher1_ or matcher2_ doesn't match x, we only need\n    // to explain why one of them fails.\n    std::string all_match_result;\n\n    for (size_t i = 0; i < matchers_.size(); ++i) {\n      StringMatchResultListener slistener;\n      if (matchers_[i].MatchAndExplain(x, &slistener)) {\n        if (all_match_result.empty()) {\n          all_match_result = slistener.str();\n        } else {\n          std::string result = slistener.str();\n          if (!result.empty()) {\n            all_match_result += \", and \";\n            all_match_result += result;\n          }\n        }\n      } else {\n        *listener << slistener.str();\n        return false;\n      }\n    }\n\n    // Otherwise we need to explain why *both* of them match.\n    *listener << all_match_result;\n    return true;\n  }\n\n private:\n  const std::vector<Matcher<T>> matchers_;\n};\n\n// VariadicMatcher is used for the variadic implementation of\n// AllOf(m_1, m_2, ...) and AnyOf(m_1, m_2, ...).\n// CombiningMatcher<T> is used to recursively combine the provided matchers\n// (of type Args...).\ntemplate <template <typename T> class CombiningMatcher, typename... Args>\nclass VariadicMatcher {\n public:\n  VariadicMatcher(const Args&... matchers)  // NOLINT\n      : matchers_(matchers...) {\n    static_assert(sizeof...(Args) > 0, \"Must have at least one matcher.\");\n  }\n\n  VariadicMatcher(const VariadicMatcher&) = default;\n  VariadicMatcher& operator=(const VariadicMatcher&) = delete;\n\n  // This template type conversion operator allows an\n  // VariadicMatcher<Matcher1, Matcher2...> object to match any type that\n  // all of the provided matchers (Matcher1, Matcher2, ...) can match.\n  template <typename T>\n  operator Matcher<T>() const {\n    std::vector<Matcher<T>> values;\n    CreateVariadicMatcher<T>(&values, std::integral_constant<size_t, 0>());\n    return Matcher<T>(new CombiningMatcher<T>(std::move(values)));\n  }\n\n private:\n  template <typename T, size_t I>\n  void CreateVariadicMatcher(std::vector<Matcher<T>>* values,\n                             std::integral_constant<size_t, I>) const {\n    values->push_back(SafeMatcherCast<T>(std::get<I>(matchers_)));\n    CreateVariadicMatcher<T>(values, std::integral_constant<size_t, I + 1>());\n  }\n\n  template <typename T>\n  void CreateVariadicMatcher(\n      std::vector<Matcher<T>>*,\n      std::integral_constant<size_t, sizeof...(Args)>) const {}\n\n  std::tuple<Args...> matchers_;\n};\n\ntemplate <typename... Args>\nusing AllOfMatcher = VariadicMatcher<AllOfMatcherImpl, Args...>;\n\n// Implements the AnyOf(m1, m2) matcher for a particular argument type\n// T.  We do not nest it inside the AnyOfMatcher class template, as\n// that will prevent different instantiations of AnyOfMatcher from\n// sharing the same EitherOfMatcherImpl<T> class.\ntemplate <typename T>\nclass AnyOfMatcherImpl : public MatcherInterface<const T&> {\n public:\n  explicit AnyOfMatcherImpl(std::vector<Matcher<T>> matchers)\n      : matchers_(std::move(matchers)) {}\n\n  void DescribeTo(::std::ostream* os) const override {\n    *os << \"(\";\n    for (size_t i = 0; i < matchers_.size(); ++i) {\n      if (i != 0) *os << \") or (\";\n      matchers_[i].DescribeTo(os);\n    }\n    *os << \")\";\n  }\n\n  void DescribeNegationTo(::std::ostream* os) const override {\n    *os << \"(\";\n    for (size_t i = 0; i < matchers_.size(); ++i) {\n      if (i != 0) *os << \") and (\";\n      matchers_[i].DescribeNegationTo(os);\n    }\n    *os << \")\";\n  }\n\n  bool MatchAndExplain(const T& x,\n                       MatchResultListener* listener) const override {\n    std::string no_match_result;\n\n    // If either matcher1_ or matcher2_ matches x, we just need to\n    // explain why *one* of them matches.\n    for (size_t i = 0; i < matchers_.size(); ++i) {\n      StringMatchResultListener slistener;\n      if (matchers_[i].MatchAndExplain(x, &slistener)) {\n        *listener << slistener.str();\n        return true;\n      } else {\n        if (no_match_result.empty()) {\n          no_match_result = slistener.str();\n        } else {\n          std::string result = slistener.str();\n          if (!result.empty()) {\n            no_match_result += \", and \";\n            no_match_result += result;\n          }\n        }\n      }\n    }\n\n    // Otherwise we need to explain why *both* of them fail.\n    *listener << no_match_result;\n    return false;\n  }\n\n private:\n  const std::vector<Matcher<T>> matchers_;\n};\n\n// AnyOfMatcher is used for the variadic implementation of AnyOf(m_1, m_2, ...).\ntemplate <typename... Args>\nusing AnyOfMatcher = VariadicMatcher<AnyOfMatcherImpl, Args...>;\n\n// ConditionalMatcher is the implementation of Conditional(cond, m1, m2)\ntemplate <typename MatcherTrue, typename MatcherFalse>\nclass ConditionalMatcher {\n public:\n  ConditionalMatcher(bool condition, MatcherTrue matcher_true,\n                     MatcherFalse matcher_false)\n      : condition_(condition),\n        matcher_true_(std::move(matcher_true)),\n        matcher_false_(std::move(matcher_false)) {}\n\n  template <typename T>\n  operator Matcher<T>() const {  // NOLINT(runtime/explicit)\n    return condition_ ? SafeMatcherCast<T>(matcher_true_)\n                      : SafeMatcherCast<T>(matcher_false_);\n  }\n\n private:\n  bool condition_;\n  MatcherTrue matcher_true_;\n  MatcherFalse matcher_false_;\n};\n\n// Wrapper for implementation of Any/AllOfArray().\ntemplate <template <class> class MatcherImpl, typename T>\nclass SomeOfArrayMatcher {\n public:\n  // Constructs the matcher from a sequence of element values or\n  // element matchers.\n  template <typename Iter>\n  SomeOfArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}\n\n  template <typename U>\n  operator Matcher<U>() const {  // NOLINT\n    using RawU = typename std::decay<U>::type;\n    std::vector<Matcher<RawU>> matchers;\n    for (const auto& matcher : matchers_) {\n      matchers.push_back(MatcherCast<RawU>(matcher));\n    }\n    return Matcher<U>(new MatcherImpl<RawU>(std::move(matchers)));\n  }\n\n private:\n  const ::std::vector<T> matchers_;\n};\n\ntemplate <typename T>\nusing AllOfArrayMatcher = SomeOfArrayMatcher<AllOfMatcherImpl, T>;\n\ntemplate <typename T>\nusing AnyOfArrayMatcher = SomeOfArrayMatcher<AnyOfMatcherImpl, T>;\n\n// Used for implementing Truly(pred), which turns a predicate into a\n// matcher.\ntemplate <typename Predicate>\nclass TrulyMatcher {\n public:\n  explicit TrulyMatcher(Predicate pred) : predicate_(pred) {}\n\n  // This method template allows Truly(pred) to be used as a matcher\n  // for type T where T is the argument type of predicate 'pred'.  The\n  // argument is passed by reference as the predicate may be\n  // interested in the address of the argument.\n  template <typename T>\n  bool MatchAndExplain(T& x,  // NOLINT\n                       MatchResultListener* listener) const {\n    // Without the if-statement, MSVC sometimes warns about converting\n    // a value to bool (warning 4800).\n    //\n    // We cannot write 'return !!predicate_(x);' as that doesn't work\n    // when predicate_(x) returns a class convertible to bool but\n    // having no operator!().\n    if (predicate_(x)) return true;\n    *listener << \"didn't satisfy the given predicate\";\n    return false;\n  }\n\n  void DescribeTo(::std::ostream* os) const {\n    *os << \"satisfies the given predicate\";\n  }\n\n  void DescribeNegationTo(::std::ostream* os) const {\n    *os << \"doesn't satisfy the given predicate\";\n  }\n\n private:\n  Predicate predicate_;\n};\n\n// Used for implementing Matches(matcher), which turns a matcher into\n// a predicate.\ntemplate <typename M>\nclass MatcherAsPredicate {\n public:\n  explicit MatcherAsPredicate(M matcher) : matcher_(matcher) {}\n\n  // This template operator() allows Matches(m) to be used as a\n  // predicate on type T where m is a matcher on type T.\n  //\n  // The argument x is passed by reference instead of by value, as\n  // some matcher may be interested in its address (e.g. as in\n  // Matches(Ref(n))(x)).\n  template <typename T>\n  bool operator()(const T& x) const {\n    // We let matcher_ commit to a particular type here instead of\n    // when the MatcherAsPredicate object was constructed.  This\n    // allows us to write Matches(m) where m is a polymorphic matcher\n    // (e.g. Eq(5)).\n    //\n    // If we write Matcher<T>(matcher_).Matches(x) here, it won't\n    // compile when matcher_ has type Matcher<const T&>; if we write\n    // Matcher<const T&>(matcher_).Matches(x) here, it won't compile\n    // when matcher_ has type Matcher<T>; if we just write\n    // matcher_.Matches(x), it won't compile when matcher_ is\n    // polymorphic, e.g. Eq(5).\n    //\n    // MatcherCast<const T&>() is necessary for making the code work\n    // in all of the above situations.\n    return MatcherCast<const T&>(matcher_).Matches(x);\n  }\n\n private:\n  M matcher_;\n};\n\n// For implementing ASSERT_THAT() and EXPECT_THAT().  The template\n// argument M must be a type that can be converted to a matcher.\ntemplate <typename M>\nclass PredicateFormatterFromMatcher {\n public:\n  explicit PredicateFormatterFromMatcher(M m) : matcher_(std::move(m)) {}\n\n  // This template () operator allows a PredicateFormatterFromMatcher\n  // object to act as a predicate-formatter suitable for using with\n  // Google Test's EXPECT_PRED_FORMAT1() macro.\n  template <typename T>\n  AssertionResult operator()(const char* value_text, const T& x) const {\n    // We convert matcher_ to a Matcher<const T&> *now* instead of\n    // when the PredicateFormatterFromMatcher object was constructed,\n    // as matcher_ may be polymorphic (e.g. NotNull()) and we won't\n    // know which type to instantiate it to until we actually see the\n    // type of x here.\n    //\n    // We write SafeMatcherCast<const T&>(matcher_) instead of\n    // Matcher<const T&>(matcher_), as the latter won't compile when\n    // matcher_ has type Matcher<T> (e.g. An<int>()).\n    // We don't write MatcherCast<const T&> either, as that allows\n    // potentially unsafe downcasting of the matcher argument.\n    const Matcher<const T&> matcher = SafeMatcherCast<const T&>(matcher_);\n\n    // The expected path here is that the matcher should match (i.e. that most\n    // tests pass) so optimize for this case.\n    if (matcher.Matches(x)) {\n      return AssertionSuccess();\n    }\n\n    ::std::stringstream ss;\n    ss << \"Value of: \" << value_text << \"\\n\"\n       << \"Expected: \";\n    matcher.DescribeTo(&ss);\n\n    // Rerun the matcher to \"PrintAndExplain\" the failure.\n    StringMatchResultListener listener;\n    if (MatchPrintAndExplain(x, matcher, &listener)) {\n      ss << \"\\n  The matcher failed on the initial attempt; but passed when \"\n            \"rerun to generate the explanation.\";\n    }\n    ss << \"\\n  Actual: \" << listener.str();\n    return AssertionFailure() << ss.str();\n  }\n\n private:\n  const M matcher_;\n};\n\n// A helper function for converting a matcher to a predicate-formatter\n// without the user needing to explicitly write the type.  This is\n// used for implementing ASSERT_THAT() and EXPECT_THAT().\n// Implementation detail: 'matcher' is received by-value to force decaying.\ntemplate <typename M>\ninline PredicateFormatterFromMatcher<M> MakePredicateFormatterFromMatcher(\n    M matcher) {\n  return PredicateFormatterFromMatcher<M>(std::move(matcher));\n}\n\n// Implements the polymorphic IsNan() matcher, which matches any floating type\n// value that is Nan.\nclass IsNanMatcher {\n public:\n  template <typename FloatType>\n  bool MatchAndExplain(const FloatType& f,\n                       MatchResultListener* /* listener */) const {\n    return (::std::isnan)(f);\n  }\n\n  void DescribeTo(::std::ostream* os) const { *os << \"is NaN\"; }\n  void DescribeNegationTo(::std::ostream* os) const { *os << \"isn't NaN\"; }\n};\n\n// Implements the polymorphic floating point equality matcher, which matches\n// two float values using ULP-based approximation or, optionally, a\n// user-specified epsilon.  The template is meant to be instantiated with\n// FloatType being either float or double.\ntemplate <typename FloatType>\nclass FloatingEqMatcher {\n public:\n  // Constructor for FloatingEqMatcher.\n  // The matcher's input will be compared with expected.  The matcher treats two\n  // NANs as equal if nan_eq_nan is true.  Otherwise, under IEEE standards,\n  // equality comparisons between NANs will always return false.  We specify a\n  // negative max_abs_error_ term to indicate that ULP-based approximation will\n  // be used for comparison.\n  FloatingEqMatcher(FloatType expected, bool nan_eq_nan)\n      : expected_(expected), nan_eq_nan_(nan_eq_nan), max_abs_error_(-1) {}\n\n  // Constructor that supports a user-specified max_abs_error that will be used\n  // for comparison instead of ULP-based approximation.  The max absolute\n  // should be non-negative.\n  FloatingEqMatcher(FloatType expected, bool nan_eq_nan,\n                    FloatType max_abs_error)\n      : expected_(expected),\n        nan_eq_nan_(nan_eq_nan),\n        max_abs_error_(max_abs_error) {\n    GTEST_CHECK_(max_abs_error >= 0)\n        << \", where max_abs_error is\" << max_abs_error;\n  }\n\n  // Implements floating point equality matcher as a Matcher<T>.\n  template <typename T>\n  class Impl : public MatcherInterface<T> {\n   public:\n    Impl(FloatType expected, bool nan_eq_nan, FloatType max_abs_error)\n        : expected_(expected),\n          nan_eq_nan_(nan_eq_nan),\n          max_abs_error_(max_abs_error) {}\n\n    bool MatchAndExplain(T value,\n                         MatchResultListener* listener) const override {\n      const FloatingPoint<FloatType> actual(value), expected(expected_);\n\n      // Compares NaNs first, if nan_eq_nan_ is true.\n      if (actual.is_nan() || expected.is_nan()) {\n        if (actual.is_nan() && expected.is_nan()) {\n          return nan_eq_nan_;\n        }\n        // One is nan; the other is not nan.\n        return false;\n      }\n      if (HasMaxAbsError()) {\n        // We perform an equality check so that inf will match inf, regardless\n        // of error bounds.  If the result of value - expected_ would result in\n        // overflow or if either value is inf, the default result is infinity,\n        // which should only match if max_abs_error_ is also infinity.\n        if (value == expected_) {\n          return true;\n        }\n\n        const FloatType diff = value - expected_;\n        if (::std::fabs(diff) <= max_abs_error_) {\n          return true;\n        }\n\n        if (listener->IsInterested()) {\n          *listener << \"which is \" << diff << \" from \" << expected_;\n        }\n        return false;\n      } else {\n        return actual.AlmostEquals(expected);\n      }\n    }\n\n    void DescribeTo(::std::ostream* os) const override {\n      // os->precision() returns the previously set precision, which we\n      // store to restore the ostream to its original configuration\n      // after outputting.\n      const ::std::streamsize old_precision =\n          os->precision(::std::numeric_limits<FloatType>::digits10 + 2);\n      if (FloatingPoint<FloatType>(expected_).is_nan()) {\n        if (nan_eq_nan_) {\n          *os << \"is NaN\";\n        } else {\n          *os << \"never matches\";\n        }\n      } else {\n        *os << \"is approximately \" << expected_;\n        if (HasMaxAbsError()) {\n          *os << \" (absolute error <= \" << max_abs_error_ << \")\";\n        }\n      }\n      os->precision(old_precision);\n    }\n\n    void DescribeNegationTo(::std::ostream* os) const override {\n      // As before, get original precision.\n      const ::std::streamsize old_precision =\n          os->precision(::std::numeric_limits<FloatType>::digits10 + 2);\n      if (FloatingPoint<FloatType>(expected_).is_nan()) {\n        if (nan_eq_nan_) {\n          *os << \"isn't NaN\";\n        } else {\n          *os << \"is anything\";\n        }\n      } else {\n        *os << \"isn't approximately \" << expected_;\n        if (HasMaxAbsError()) {\n          *os << \" (absolute error > \" << max_abs_error_ << \")\";\n        }\n      }\n      // Restore original precision.\n      os->precision(old_precision);\n    }\n\n   private:\n    bool HasMaxAbsError() const { return max_abs_error_ >= 0; }\n\n    const FloatType expected_;\n    const bool nan_eq_nan_;\n    // max_abs_error will be used for value comparison when >= 0.\n    const FloatType max_abs_error_;\n  };\n\n  // The following 3 type conversion operators allow FloatEq(expected) and\n  // NanSensitiveFloatEq(expected) to be used as a Matcher<float>, a\n  // Matcher<const float&>, or a Matcher<float&>, but nothing else.\n  operator Matcher<FloatType>() const {\n    return MakeMatcher(\n        new Impl<FloatType>(expected_, nan_eq_nan_, max_abs_error_));\n  }\n\n  operator Matcher<const FloatType&>() const {\n    return MakeMatcher(\n        new Impl<const FloatType&>(expected_, nan_eq_nan_, max_abs_error_));\n  }\n\n  operator Matcher<FloatType&>() const {\n    return MakeMatcher(\n        new Impl<FloatType&>(expected_, nan_eq_nan_, max_abs_error_));\n  }\n\n private:\n  const FloatType expected_;\n  const bool nan_eq_nan_;\n  // max_abs_error will be used for value comparison when >= 0.\n  const FloatType max_abs_error_;\n};\n\n// A 2-tuple (\"binary\") wrapper around FloatingEqMatcher:\n// FloatingEq2Matcher() matches (x, y) by matching FloatingEqMatcher(x, false)\n// against y, and FloatingEq2Matcher(e) matches FloatingEqMatcher(x, false, e)\n// against y. The former implements \"Eq\", the latter \"Near\". At present, there\n// is no version that compares NaNs as equal.\ntemplate <typename FloatType>\nclass FloatingEq2Matcher {\n public:\n  FloatingEq2Matcher() { Init(-1, false); }\n\n  explicit FloatingEq2Matcher(bool nan_eq_nan) { Init(-1, nan_eq_nan); }\n\n  explicit FloatingEq2Matcher(FloatType max_abs_error) {\n    Init(max_abs_error, false);\n  }\n\n  FloatingEq2Matcher(FloatType max_abs_error, bool nan_eq_nan) {\n    Init(max_abs_error, nan_eq_nan);\n  }\n\n  template <typename T1, typename T2>\n  operator Matcher<::std::tuple<T1, T2>>() const {\n    return MakeMatcher(\n        new Impl<::std::tuple<T1, T2>>(max_abs_error_, nan_eq_nan_));\n  }\n  template <typename T1, typename T2>\n  operator Matcher<const ::std::tuple<T1, T2>&>() const {\n    return MakeMatcher(\n        new Impl<const ::std::tuple<T1, T2>&>(max_abs_error_, nan_eq_nan_));\n  }\n\n private:\n  static ::std::ostream& GetDesc(::std::ostream& os) {  // NOLINT\n    return os << \"an almost-equal pair\";\n  }\n\n  template <typename Tuple>\n  class Impl : public MatcherInterface<Tuple> {\n   public:\n    Impl(FloatType max_abs_error, bool nan_eq_nan)\n        : max_abs_error_(max_abs_error), nan_eq_nan_(nan_eq_nan) {}\n\n    bool MatchAndExplain(Tuple args,\n                         MatchResultListener* listener) const override {\n      if (max_abs_error_ == -1) {\n        FloatingEqMatcher<FloatType> fm(::std::get<0>(args), nan_eq_nan_);\n        return static_cast<Matcher<FloatType>>(fm).MatchAndExplain(\n            ::std::get<1>(args), listener);\n      } else {\n        FloatingEqMatcher<FloatType> fm(::std::get<0>(args), nan_eq_nan_,\n                                        max_abs_error_);\n        return static_cast<Matcher<FloatType>>(fm).MatchAndExplain(\n            ::std::get<1>(args), listener);\n      }\n    }\n    void DescribeTo(::std::ostream* os) const override {\n      *os << \"are \" << GetDesc;\n    }\n    void DescribeNegationTo(::std::ostream* os) const override {\n      *os << \"aren't \" << GetDesc;\n    }\n\n   private:\n    FloatType max_abs_error_;\n    const bool nan_eq_nan_;\n  };\n\n  void Init(FloatType max_abs_error_val, bool nan_eq_nan_val) {\n    max_abs_error_ = max_abs_error_val;\n    nan_eq_nan_ = nan_eq_nan_val;\n  }\n  FloatType max_abs_error_;\n  bool nan_eq_nan_;\n};\n\n// Implements the Pointee(m) matcher for matching a pointer whose\n// pointee matches matcher m.  The pointer can be either raw or smart.\ntemplate <typename InnerMatcher>\nclass PointeeMatcher {\n public:\n  explicit PointeeMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}\n\n  // This type conversion operator template allows Pointee(m) to be\n  // used as a matcher for any pointer type whose pointee type is\n  // compatible with the inner matcher, where type Pointer can be\n  // either a raw pointer or a smart pointer.\n  //\n  // The reason we do this instead of relying on\n  // MakePolymorphicMatcher() is that the latter is not flexible\n  // enough for implementing the DescribeTo() method of Pointee().\n  template <typename Pointer>\n  operator Matcher<Pointer>() const {\n    return Matcher<Pointer>(new Impl<const Pointer&>(matcher_));\n  }\n\n private:\n  // The monomorphic implementation that works for a particular pointer type.\n  template <typename Pointer>\n  class Impl : public MatcherInterface<Pointer> {\n   public:\n    using Pointee =\n        typename std::pointer_traits<GTEST_REMOVE_REFERENCE_AND_CONST_(\n            Pointer)>::element_type;\n\n    explicit Impl(const InnerMatcher& matcher)\n        : matcher_(MatcherCast<const Pointee&>(matcher)) {}\n\n    void DescribeTo(::std::ostream* os) const override {\n      *os << \"points to a value that \";\n      matcher_.DescribeTo(os);\n    }\n\n    void DescribeNegationTo(::std::ostream* os) const override {\n      *os << \"does not point to a value that \";\n      matcher_.DescribeTo(os);\n    }\n\n    bool MatchAndExplain(Pointer pointer,\n                         MatchResultListener* listener) const override {\n      if (GetRawPointer(pointer) == nullptr) return false;\n\n      *listener << \"which points to \";\n      return MatchPrintAndExplain(*pointer, matcher_, listener);\n    }\n\n   private:\n    const Matcher<const Pointee&> matcher_;\n  };\n\n  const InnerMatcher matcher_;\n};\n\n// Implements the Pointer(m) matcher\n// Implements the Pointer(m) matcher for matching a pointer that matches matcher\n// m.  The pointer can be either raw or smart, and will match `m` against the\n// raw pointer.\ntemplate <typename InnerMatcher>\nclass PointerMatcher {\n public:\n  explicit PointerMatcher(const InnerMatcher& matcher) : matcher_(matcher) {}\n\n  // This type conversion operator template allows Pointer(m) to be\n  // used as a matcher for any pointer type whose pointer type is\n  // compatible with the inner matcher, where type PointerType can be\n  // either a raw pointer or a smart pointer.\n  //\n  // The reason we do this instead of relying on\n  // MakePolymorphicMatcher() is that the latter is not flexible\n  // enough for implementing the DescribeTo() method of Pointer().\n  template <typename PointerType>\n  operator Matcher<PointerType>() const {  // NOLINT\n    return Matcher<PointerType>(new Impl<const PointerType&>(matcher_));\n  }\n\n private:\n  // The monomorphic implementation that works for a particular pointer type.\n  template <typename PointerType>\n  class Impl : public MatcherInterface<PointerType> {\n   public:\n    using Pointer =\n        const typename std::pointer_traits<GTEST_REMOVE_REFERENCE_AND_CONST_(\n            PointerType)>::element_type*;\n\n    explicit Impl(const InnerMatcher& matcher)\n        : matcher_(MatcherCast<Pointer>(matcher)) {}\n\n    void DescribeTo(::std::ostream* os) const override {\n      *os << \"is a pointer that \";\n      matcher_.DescribeTo(os);\n    }\n\n    void DescribeNegationTo(::std::ostream* os) const override {\n      *os << \"is not a pointer that \";\n      matcher_.DescribeTo(os);\n    }\n\n    bool MatchAndExplain(PointerType pointer,\n                         MatchResultListener* listener) const override {\n      *listener << \"which is a pointer that \";\n      Pointer p = GetRawPointer(pointer);\n      return MatchPrintAndExplain(p, matcher_, listener);\n    }\n\n   private:\n    Matcher<Pointer> matcher_;\n  };\n\n  const InnerMatcher matcher_;\n};\n\n#if GTEST_HAS_RTTI\n// Implements the WhenDynamicCastTo<T>(m) matcher that matches a pointer or\n// reference that matches inner_matcher when dynamic_cast<T> is applied.\n// The result of dynamic_cast<To> is forwarded to the inner matcher.\n// If To is a pointer and the cast fails, the inner matcher will receive NULL.\n// If To is a reference and the cast fails, this matcher returns false\n// immediately.\ntemplate <typename To>\nclass WhenDynamicCastToMatcherBase {\n public:\n  explicit WhenDynamicCastToMatcherBase(const Matcher<To>& matcher)\n      : matcher_(matcher) {}\n\n  void DescribeTo(::std::ostream* os) const {\n    GetCastTypeDescription(os);\n    matcher_.DescribeTo(os);\n  }\n\n  void DescribeNegationTo(::std::ostream* os) const {\n    GetCastTypeDescription(os);\n    matcher_.DescribeNegationTo(os);\n  }\n\n protected:\n  const Matcher<To> matcher_;\n\n  static std::string GetToName() { return GetTypeName<To>(); }\n\n private:\n  static void GetCastTypeDescription(::std::ostream* os) {\n    *os << \"when dynamic_cast to \" << GetToName() << \", \";\n  }\n};\n\n// Primary template.\n// To is a pointer. Cast and forward the result.\ntemplate <typename To>\nclass WhenDynamicCastToMatcher : public WhenDynamicCastToMatcherBase<To> {\n public:\n  explicit WhenDynamicCastToMatcher(const Matcher<To>& matcher)\n      : WhenDynamicCastToMatcherBase<To>(matcher) {}\n\n  template <typename From>\n  bool MatchAndExplain(From from, MatchResultListener* listener) const {\n    To to = dynamic_cast<To>(from);\n    return MatchPrintAndExplain(to, this->matcher_, listener);\n  }\n};\n\n// Specialize for references.\n// In this case we return false if the dynamic_cast fails.\ntemplate <typename To>\nclass WhenDynamicCastToMatcher<To&> : public WhenDynamicCastToMatcherBase<To&> {\n public:\n  explicit WhenDynamicCastToMatcher(const Matcher<To&>& matcher)\n      : WhenDynamicCastToMatcherBase<To&>(matcher) {}\n\n  template <typename From>\n  bool MatchAndExplain(From& from, MatchResultListener* listener) const {\n    // We don't want an std::bad_cast here, so do the cast with pointers.\n    To* to = dynamic_cast<To*>(&from);\n    if (to == nullptr) {\n      *listener << \"which cannot be dynamic_cast to \" << this->GetToName();\n      return false;\n    }\n    return MatchPrintAndExplain(*to, this->matcher_, listener);\n  }\n};\n#endif  // GTEST_HAS_RTTI\n\n// Implements the Field() matcher for matching a field (i.e. member\n// variable) of an object.\ntemplate <typename Class, typename FieldType>\nclass FieldMatcher {\n public:\n  FieldMatcher(FieldType Class::*field,\n               const Matcher<const FieldType&>& matcher)\n      : field_(field), matcher_(matcher), whose_field_(\"whose given field \") {}\n\n  FieldMatcher(const std::string& field_name, FieldType Class::*field,\n               const Matcher<const FieldType&>& matcher)\n      : field_(field),\n        matcher_(matcher),\n        whose_field_(\"whose field `\" + field_name + \"` \") {}\n\n  void DescribeTo(::std::ostream* os) const {\n    *os << \"is an object \" << whose_field_;\n    matcher_.DescribeTo(os);\n  }\n\n  void DescribeNegationTo(::std::ostream* os) const {\n    *os << \"is an object \" << whose_field_;\n    matcher_.DescribeNegationTo(os);\n  }\n\n  template <typename T>\n  bool MatchAndExplain(const T& value, MatchResultListener* listener) const {\n    // FIXME: The dispatch on std::is_pointer was introduced as a workaround for\n    // a compiler bug, and can now be removed.\n    return MatchAndExplainImpl(\n        typename std::is_pointer<typename std::remove_const<T>::type>::type(),\n        value, listener);\n  }\n\n private:\n  bool MatchAndExplainImpl(std::false_type /* is_not_pointer */,\n                           const Class& obj,\n                           MatchResultListener* listener) const {\n    *listener << whose_field_ << \"is \";\n    return MatchPrintAndExplain(obj.*field_, matcher_, listener);\n  }\n\n  bool MatchAndExplainImpl(std::true_type /* is_pointer */, const Class* p,\n                           MatchResultListener* listener) const {\n    if (p == nullptr) return false;\n\n    *listener << \"which points to an object \";\n    // Since *p has a field, it must be a class/struct/union type and\n    // thus cannot be a pointer.  Therefore we pass false_type() as\n    // the first argument.\n    return MatchAndExplainImpl(std::false_type(), *p, listener);\n  }\n\n  const FieldType Class::*field_;\n  const Matcher<const FieldType&> matcher_;\n\n  // Contains either \"whose given field \" if the name of the field is unknown\n  // or \"whose field `name_of_field` \" if the name is known.\n  const std::string whose_field_;\n};\n\n// Implements the Property() matcher for matching a property\n// (i.e. return value of a getter method) of an object.\n//\n// Property is a const-qualified member function of Class returning\n// PropertyType.\ntemplate <typename Class, typename PropertyType, typename Property>\nclass PropertyMatcher {\n public:\n  typedef const PropertyType& RefToConstProperty;\n\n  PropertyMatcher(Property property, const Matcher<RefToConstProperty>& matcher)\n      : property_(property),\n        matcher_(matcher),\n        whose_property_(\"whose given property \") {}\n\n  PropertyMatcher(const std::string& property_name, Property property,\n                  const Matcher<RefToConstProperty>& matcher)\n      : property_(property),\n        matcher_(matcher),\n        whose_property_(\"whose property `\" + property_name + \"` \") {}\n\n  void DescribeTo(::std::ostream* os) const {\n    *os << \"is an object \" << whose_property_;\n    matcher_.DescribeTo(os);\n  }\n\n  void DescribeNegationTo(::std::ostream* os) const {\n    *os << \"is an object \" << whose_property_;\n    matcher_.DescribeNegationTo(os);\n  }\n\n  template <typename T>\n  bool MatchAndExplain(const T& value, MatchResultListener* listener) const {\n    return MatchAndExplainImpl(\n        typename std::is_pointer<typename std::remove_const<T>::type>::type(),\n        value, listener);\n  }\n\n private:\n  bool MatchAndExplainImpl(std::false_type /* is_not_pointer */,\n                           const Class& obj,\n                           MatchResultListener* listener) const {\n    *listener << whose_property_ << \"is \";\n    // Cannot pass the return value (for example, int) to MatchPrintAndExplain,\n    // which takes a non-const reference as argument.\n    RefToConstProperty result = (obj.*property_)();\n    return MatchPrintAndExplain(result, matcher_, listener);\n  }\n\n  bool MatchAndExplainImpl(std::true_type /* is_pointer */, const Class* p,\n                           MatchResultListener* listener) const {\n    if (p == nullptr) return false;\n\n    *listener << \"which points to an object \";\n    // Since *p has a property method, it must be a class/struct/union\n    // type and thus cannot be a pointer.  Therefore we pass\n    // false_type() as the first argument.\n    return MatchAndExplainImpl(std::false_type(), *p, listener);\n  }\n\n  Property property_;\n  const Matcher<RefToConstProperty> matcher_;\n\n  // Contains either \"whose given property \" if the name of the property is\n  // unknown or \"whose property `name_of_property` \" if the name is known.\n  const std::string whose_property_;\n};\n\n// Type traits specifying various features of different functors for ResultOf.\n// The default template specifies features for functor objects.\ntemplate <typename Functor>\nstruct CallableTraits {\n  typedef Functor StorageType;\n\n  static void CheckIsValid(Functor /* functor */) {}\n\n  template <typename T>\n  static auto Invoke(Functor f, const T& arg) -> decltype(f(arg)) {\n    return f(arg);\n  }\n};\n\n// Specialization for function pointers.\ntemplate <typename ArgType, typename ResType>\nstruct CallableTraits<ResType (*)(ArgType)> {\n  typedef ResType ResultType;\n  typedef ResType (*StorageType)(ArgType);\n\n  static void CheckIsValid(ResType (*f)(ArgType)) {\n    GTEST_CHECK_(f != nullptr)\n        << \"NULL function pointer is passed into ResultOf().\";\n  }\n  template <typename T>\n  static ResType Invoke(ResType (*f)(ArgType), T arg) {\n    return (*f)(arg);\n  }\n};\n\n// Implements the ResultOf() matcher for matching a return value of a\n// unary function of an object.\ntemplate <typename Callable, typename InnerMatcher>\nclass ResultOfMatcher {\n public:\n  ResultOfMatcher(Callable callable, InnerMatcher matcher)\n      : ResultOfMatcher(/*result_description=*/\"\", std::move(callable),\n                        std::move(matcher)) {}\n\n  ResultOfMatcher(const std::string& result_description, Callable callable,\n                  InnerMatcher matcher)\n      : result_description_(result_description),\n        callable_(std::move(callable)),\n        matcher_(std::move(matcher)) {\n    CallableTraits<Callable>::CheckIsValid(callable_);\n  }\n\n  template <typename T>\n  operator Matcher<T>() const {\n    return Matcher<T>(\n        new Impl<const T&>(result_description_, callable_, matcher_));\n  }\n\n private:\n  typedef typename CallableTraits<Callable>::StorageType CallableStorageType;\n\n  template <typename T>\n  class Impl : public MatcherInterface<T> {\n    using ResultType = decltype(CallableTraits<Callable>::template Invoke<T>(\n        std::declval<CallableStorageType>(), std::declval<T>()));\n\n   public:\n    template <typename M>\n    Impl(const std::string& result_description,\n         const CallableStorageType& callable, const M& matcher)\n        : result_description_(result_description),\n          callable_(callable),\n          matcher_(MatcherCast<ResultType>(matcher)) {}\n\n    void DescribeTo(::std::ostream* os) const override {\n      if (result_description_.empty()) {\n        *os << \"is mapped by the given callable to a value that \";\n      } else {\n        *os << \"whose \" << result_description_ << \" \";\n      }\n      matcher_.DescribeTo(os);\n    }\n\n    void DescribeNegationTo(::std::ostream* os) const override {\n      if (result_description_.empty()) {\n        *os << \"is mapped by the given callable to a value that \";\n      } else {\n        *os << \"whose \" << result_description_ << \" \";\n      }\n      matcher_.DescribeNegationTo(os);\n    }\n\n    bool MatchAndExplain(T obj, MatchResultListener* listener) const override {\n      if (result_description_.empty()) {\n        *listener << \"which is mapped by the given callable to \";\n      } else {\n        *listener << \"whose \" << result_description_ << \" is \";\n      }\n      // Cannot pass the return value directly to MatchPrintAndExplain, which\n      // takes a non-const reference as argument.\n      // Also, specifying template argument explicitly is needed because T could\n      // be a non-const reference (e.g. Matcher<Uncopyable&>).\n      ResultType result =\n          CallableTraits<Callable>::template Invoke<T>(callable_, obj);\n      return MatchPrintAndExplain(result, matcher_, listener);\n    }\n\n   private:\n    const std::string result_description_;\n    // Functors often define operator() as non-const method even though\n    // they are actually stateless. But we need to use them even when\n    // 'this' is a const pointer. It's the user's responsibility not to\n    // use stateful callables with ResultOf(), which doesn't guarantee\n    // how many times the callable will be invoked.\n    mutable CallableStorageType callable_;\n    const Matcher<ResultType> matcher_;\n  };  // class Impl\n\n  const std::string result_description_;\n  const CallableStorageType callable_;\n  const InnerMatcher matcher_;\n};\n\n// Implements a matcher that checks the size of an STL-style container.\ntemplate <typename SizeMatcher>\nclass SizeIsMatcher {\n public:\n  explicit SizeIsMatcher(const SizeMatcher& size_matcher)\n      : size_matcher_(size_matcher) {}\n\n  template <typename Container>\n  operator Matcher<Container>() const {\n    return Matcher<Container>(new Impl<const Container&>(size_matcher_));\n  }\n\n  template <typename Container>\n  class Impl : public MatcherInterface<Container> {\n   public:\n    using SizeType = decltype(std::declval<Container>().size());\n    explicit Impl(const SizeMatcher& size_matcher)\n        : size_matcher_(MatcherCast<SizeType>(size_matcher)) {}\n\n    void DescribeTo(::std::ostream* os) const override {\n      *os << \"size \";\n      size_matcher_.DescribeTo(os);\n    }\n    void DescribeNegationTo(::std::ostream* os) const override {\n      *os << \"size \";\n      size_matcher_.DescribeNegationTo(os);\n    }\n\n    bool MatchAndExplain(Container container,\n                         MatchResultListener* listener) const override {\n      SizeType size = container.size();\n      StringMatchResultListener size_listener;\n      const bool result = size_matcher_.MatchAndExplain(size, &size_listener);\n      *listener << \"whose size \" << size\n                << (result ? \" matches\" : \" doesn't match\");\n      PrintIfNotEmpty(size_listener.str(), listener->stream());\n      return result;\n    }\n\n   private:\n    const Matcher<SizeType> size_matcher_;\n  };\n\n private:\n  const SizeMatcher size_matcher_;\n};\n\n// Implements a matcher that checks the begin()..end() distance of an STL-style\n// container.\ntemplate <typename DistanceMatcher>\nclass BeginEndDistanceIsMatcher {\n public:\n  explicit BeginEndDistanceIsMatcher(const DistanceMatcher& distance_matcher)\n      : distance_matcher_(distance_matcher) {}\n\n  template <typename Container>\n  operator Matcher<Container>() const {\n    return Matcher<Container>(new Impl<const Container&>(distance_matcher_));\n  }\n\n  template <typename Container>\n  class Impl : public MatcherInterface<Container> {\n   public:\n    typedef internal::StlContainerView<GTEST_REMOVE_REFERENCE_AND_CONST_(\n        Container)>\n        ContainerView;\n    typedef typename std::iterator_traits<\n        typename ContainerView::type::const_iterator>::difference_type\n        DistanceType;\n    explicit Impl(const DistanceMatcher& distance_matcher)\n        : distance_matcher_(MatcherCast<DistanceType>(distance_matcher)) {}\n\n    void DescribeTo(::std::ostream* os) const override {\n      *os << \"distance between begin() and end() \";\n      distance_matcher_.DescribeTo(os);\n    }\n    void DescribeNegationTo(::std::ostream* os) const override {\n      *os << \"distance between begin() and end() \";\n      distance_matcher_.DescribeNegationTo(os);\n    }\n\n    bool MatchAndExplain(Container container,\n                         MatchResultListener* listener) const override {\n      using std::begin;\n      using std::end;\n      DistanceType distance = std::distance(begin(container), end(container));\n      StringMatchResultListener distance_listener;\n      const bool result =\n          distance_matcher_.MatchAndExplain(distance, &distance_listener);\n      *listener << \"whose distance between begin() and end() \" << distance\n                << (result ? \" matches\" : \" doesn't match\");\n      PrintIfNotEmpty(distance_listener.str(), listener->stream());\n      return result;\n    }\n\n   private:\n    const Matcher<DistanceType> distance_matcher_;\n  };\n\n private:\n  const DistanceMatcher distance_matcher_;\n};\n\n// Implements an equality matcher for any STL-style container whose elements\n// support ==. This matcher is like Eq(), but its failure explanations provide\n// more detailed information that is useful when the container is used as a set.\n// The failure message reports elements that are in one of the operands but not\n// the other. The failure messages do not report duplicate or out-of-order\n// elements in the containers (which don't properly matter to sets, but can\n// occur if the containers are vectors or lists, for example).\n//\n// Uses the container's const_iterator, value_type, operator ==,\n// begin(), and end().\ntemplate <typename Container>\nclass ContainerEqMatcher {\n public:\n  typedef internal::StlContainerView<Container> View;\n  typedef typename View::type StlContainer;\n  typedef typename View::const_reference StlContainerReference;\n\n  static_assert(!std::is_const<Container>::value,\n                \"Container type must not be const\");\n  static_assert(!std::is_reference<Container>::value,\n                \"Container type must not be a reference\");\n\n  // We make a copy of expected in case the elements in it are modified\n  // after this matcher is created.\n  explicit ContainerEqMatcher(const Container& expected)\n      : expected_(View::Copy(expected)) {}\n\n  void DescribeTo(::std::ostream* os) const {\n    *os << \"equals \";\n    UniversalPrint(expected_, os);\n  }\n  void DescribeNegationTo(::std::ostream* os) const {\n    *os << \"does not equal \";\n    UniversalPrint(expected_, os);\n  }\n\n  template <typename LhsContainer>\n  bool MatchAndExplain(const LhsContainer& lhs,\n                       MatchResultListener* listener) const {\n    typedef internal::StlContainerView<\n        typename std::remove_const<LhsContainer>::type>\n        LhsView;\n    StlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);\n    if (lhs_stl_container == expected_) return true;\n\n    ::std::ostream* const os = listener->stream();\n    if (os != nullptr) {\n      // Something is different. Check for extra values first.\n      bool printed_header = false;\n      for (auto it = lhs_stl_container.begin(); it != lhs_stl_container.end();\n           ++it) {\n        if (internal::ArrayAwareFind(expected_.begin(), expected_.end(), *it) ==\n            expected_.end()) {\n          if (printed_header) {\n            *os << \", \";\n          } else {\n            *os << \"which has these unexpected elements: \";\n            printed_header = true;\n          }\n          UniversalPrint(*it, os);\n        }\n      }\n\n      // Now check for missing values.\n      bool printed_header2 = false;\n      for (auto it = expected_.begin(); it != expected_.end(); ++it) {\n        if (internal::ArrayAwareFind(lhs_stl_container.begin(),\n                                     lhs_stl_container.end(),\n                                     *it) == lhs_stl_container.end()) {\n          if (printed_header2) {\n            *os << \", \";\n          } else {\n            *os << (printed_header ? \",\\nand\" : \"which\")\n                << \" doesn't have these expected elements: \";\n            printed_header2 = true;\n          }\n          UniversalPrint(*it, os);\n        }\n      }\n    }\n\n    return false;\n  }\n\n private:\n  const StlContainer expected_;\n};\n\n// A comparator functor that uses the < operator to compare two values.\nstruct LessComparator {\n  template <typename T, typename U>\n  bool operator()(const T& lhs, const U& rhs) const {\n    return lhs < rhs;\n  }\n};\n\n// Implements WhenSortedBy(comparator, container_matcher).\ntemplate <typename Comparator, typename ContainerMatcher>\nclass WhenSortedByMatcher {\n public:\n  WhenSortedByMatcher(const Comparator& comparator,\n                      const ContainerMatcher& matcher)\n      : comparator_(comparator), matcher_(matcher) {}\n\n  template <typename LhsContainer>\n  operator Matcher<LhsContainer>() const {\n    return MakeMatcher(new Impl<LhsContainer>(comparator_, matcher_));\n  }\n\n  template <typename LhsContainer>\n  class Impl : public MatcherInterface<LhsContainer> {\n   public:\n    typedef internal::StlContainerView<GTEST_REMOVE_REFERENCE_AND_CONST_(\n        LhsContainer)>\n        LhsView;\n    typedef typename LhsView::type LhsStlContainer;\n    typedef typename LhsView::const_reference LhsStlContainerReference;\n    // Transforms std::pair<const Key, Value> into std::pair<Key, Value>\n    // so that we can match associative containers.\n    typedef\n        typename RemoveConstFromKey<typename LhsStlContainer::value_type>::type\n            LhsValue;\n\n    Impl(const Comparator& comparator, const ContainerMatcher& matcher)\n        : comparator_(comparator), matcher_(matcher) {}\n\n    void DescribeTo(::std::ostream* os) const override {\n      *os << \"(when sorted) \";\n      matcher_.DescribeTo(os);\n    }\n\n    void DescribeNegationTo(::std::ostream* os) const override {\n      *os << \"(when sorted) \";\n      matcher_.DescribeNegationTo(os);\n    }\n\n    bool MatchAndExplain(LhsContainer lhs,\n                         MatchResultListener* listener) const override {\n      LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);\n      ::std::vector<LhsValue> sorted_container(lhs_stl_container.begin(),\n                                               lhs_stl_container.end());\n      ::std::sort(sorted_container.begin(), sorted_container.end(),\n                  comparator_);\n\n      if (!listener->IsInterested()) {\n        // If the listener is not interested, we do not need to\n        // construct the inner explanation.\n        return matcher_.Matches(sorted_container);\n      }\n\n      *listener << \"which is \";\n      UniversalPrint(sorted_container, listener->stream());\n      *listener << \" when sorted\";\n\n      StringMatchResultListener inner_listener;\n      const bool match =\n          matcher_.MatchAndExplain(sorted_container, &inner_listener);\n      PrintIfNotEmpty(inner_listener.str(), listener->stream());\n      return match;\n    }\n\n   private:\n    const Comparator comparator_;\n    const Matcher<const ::std::vector<LhsValue>&> matcher_;\n\n    Impl(const Impl&) = delete;\n    Impl& operator=(const Impl&) = delete;\n  };\n\n private:\n  const Comparator comparator_;\n  const ContainerMatcher matcher_;\n};\n\n// Implements Pointwise(tuple_matcher, rhs_container).  tuple_matcher\n// must be able to be safely cast to Matcher<std::tuple<const T1&, const\n// T2&> >, where T1 and T2 are the types of elements in the LHS\n// container and the RHS container respectively.\ntemplate <typename TupleMatcher, typename RhsContainer>\nclass PointwiseMatcher {\n  static_assert(\n      !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(RhsContainer)>::value,\n      \"use UnorderedPointwise with hash tables\");\n\n public:\n  typedef internal::StlContainerView<RhsContainer> RhsView;\n  typedef typename RhsView::type RhsStlContainer;\n  typedef typename RhsStlContainer::value_type RhsValue;\n\n  static_assert(!std::is_const<RhsContainer>::value,\n                \"RhsContainer type must not be const\");\n  static_assert(!std::is_reference<RhsContainer>::value,\n                \"RhsContainer type must not be a reference\");\n\n  // Like ContainerEq, we make a copy of rhs in case the elements in\n  // it are modified after this matcher is created.\n  PointwiseMatcher(const TupleMatcher& tuple_matcher, const RhsContainer& rhs)\n      : tuple_matcher_(tuple_matcher), rhs_(RhsView::Copy(rhs)) {}\n\n  template <typename LhsContainer>\n  operator Matcher<LhsContainer>() const {\n    static_assert(\n        !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(LhsContainer)>::value,\n        \"use UnorderedPointwise with hash tables\");\n\n    return Matcher<LhsContainer>(\n        new Impl<const LhsContainer&>(tuple_matcher_, rhs_));\n  }\n\n  template <typename LhsContainer>\n  class Impl : public MatcherInterface<LhsContainer> {\n   public:\n    typedef internal::StlContainerView<GTEST_REMOVE_REFERENCE_AND_CONST_(\n        LhsContainer)>\n        LhsView;\n    typedef typename LhsView::type LhsStlContainer;\n    typedef typename LhsView::const_reference LhsStlContainerReference;\n    typedef typename LhsStlContainer::value_type LhsValue;\n    // We pass the LHS value and the RHS value to the inner matcher by\n    // reference, as they may be expensive to copy.  We must use tuple\n    // instead of pair here, as a pair cannot hold references (C++ 98,\n    // 20.2.2 [lib.pairs]).\n    typedef ::std::tuple<const LhsValue&, const RhsValue&> InnerMatcherArg;\n\n    Impl(const TupleMatcher& tuple_matcher, const RhsStlContainer& rhs)\n        // mono_tuple_matcher_ holds a monomorphic version of the tuple matcher.\n        : mono_tuple_matcher_(SafeMatcherCast<InnerMatcherArg>(tuple_matcher)),\n          rhs_(rhs) {}\n\n    void DescribeTo(::std::ostream* os) const override {\n      *os << \"contains \" << rhs_.size()\n          << \" values, where each value and its corresponding value in \";\n      UniversalPrinter<RhsStlContainer>::Print(rhs_, os);\n      *os << \" \";\n      mono_tuple_matcher_.DescribeTo(os);\n    }\n    void DescribeNegationTo(::std::ostream* os) const override {\n      *os << \"doesn't contain exactly \" << rhs_.size()\n          << \" values, or contains a value x at some index i\"\n          << \" where x and the i-th value of \";\n      UniversalPrint(rhs_, os);\n      *os << \" \";\n      mono_tuple_matcher_.DescribeNegationTo(os);\n    }\n\n    bool MatchAndExplain(LhsContainer lhs,\n                         MatchResultListener* listener) const override {\n      LhsStlContainerReference lhs_stl_container = LhsView::ConstReference(lhs);\n      const size_t actual_size = lhs_stl_container.size();\n      if (actual_size != rhs_.size()) {\n        *listener << \"which contains \" << actual_size << \" values\";\n        return false;\n      }\n\n      auto left = lhs_stl_container.begin();\n      auto right = rhs_.begin();\n      for (size_t i = 0; i != actual_size; ++i, ++left, ++right) {\n        if (listener->IsInterested()) {\n          StringMatchResultListener inner_listener;\n          // Create InnerMatcherArg as a temporarily object to avoid it outlives\n          // *left and *right. Dereference or the conversion to `const T&` may\n          // return temp objects, e.g. for vector<bool>.\n          if (!mono_tuple_matcher_.MatchAndExplain(\n                  InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),\n                                  ImplicitCast_<const RhsValue&>(*right)),\n                  &inner_listener)) {\n            *listener << \"where the value pair (\";\n            UniversalPrint(*left, listener->stream());\n            *listener << \", \";\n            UniversalPrint(*right, listener->stream());\n            *listener << \") at index #\" << i << \" don't match\";\n            PrintIfNotEmpty(inner_listener.str(), listener->stream());\n            return false;\n          }\n        } else {\n          if (!mono_tuple_matcher_.Matches(\n                  InnerMatcherArg(ImplicitCast_<const LhsValue&>(*left),\n                                  ImplicitCast_<const RhsValue&>(*right))))\n            return false;\n        }\n      }\n\n      return true;\n    }\n\n   private:\n    const Matcher<InnerMatcherArg> mono_tuple_matcher_;\n    const RhsStlContainer rhs_;\n  };\n\n private:\n  const TupleMatcher tuple_matcher_;\n  const RhsStlContainer rhs_;\n};\n\n// Holds the logic common to ContainsMatcherImpl and EachMatcherImpl.\ntemplate <typename Container>\nclass QuantifierMatcherImpl : public MatcherInterface<Container> {\n public:\n  typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;\n  typedef StlContainerView<RawContainer> View;\n  typedef typename View::type StlContainer;\n  typedef typename View::const_reference StlContainerReference;\n  typedef typename StlContainer::value_type Element;\n\n  template <typename InnerMatcher>\n  explicit QuantifierMatcherImpl(InnerMatcher inner_matcher)\n      : inner_matcher_(\n            testing::SafeMatcherCast<const Element&>(inner_matcher)) {}\n\n  // Checks whether:\n  // * All elements in the container match, if all_elements_should_match.\n  // * Any element in the container matches, if !all_elements_should_match.\n  bool MatchAndExplainImpl(bool all_elements_should_match, Container container,\n                           MatchResultListener* listener) const {\n    StlContainerReference stl_container = View::ConstReference(container);\n    size_t i = 0;\n    for (auto it = stl_container.begin(); it != stl_container.end();\n         ++it, ++i) {\n      StringMatchResultListener inner_listener;\n      const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);\n\n      if (matches != all_elements_should_match) {\n        *listener << \"whose element #\" << i\n                  << (matches ? \" matches\" : \" doesn't match\");\n        PrintIfNotEmpty(inner_listener.str(), listener->stream());\n        return !all_elements_should_match;\n      }\n    }\n    return all_elements_should_match;\n  }\n\n  bool MatchAndExplainImpl(const Matcher<size_t>& count_matcher,\n                           Container container,\n                           MatchResultListener* listener) const {\n    StlContainerReference stl_container = View::ConstReference(container);\n    size_t i = 0;\n    std::vector<size_t> match_elements;\n    for (auto it = stl_container.begin(); it != stl_container.end();\n         ++it, ++i) {\n      StringMatchResultListener inner_listener;\n      const bool matches = inner_matcher_.MatchAndExplain(*it, &inner_listener);\n      if (matches) {\n        match_elements.push_back(i);\n      }\n    }\n    if (listener->IsInterested()) {\n      if (match_elements.empty()) {\n        *listener << \"has no element that matches\";\n      } else if (match_elements.size() == 1) {\n        *listener << \"whose element #\" << match_elements[0] << \" matches\";\n      } else {\n        *listener << \"whose elements (\";\n        std::string sep = \"\";\n        for (size_t e : match_elements) {\n          *listener << sep << e;\n          sep = \", \";\n        }\n        *listener << \") match\";\n      }\n    }\n    StringMatchResultListener count_listener;\n    if (count_matcher.MatchAndExplain(match_elements.size(), &count_listener)) {\n      *listener << \" and whose match quantity of \" << match_elements.size()\n                << \" matches\";\n      PrintIfNotEmpty(count_listener.str(), listener->stream());\n      return true;\n    } else {\n      if (match_elements.empty()) {\n        *listener << \" and\";\n      } else {\n        *listener << \" but\";\n      }\n      *listener << \" whose match quantity of \" << match_elements.size()\n                << \" does not match\";\n      PrintIfNotEmpty(count_listener.str(), listener->stream());\n      return false;\n    }\n  }\n\n protected:\n  const Matcher<const Element&> inner_matcher_;\n};\n\n// Implements Contains(element_matcher) for the given argument type Container.\n// Symmetric to EachMatcherImpl.\ntemplate <typename Container>\nclass ContainsMatcherImpl : public QuantifierMatcherImpl<Container> {\n public:\n  template <typename InnerMatcher>\n  explicit ContainsMatcherImpl(InnerMatcher inner_matcher)\n      : QuantifierMatcherImpl<Container>(inner_matcher) {}\n\n  // Describes what this matcher does.\n  void DescribeTo(::std::ostream* os) const override {\n    *os << \"contains at least one element that \";\n    this->inner_matcher_.DescribeTo(os);\n  }\n\n  void DescribeNegationTo(::std::ostream* os) const override {\n    *os << \"doesn't contain any element that \";\n    this->inner_matcher_.DescribeTo(os);\n  }\n\n  bool MatchAndExplain(Container container,\n                       MatchResultListener* listener) const override {\n    return this->MatchAndExplainImpl(false, container, listener);\n  }\n};\n\n// Implements Each(element_matcher) for the given argument type Container.\n// Symmetric to ContainsMatcherImpl.\ntemplate <typename Container>\nclass EachMatcherImpl : public QuantifierMatcherImpl<Container> {\n public:\n  template <typename InnerMatcher>\n  explicit EachMatcherImpl(InnerMatcher inner_matcher)\n      : QuantifierMatcherImpl<Container>(inner_matcher) {}\n\n  // Describes what this matcher does.\n  void DescribeTo(::std::ostream* os) const override {\n    *os << \"only contains elements that \";\n    this->inner_matcher_.DescribeTo(os);\n  }\n\n  void DescribeNegationTo(::std::ostream* os) const override {\n    *os << \"contains some element that \";\n    this->inner_matcher_.DescribeNegationTo(os);\n  }\n\n  bool MatchAndExplain(Container container,\n                       MatchResultListener* listener) const override {\n    return this->MatchAndExplainImpl(true, container, listener);\n  }\n};\n\n// Implements Contains(element_matcher).Times(n) for the given argument type\n// Container.\ntemplate <typename Container>\nclass ContainsTimesMatcherImpl : public QuantifierMatcherImpl<Container> {\n public:\n  template <typename InnerMatcher>\n  explicit ContainsTimesMatcherImpl(InnerMatcher inner_matcher,\n                                    Matcher<size_t> count_matcher)\n      : QuantifierMatcherImpl<Container>(inner_matcher),\n        count_matcher_(std::move(count_matcher)) {}\n\n  void DescribeTo(::std::ostream* os) const override {\n    *os << \"quantity of elements that match \";\n    this->inner_matcher_.DescribeTo(os);\n    *os << \" \";\n    count_matcher_.DescribeTo(os);\n  }\n\n  void DescribeNegationTo(::std::ostream* os) const override {\n    *os << \"quantity of elements that match \";\n    this->inner_matcher_.DescribeTo(os);\n    *os << \" \";\n    count_matcher_.DescribeNegationTo(os);\n  }\n\n  bool MatchAndExplain(Container container,\n                       MatchResultListener* listener) const override {\n    return this->MatchAndExplainImpl(count_matcher_, container, listener);\n  }\n\n private:\n  const Matcher<size_t> count_matcher_;\n};\n\n// Implements polymorphic Contains(element_matcher).Times(n).\ntemplate <typename M>\nclass ContainsTimesMatcher {\n public:\n  explicit ContainsTimesMatcher(M m, Matcher<size_t> count_matcher)\n      : inner_matcher_(m), count_matcher_(std::move(count_matcher)) {}\n\n  template <typename Container>\n  operator Matcher<Container>() const {  // NOLINT\n    return Matcher<Container>(new ContainsTimesMatcherImpl<const Container&>(\n        inner_matcher_, count_matcher_));\n  }\n\n private:\n  const M inner_matcher_;\n  const Matcher<size_t> count_matcher_;\n};\n\n// Implements polymorphic Contains(element_matcher).\ntemplate <typename M>\nclass ContainsMatcher {\n public:\n  explicit ContainsMatcher(M m) : inner_matcher_(m) {}\n\n  template <typename Container>\n  operator Matcher<Container>() const {  // NOLINT\n    return Matcher<Container>(\n        new ContainsMatcherImpl<const Container&>(inner_matcher_));\n  }\n\n  ContainsTimesMatcher<M> Times(Matcher<size_t> count_matcher) const {\n    return ContainsTimesMatcher<M>(inner_matcher_, std::move(count_matcher));\n  }\n\n private:\n  const M inner_matcher_;\n};\n\n// Implements polymorphic Each(element_matcher).\ntemplate <typename M>\nclass EachMatcher {\n public:\n  explicit EachMatcher(M m) : inner_matcher_(m) {}\n\n  template <typename Container>\n  operator Matcher<Container>() const {  // NOLINT\n    return Matcher<Container>(\n        new EachMatcherImpl<const Container&>(inner_matcher_));\n  }\n\n private:\n  const M inner_matcher_;\n};\n\nstruct Rank1 {};\nstruct Rank0 : Rank1 {};\n\nnamespace pair_getters {\nusing std::get;\ntemplate <typename T>\nauto First(T& x, Rank1) -> decltype(get<0>(x)) {  // NOLINT\n  return get<0>(x);\n}\ntemplate <typename T>\nauto First(T& x, Rank0) -> decltype((x.first)) {  // NOLINT\n  return x.first;\n}\n\ntemplate <typename T>\nauto Second(T& x, Rank1) -> decltype(get<1>(x)) {  // NOLINT\n  return get<1>(x);\n}\ntemplate <typename T>\nauto Second(T& x, Rank0) -> decltype((x.second)) {  // NOLINT\n  return x.second;\n}\n}  // namespace pair_getters\n\n// Implements Key(inner_matcher) for the given argument pair type.\n// Key(inner_matcher) matches an std::pair whose 'first' field matches\n// inner_matcher.  For example, Contains(Key(Ge(5))) can be used to match an\n// std::map that contains at least one element whose key is >= 5.\ntemplate <typename PairType>\nclass KeyMatcherImpl : public MatcherInterface<PairType> {\n public:\n  typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;\n  typedef typename RawPairType::first_type KeyType;\n\n  template <typename InnerMatcher>\n  explicit KeyMatcherImpl(InnerMatcher inner_matcher)\n      : inner_matcher_(\n            testing::SafeMatcherCast<const KeyType&>(inner_matcher)) {}\n\n  // Returns true if and only if 'key_value.first' (the key) matches the inner\n  // matcher.\n  bool MatchAndExplain(PairType key_value,\n                       MatchResultListener* listener) const override {\n    StringMatchResultListener inner_listener;\n    const bool match = inner_matcher_.MatchAndExplain(\n        pair_getters::First(key_value, Rank0()), &inner_listener);\n    const std::string explanation = inner_listener.str();\n    if (explanation != \"\") {\n      *listener << \"whose first field is a value \" << explanation;\n    }\n    return match;\n  }\n\n  // Describes what this matcher does.\n  void DescribeTo(::std::ostream* os) const override {\n    *os << \"has a key that \";\n    inner_matcher_.DescribeTo(os);\n  }\n\n  // Describes what the negation of this matcher does.\n  void DescribeNegationTo(::std::ostream* os) const override {\n    *os << \"doesn't have a key that \";\n    inner_matcher_.DescribeTo(os);\n  }\n\n private:\n  const Matcher<const KeyType&> inner_matcher_;\n};\n\n// Implements polymorphic Key(matcher_for_key).\ntemplate <typename M>\nclass KeyMatcher {\n public:\n  explicit KeyMatcher(M m) : matcher_for_key_(m) {}\n\n  template <typename PairType>\n  operator Matcher<PairType>() const {\n    return Matcher<PairType>(\n        new KeyMatcherImpl<const PairType&>(matcher_for_key_));\n  }\n\n private:\n  const M matcher_for_key_;\n};\n\n// Implements polymorphic Address(matcher_for_address).\ntemplate <typename InnerMatcher>\nclass AddressMatcher {\n public:\n  explicit AddressMatcher(InnerMatcher m) : matcher_(m) {}\n\n  template <typename Type>\n  operator Matcher<Type>() const {  // NOLINT\n    return Matcher<Type>(new Impl<const Type&>(matcher_));\n  }\n\n private:\n  // The monomorphic implementation that works for a particular object type.\n  template <typename Type>\n  class Impl : public MatcherInterface<Type> {\n   public:\n    using Address = const GTEST_REMOVE_REFERENCE_AND_CONST_(Type) *;\n    explicit Impl(const InnerMatcher& matcher)\n        : matcher_(MatcherCast<Address>(matcher)) {}\n\n    void DescribeTo(::std::ostream* os) const override {\n      *os << \"has address that \";\n      matcher_.DescribeTo(os);\n    }\n\n    void DescribeNegationTo(::std::ostream* os) const override {\n      *os << \"does not have address that \";\n      matcher_.DescribeTo(os);\n    }\n\n    bool MatchAndExplain(Type object,\n                         MatchResultListener* listener) const override {\n      *listener << \"which has address \";\n      Address address = std::addressof(object);\n      return MatchPrintAndExplain(address, matcher_, listener);\n    }\n\n   private:\n    const Matcher<Address> matcher_;\n  };\n  const InnerMatcher matcher_;\n};\n\n// Implements Pair(first_matcher, second_matcher) for the given argument pair\n// type with its two matchers. See Pair() function below.\ntemplate <typename PairType>\nclass PairMatcherImpl : public MatcherInterface<PairType> {\n public:\n  typedef GTEST_REMOVE_REFERENCE_AND_CONST_(PairType) RawPairType;\n  typedef typename RawPairType::first_type FirstType;\n  typedef typename RawPairType::second_type SecondType;\n\n  template <typename FirstMatcher, typename SecondMatcher>\n  PairMatcherImpl(FirstMatcher first_matcher, SecondMatcher second_matcher)\n      : first_matcher_(\n            testing::SafeMatcherCast<const FirstType&>(first_matcher)),\n        second_matcher_(\n            testing::SafeMatcherCast<const SecondType&>(second_matcher)) {}\n\n  // Describes what this matcher does.\n  void DescribeTo(::std::ostream* os) const override {\n    *os << \"has a first field that \";\n    first_matcher_.DescribeTo(os);\n    *os << \", and has a second field that \";\n    second_matcher_.DescribeTo(os);\n  }\n\n  // Describes what the negation of this matcher does.\n  void DescribeNegationTo(::std::ostream* os) const override {\n    *os << \"has a first field that \";\n    first_matcher_.DescribeNegationTo(os);\n    *os << \", or has a second field that \";\n    second_matcher_.DescribeNegationTo(os);\n  }\n\n  // Returns true if and only if 'a_pair.first' matches first_matcher and\n  // 'a_pair.second' matches second_matcher.\n  bool MatchAndExplain(PairType a_pair,\n                       MatchResultListener* listener) const override {\n    if (!listener->IsInterested()) {\n      // If the listener is not interested, we don't need to construct the\n      // explanation.\n      return first_matcher_.Matches(pair_getters::First(a_pair, Rank0())) &&\n             second_matcher_.Matches(pair_getters::Second(a_pair, Rank0()));\n    }\n    StringMatchResultListener first_inner_listener;\n    if (!first_matcher_.MatchAndExplain(pair_getters::First(a_pair, Rank0()),\n                                        &first_inner_listener)) {\n      *listener << \"whose first field does not match\";\n      PrintIfNotEmpty(first_inner_listener.str(), listener->stream());\n      return false;\n    }\n    StringMatchResultListener second_inner_listener;\n    if (!second_matcher_.MatchAndExplain(pair_getters::Second(a_pair, Rank0()),\n                                         &second_inner_listener)) {\n      *listener << \"whose second field does not match\";\n      PrintIfNotEmpty(second_inner_listener.str(), listener->stream());\n      return false;\n    }\n    ExplainSuccess(first_inner_listener.str(), second_inner_listener.str(),\n                   listener);\n    return true;\n  }\n\n private:\n  void ExplainSuccess(const std::string& first_explanation,\n                      const std::string& second_explanation,\n                      MatchResultListener* listener) const {\n    *listener << \"whose both fields match\";\n    if (first_explanation != \"\") {\n      *listener << \", where the first field is a value \" << first_explanation;\n    }\n    if (second_explanation != \"\") {\n      *listener << \", \";\n      if (first_explanation != \"\") {\n        *listener << \"and \";\n      } else {\n        *listener << \"where \";\n      }\n      *listener << \"the second field is a value \" << second_explanation;\n    }\n  }\n\n  const Matcher<const FirstType&> first_matcher_;\n  const Matcher<const SecondType&> second_matcher_;\n};\n\n// Implements polymorphic Pair(first_matcher, second_matcher).\ntemplate <typename FirstMatcher, typename SecondMatcher>\nclass PairMatcher {\n public:\n  PairMatcher(FirstMatcher first_matcher, SecondMatcher second_matcher)\n      : first_matcher_(first_matcher), second_matcher_(second_matcher) {}\n\n  template <typename PairType>\n  operator Matcher<PairType>() const {\n    return Matcher<PairType>(\n        new PairMatcherImpl<const PairType&>(first_matcher_, second_matcher_));\n  }\n\n private:\n  const FirstMatcher first_matcher_;\n  const SecondMatcher second_matcher_;\n};\n\ntemplate <typename T, size_t... I>\nauto UnpackStructImpl(const T& t, IndexSequence<I...>, int)\n    -> decltype(std::tie(get<I>(t)...)) {\n  static_assert(std::tuple_size<T>::value == sizeof...(I),\n                \"Number of arguments doesn't match the number of fields.\");\n  return std::tie(get<I>(t)...);\n}\n\n#if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606\ntemplate <typename T>\nauto UnpackStructImpl(const T& t, MakeIndexSequence<1>, char) {\n  const auto& [a] = t;\n  return std::tie(a);\n}\ntemplate <typename T>\nauto UnpackStructImpl(const T& t, MakeIndexSequence<2>, char) {\n  const auto& [a, b] = t;\n  return std::tie(a, b);\n}\ntemplate <typename T>\nauto UnpackStructImpl(const T& t, MakeIndexSequence<3>, char) {\n  const auto& [a, b, c] = t;\n  return std::tie(a, b, c);\n}\ntemplate <typename T>\nauto UnpackStructImpl(const T& t, MakeIndexSequence<4>, char) {\n  const auto& [a, b, c, d] = t;\n  return std::tie(a, b, c, d);\n}\ntemplate <typename T>\nauto UnpackStructImpl(const T& t, MakeIndexSequence<5>, char) {\n  const auto& [a, b, c, d, e] = t;\n  return std::tie(a, b, c, d, e);\n}\ntemplate <typename T>\nauto UnpackStructImpl(const T& t, MakeIndexSequence<6>, char) {\n  const auto& [a, b, c, d, e, f] = t;\n  return std::tie(a, b, c, d, e, f);\n}\ntemplate <typename T>\nauto UnpackStructImpl(const T& t, MakeIndexSequence<7>, char) {\n  const auto& [a, b, c, d, e, f, g] = t;\n  return std::tie(a, b, c, d, e, f, g);\n}\ntemplate <typename T>\nauto UnpackStructImpl(const T& t, MakeIndexSequence<8>, char) {\n  const auto& [a, b, c, d, e, f, g, h] = t;\n  return std::tie(a, b, c, d, e, f, g, h);\n}\ntemplate <typename T>\nauto UnpackStructImpl(const T& t, MakeIndexSequence<9>, char) {\n  const auto& [a, b, c, d, e, f, g, h, i] = t;\n  return std::tie(a, b, c, d, e, f, g, h, i);\n}\ntemplate <typename T>\nauto UnpackStructImpl(const T& t, MakeIndexSequence<10>, char) {\n  const auto& [a, b, c, d, e, f, g, h, i, j] = t;\n  return std::tie(a, b, c, d, e, f, g, h, i, j);\n}\ntemplate <typename T>\nauto UnpackStructImpl(const T& t, MakeIndexSequence<11>, char) {\n  const auto& [a, b, c, d, e, f, g, h, i, j, k] = t;\n  return std::tie(a, b, c, d, e, f, g, h, i, j, k);\n}\ntemplate <typename T>\nauto UnpackStructImpl(const T& t, MakeIndexSequence<12>, char) {\n  const auto& [a, b, c, d, e, f, g, h, i, j, k, l] = t;\n  return std::tie(a, b, c, d, e, f, g, h, i, j, k, l);\n}\ntemplate <typename T>\nauto UnpackStructImpl(const T& t, MakeIndexSequence<13>, char) {\n  const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m] = t;\n  return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m);\n}\ntemplate <typename T>\nauto UnpackStructImpl(const T& t, MakeIndexSequence<14>, char) {\n  const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n] = t;\n  return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n);\n}\ntemplate <typename T>\nauto UnpackStructImpl(const T& t, MakeIndexSequence<15>, char) {\n  const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o] = t;\n  return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o);\n}\ntemplate <typename T>\nauto UnpackStructImpl(const T& t, MakeIndexSequence<16>, char) {\n  const auto& [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p] = t;\n  return std::tie(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p);\n}\n#endif  // defined(__cpp_structured_bindings)\n\ntemplate <size_t I, typename T>\nauto UnpackStruct(const T& t)\n    -> decltype((UnpackStructImpl)(t, MakeIndexSequence<I>{}, 0)) {\n  return (UnpackStructImpl)(t, MakeIndexSequence<I>{}, 0);\n}\n\n// Helper function to do comma folding in C++11.\n// The array ensures left-to-right order of evaluation.\n// Usage: VariadicExpand({expr...});\ntemplate <typename T, size_t N>\nvoid VariadicExpand(const T (&)[N]) {}\n\ntemplate <typename Struct, typename StructSize>\nclass FieldsAreMatcherImpl;\n\ntemplate <typename Struct, size_t... I>\nclass FieldsAreMatcherImpl<Struct, IndexSequence<I...>>\n    : public MatcherInterface<Struct> {\n  using UnpackedType =\n      decltype(UnpackStruct<sizeof...(I)>(std::declval<const Struct&>()));\n  using MatchersType = std::tuple<\n      Matcher<const typename std::tuple_element<I, UnpackedType>::type&>...>;\n\n public:\n  template <typename Inner>\n  explicit FieldsAreMatcherImpl(const Inner& matchers)\n      : matchers_(testing::SafeMatcherCast<\n                  const typename std::tuple_element<I, UnpackedType>::type&>(\n            std::get<I>(matchers))...) {}\n\n  void DescribeTo(::std::ostream* os) const override {\n    const char* separator = \"\";\n    VariadicExpand(\n        {(*os << separator << \"has field #\" << I << \" that \",\n          std::get<I>(matchers_).DescribeTo(os), separator = \", and \")...});\n  }\n\n  void DescribeNegationTo(::std::ostream* os) const override {\n    const char* separator = \"\";\n    VariadicExpand({(*os << separator << \"has field #\" << I << \" that \",\n                     std::get<I>(matchers_).DescribeNegationTo(os),\n                     separator = \", or \")...});\n  }\n\n  bool MatchAndExplain(Struct t, MatchResultListener* listener) const override {\n    return MatchInternal((UnpackStruct<sizeof...(I)>)(t), listener);\n  }\n\n private:\n  bool MatchInternal(UnpackedType tuple, MatchResultListener* listener) const {\n    if (!listener->IsInterested()) {\n      // If the listener is not interested, we don't need to construct the\n      // explanation.\n      bool good = true;\n      VariadicExpand({good = good && std::get<I>(matchers_).Matches(\n                                         std::get<I>(tuple))...});\n      return good;\n    }\n\n    size_t failed_pos = ~size_t{};\n\n    std::vector<StringMatchResultListener> inner_listener(sizeof...(I));\n\n    VariadicExpand(\n        {failed_pos == ~size_t{} && !std::get<I>(matchers_).MatchAndExplain(\n                                        std::get<I>(tuple), &inner_listener[I])\n             ? failed_pos = I\n             : 0 ...});\n    if (failed_pos != ~size_t{}) {\n      *listener << \"whose field #\" << failed_pos << \" does not match\";\n      PrintIfNotEmpty(inner_listener[failed_pos].str(), listener->stream());\n      return false;\n    }\n\n    *listener << \"whose all elements match\";\n    const char* separator = \", where\";\n    for (size_t index = 0; index < sizeof...(I); ++index) {\n      const std::string str = inner_listener[index].str();\n      if (!str.empty()) {\n        *listener << separator << \" field #\" << index << \" is a value \" << str;\n        separator = \", and\";\n      }\n    }\n\n    return true;\n  }\n\n  MatchersType matchers_;\n};\n\ntemplate <typename... Inner>\nclass FieldsAreMatcher {\n public:\n  explicit FieldsAreMatcher(Inner... inner) : matchers_(std::move(inner)...) {}\n\n  template <typename Struct>\n  operator Matcher<Struct>() const {  // NOLINT\n    return Matcher<Struct>(\n        new FieldsAreMatcherImpl<const Struct&, IndexSequenceFor<Inner...>>(\n            matchers_));\n  }\n\n private:\n  std::tuple<Inner...> matchers_;\n};\n\n// Implements ElementsAre() and ElementsAreArray().\ntemplate <typename Container>\nclass ElementsAreMatcherImpl : public MatcherInterface<Container> {\n public:\n  typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;\n  typedef internal::StlContainerView<RawContainer> View;\n  typedef typename View::type StlContainer;\n  typedef typename View::const_reference StlContainerReference;\n  typedef typename StlContainer::value_type Element;\n\n  // Constructs the matcher from a sequence of element values or\n  // element matchers.\n  template <typename InputIter>\n  ElementsAreMatcherImpl(InputIter first, InputIter last) {\n    while (first != last) {\n      matchers_.push_back(MatcherCast<const Element&>(*first++));\n    }\n  }\n\n  // Describes what this matcher does.\n  void DescribeTo(::std::ostream* os) const override {\n    if (count() == 0) {\n      *os << \"is empty\";\n    } else if (count() == 1) {\n      *os << \"has 1 element that \";\n      matchers_[0].DescribeTo(os);\n    } else {\n      *os << \"has \" << Elements(count()) << \" where\\n\";\n      for (size_t i = 0; i != count(); ++i) {\n        *os << \"element #\" << i << \" \";\n        matchers_[i].DescribeTo(os);\n        if (i + 1 < count()) {\n          *os << \",\\n\";\n        }\n      }\n    }\n  }\n\n  // Describes what the negation of this matcher does.\n  void DescribeNegationTo(::std::ostream* os) const override {\n    if (count() == 0) {\n      *os << \"isn't empty\";\n      return;\n    }\n\n    *os << \"doesn't have \" << Elements(count()) << \", or\\n\";\n    for (size_t i = 0; i != count(); ++i) {\n      *os << \"element #\" << i << \" \";\n      matchers_[i].DescribeNegationTo(os);\n      if (i + 1 < count()) {\n        *os << \", or\\n\";\n      }\n    }\n  }\n\n  bool MatchAndExplain(Container container,\n                       MatchResultListener* listener) const override {\n    // To work with stream-like \"containers\", we must only walk\n    // through the elements in one pass.\n\n    const bool listener_interested = listener->IsInterested();\n\n    // explanations[i] is the explanation of the element at index i.\n    ::std::vector<std::string> explanations(count());\n    StlContainerReference stl_container = View::ConstReference(container);\n    auto it = stl_container.begin();\n    size_t exam_pos = 0;\n    bool mismatch_found = false;  // Have we found a mismatched element yet?\n\n    // Go through the elements and matchers in pairs, until we reach\n    // the end of either the elements or the matchers, or until we find a\n    // mismatch.\n    for (; it != stl_container.end() && exam_pos != count(); ++it, ++exam_pos) {\n      bool match;  // Does the current element match the current matcher?\n      if (listener_interested) {\n        StringMatchResultListener s;\n        match = matchers_[exam_pos].MatchAndExplain(*it, &s);\n        explanations[exam_pos] = s.str();\n      } else {\n        match = matchers_[exam_pos].Matches(*it);\n      }\n\n      if (!match) {\n        mismatch_found = true;\n        break;\n      }\n    }\n    // If mismatch_found is true, 'exam_pos' is the index of the mismatch.\n\n    // Find how many elements the actual container has.  We avoid\n    // calling size() s.t. this code works for stream-like \"containers\"\n    // that don't define size().\n    size_t actual_count = exam_pos;\n    for (; it != stl_container.end(); ++it) {\n      ++actual_count;\n    }\n\n    if (actual_count != count()) {\n      // The element count doesn't match.  If the container is empty,\n      // there's no need to explain anything as Google Mock already\n      // prints the empty container.  Otherwise we just need to show\n      // how many elements there actually are.\n      if (listener_interested && (actual_count != 0)) {\n        *listener << \"which has \" << Elements(actual_count);\n      }\n      return false;\n    }\n\n    if (mismatch_found) {\n      // The element count matches, but the exam_pos-th element doesn't match.\n      if (listener_interested) {\n        *listener << \"whose element #\" << exam_pos << \" doesn't match\";\n        PrintIfNotEmpty(explanations[exam_pos], listener->stream());\n      }\n      return false;\n    }\n\n    // Every element matches its expectation.  We need to explain why\n    // (the obvious ones can be skipped).\n    if (listener_interested) {\n      bool reason_printed = false;\n      for (size_t i = 0; i != count(); ++i) {\n        const std::string& s = explanations[i];\n        if (!s.empty()) {\n          if (reason_printed) {\n            *listener << \",\\nand \";\n          }\n          *listener << \"whose element #\" << i << \" matches, \" << s;\n          reason_printed = true;\n        }\n      }\n    }\n    return true;\n  }\n\n private:\n  static Message Elements(size_t count) {\n    return Message() << count << (count == 1 ? \" element\" : \" elements\");\n  }\n\n  size_t count() const { return matchers_.size(); }\n\n  ::std::vector<Matcher<const Element&>> matchers_;\n};\n\n// Connectivity matrix of (elements X matchers), in element-major order.\n// Initially, there are no edges.\n// Use NextGraph() to iterate over all possible edge configurations.\n// Use Randomize() to generate a random edge configuration.\nclass GTEST_API_ MatchMatrix {\n public:\n  MatchMatrix(size_t num_elements, size_t num_matchers)\n      : num_elements_(num_elements),\n        num_matchers_(num_matchers),\n        matched_(num_elements_ * num_matchers_, 0) {}\n\n  size_t LhsSize() const { return num_elements_; }\n  size_t RhsSize() const { return num_matchers_; }\n  bool HasEdge(size_t ilhs, size_t irhs) const {\n    return matched_[SpaceIndex(ilhs, irhs)] == 1;\n  }\n  void SetEdge(size_t ilhs, size_t irhs, bool b) {\n    matched_[SpaceIndex(ilhs, irhs)] = b ? 1 : 0;\n  }\n\n  // Treating the connectivity matrix as a (LhsSize()*RhsSize())-bit number,\n  // adds 1 to that number; returns false if incrementing the graph left it\n  // empty.\n  bool NextGraph();\n\n  void Randomize();\n\n  std::string DebugString() const;\n\n private:\n  size_t SpaceIndex(size_t ilhs, size_t irhs) const {\n    return ilhs * num_matchers_ + irhs;\n  }\n\n  size_t num_elements_;\n  size_t num_matchers_;\n\n  // Each element is a char interpreted as bool. They are stored as a\n  // flattened array in lhs-major order, use 'SpaceIndex()' to translate\n  // a (ilhs, irhs) matrix coordinate into an offset.\n  ::std::vector<char> matched_;\n};\n\ntypedef ::std::pair<size_t, size_t> ElementMatcherPair;\ntypedef ::std::vector<ElementMatcherPair> ElementMatcherPairs;\n\n// Returns a maximum bipartite matching for the specified graph 'g'.\n// The matching is represented as a vector of {element, matcher} pairs.\nGTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g);\n\nstruct UnorderedMatcherRequire {\n  enum Flags {\n    Superset = 1 << 0,\n    Subset = 1 << 1,\n    ExactMatch = Superset | Subset,\n  };\n};\n\n// Untyped base class for implementing UnorderedElementsAre.  By\n// putting logic that's not specific to the element type here, we\n// reduce binary bloat and increase compilation speed.\nclass GTEST_API_ UnorderedElementsAreMatcherImplBase {\n protected:\n  explicit UnorderedElementsAreMatcherImplBase(\n      UnorderedMatcherRequire::Flags matcher_flags)\n      : match_flags_(matcher_flags) {}\n\n  // A vector of matcher describers, one for each element matcher.\n  // Does not own the describers (and thus can be used only when the\n  // element matchers are alive).\n  typedef ::std::vector<const MatcherDescriberInterface*> MatcherDescriberVec;\n\n  // Describes this UnorderedElementsAre matcher.\n  void DescribeToImpl(::std::ostream* os) const;\n\n  // Describes the negation of this UnorderedElementsAre matcher.\n  void DescribeNegationToImpl(::std::ostream* os) const;\n\n  bool VerifyMatchMatrix(const ::std::vector<std::string>& element_printouts,\n                         const MatchMatrix& matrix,\n                         MatchResultListener* listener) const;\n\n  bool FindPairing(const MatchMatrix& matrix,\n                   MatchResultListener* listener) const;\n\n  MatcherDescriberVec& matcher_describers() { return matcher_describers_; }\n\n  static Message Elements(size_t n) {\n    return Message() << n << \" element\" << (n == 1 ? \"\" : \"s\");\n  }\n\n  UnorderedMatcherRequire::Flags match_flags() const { return match_flags_; }\n\n private:\n  UnorderedMatcherRequire::Flags match_flags_;\n  MatcherDescriberVec matcher_describers_;\n};\n\n// Implements UnorderedElementsAre, UnorderedElementsAreArray, IsSubsetOf, and\n// IsSupersetOf.\ntemplate <typename Container>\nclass UnorderedElementsAreMatcherImpl\n    : public MatcherInterface<Container>,\n      public UnorderedElementsAreMatcherImplBase {\n public:\n  typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;\n  typedef internal::StlContainerView<RawContainer> View;\n  typedef typename View::type StlContainer;\n  typedef typename View::const_reference StlContainerReference;\n  typedef typename StlContainer::value_type Element;\n\n  template <typename InputIter>\n  UnorderedElementsAreMatcherImpl(UnorderedMatcherRequire::Flags matcher_flags,\n                                  InputIter first, InputIter last)\n      : UnorderedElementsAreMatcherImplBase(matcher_flags) {\n    for (; first != last; ++first) {\n      matchers_.push_back(MatcherCast<const Element&>(*first));\n    }\n    for (const auto& m : matchers_) {\n      matcher_describers().push_back(m.GetDescriber());\n    }\n  }\n\n  // Describes what this matcher does.\n  void DescribeTo(::std::ostream* os) const override {\n    return UnorderedElementsAreMatcherImplBase::DescribeToImpl(os);\n  }\n\n  // Describes what the negation of this matcher does.\n  void DescribeNegationTo(::std::ostream* os) const override {\n    return UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(os);\n  }\n\n  bool MatchAndExplain(Container container,\n                       MatchResultListener* listener) const override {\n    StlContainerReference stl_container = View::ConstReference(container);\n    ::std::vector<std::string> element_printouts;\n    MatchMatrix matrix =\n        AnalyzeElements(stl_container.begin(), stl_container.end(),\n                        &element_printouts, listener);\n\n    if (matrix.LhsSize() == 0 && matrix.RhsSize() == 0) {\n      return true;\n    }\n\n    if (match_flags() == UnorderedMatcherRequire::ExactMatch) {\n      if (matrix.LhsSize() != matrix.RhsSize()) {\n        // The element count doesn't match.  If the container is empty,\n        // there's no need to explain anything as Google Mock already\n        // prints the empty container. Otherwise we just need to show\n        // how many elements there actually are.\n        if (matrix.LhsSize() != 0 && listener->IsInterested()) {\n          *listener << \"which has \" << Elements(matrix.LhsSize());\n        }\n        return false;\n      }\n    }\n\n    return VerifyMatchMatrix(element_printouts, matrix, listener) &&\n           FindPairing(matrix, listener);\n  }\n\n private:\n  template <typename ElementIter>\n  MatchMatrix AnalyzeElements(ElementIter elem_first, ElementIter elem_last,\n                              ::std::vector<std::string>* element_printouts,\n                              MatchResultListener* listener) const {\n    element_printouts->clear();\n    ::std::vector<char> did_match;\n    size_t num_elements = 0;\n    DummyMatchResultListener dummy;\n    for (; elem_first != elem_last; ++num_elements, ++elem_first) {\n      if (listener->IsInterested()) {\n        element_printouts->push_back(PrintToString(*elem_first));\n      }\n      for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {\n        did_match.push_back(\n            matchers_[irhs].MatchAndExplain(*elem_first, &dummy));\n      }\n    }\n\n    MatchMatrix matrix(num_elements, matchers_.size());\n    ::std::vector<char>::const_iterator did_match_iter = did_match.begin();\n    for (size_t ilhs = 0; ilhs != num_elements; ++ilhs) {\n      for (size_t irhs = 0; irhs != matchers_.size(); ++irhs) {\n        matrix.SetEdge(ilhs, irhs, *did_match_iter++ != 0);\n      }\n    }\n    return matrix;\n  }\n\n  ::std::vector<Matcher<const Element&>> matchers_;\n};\n\n// Functor for use in TransformTuple.\n// Performs MatcherCast<Target> on an input argument of any type.\ntemplate <typename Target>\nstruct CastAndAppendTransform {\n  template <typename Arg>\n  Matcher<Target> operator()(const Arg& a) const {\n    return MatcherCast<Target>(a);\n  }\n};\n\n// Implements UnorderedElementsAre.\ntemplate <typename MatcherTuple>\nclass UnorderedElementsAreMatcher {\n public:\n  explicit UnorderedElementsAreMatcher(const MatcherTuple& args)\n      : matchers_(args) {}\n\n  template <typename Container>\n  operator Matcher<Container>() const {\n    typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;\n    typedef typename internal::StlContainerView<RawContainer>::type View;\n    typedef typename View::value_type Element;\n    typedef ::std::vector<Matcher<const Element&>> MatcherVec;\n    MatcherVec matchers;\n    matchers.reserve(::std::tuple_size<MatcherTuple>::value);\n    TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,\n                         ::std::back_inserter(matchers));\n    return Matcher<Container>(\n        new UnorderedElementsAreMatcherImpl<const Container&>(\n            UnorderedMatcherRequire::ExactMatch, matchers.begin(),\n            matchers.end()));\n  }\n\n private:\n  const MatcherTuple matchers_;\n};\n\n// Implements ElementsAre.\ntemplate <typename MatcherTuple>\nclass ElementsAreMatcher {\n public:\n  explicit ElementsAreMatcher(const MatcherTuple& args) : matchers_(args) {}\n\n  template <typename Container>\n  operator Matcher<Container>() const {\n    static_assert(\n        !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value ||\n            ::std::tuple_size<MatcherTuple>::value < 2,\n        \"use UnorderedElementsAre with hash tables\");\n\n    typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Container) RawContainer;\n    typedef typename internal::StlContainerView<RawContainer>::type View;\n    typedef typename View::value_type Element;\n    typedef ::std::vector<Matcher<const Element&>> MatcherVec;\n    MatcherVec matchers;\n    matchers.reserve(::std::tuple_size<MatcherTuple>::value);\n    TransformTupleValues(CastAndAppendTransform<const Element&>(), matchers_,\n                         ::std::back_inserter(matchers));\n    return Matcher<Container>(new ElementsAreMatcherImpl<const Container&>(\n        matchers.begin(), matchers.end()));\n  }\n\n private:\n  const MatcherTuple matchers_;\n};\n\n// Implements UnorderedElementsAreArray(), IsSubsetOf(), and IsSupersetOf().\ntemplate <typename T>\nclass UnorderedElementsAreArrayMatcher {\n public:\n  template <typename Iter>\n  UnorderedElementsAreArrayMatcher(UnorderedMatcherRequire::Flags match_flags,\n                                   Iter first, Iter last)\n      : match_flags_(match_flags), matchers_(first, last) {}\n\n  template <typename Container>\n  operator Matcher<Container>() const {\n    return Matcher<Container>(\n        new UnorderedElementsAreMatcherImpl<const Container&>(\n            match_flags_, matchers_.begin(), matchers_.end()));\n  }\n\n private:\n  UnorderedMatcherRequire::Flags match_flags_;\n  ::std::vector<T> matchers_;\n};\n\n// Implements ElementsAreArray().\ntemplate <typename T>\nclass ElementsAreArrayMatcher {\n public:\n  template <typename Iter>\n  ElementsAreArrayMatcher(Iter first, Iter last) : matchers_(first, last) {}\n\n  template <typename Container>\n  operator Matcher<Container>() const {\n    static_assert(\n        !IsHashTable<GTEST_REMOVE_REFERENCE_AND_CONST_(Container)>::value,\n        \"use UnorderedElementsAreArray with hash tables\");\n\n    return Matcher<Container>(new ElementsAreMatcherImpl<const Container&>(\n        matchers_.begin(), matchers_.end()));\n  }\n\n private:\n  const ::std::vector<T> matchers_;\n};\n\n// Given a 2-tuple matcher tm of type Tuple2Matcher and a value second\n// of type Second, BoundSecondMatcher<Tuple2Matcher, Second>(tm,\n// second) is a polymorphic matcher that matches a value x if and only if\n// tm matches tuple (x, second).  Useful for implementing\n// UnorderedPointwise() in terms of UnorderedElementsAreArray().\n//\n// BoundSecondMatcher is copyable and assignable, as we need to put\n// instances of this class in a vector when implementing\n// UnorderedPointwise().\ntemplate <typename Tuple2Matcher, typename Second>\nclass BoundSecondMatcher {\n public:\n  BoundSecondMatcher(const Tuple2Matcher& tm, const Second& second)\n      : tuple2_matcher_(tm), second_value_(second) {}\n\n  BoundSecondMatcher(const BoundSecondMatcher& other) = default;\n\n  template <typename T>\n  operator Matcher<T>() const {\n    return MakeMatcher(new Impl<T>(tuple2_matcher_, second_value_));\n  }\n\n  // We have to define this for UnorderedPointwise() to compile in\n  // C++98 mode, as it puts BoundSecondMatcher instances in a vector,\n  // which requires the elements to be assignable in C++98.  The\n  // compiler cannot generate the operator= for us, as Tuple2Matcher\n  // and Second may not be assignable.\n  //\n  // However, this should never be called, so the implementation just\n  // need to assert.\n  void operator=(const BoundSecondMatcher& /*rhs*/) {\n    GTEST_LOG_(FATAL) << \"BoundSecondMatcher should never be assigned.\";\n  }\n\n private:\n  template <typename T>\n  class Impl : public MatcherInterface<T> {\n   public:\n    typedef ::std::tuple<T, Second> ArgTuple;\n\n    Impl(const Tuple2Matcher& tm, const Second& second)\n        : mono_tuple2_matcher_(SafeMatcherCast<const ArgTuple&>(tm)),\n          second_value_(second) {}\n\n    void DescribeTo(::std::ostream* os) const override {\n      *os << \"and \";\n      UniversalPrint(second_value_, os);\n      *os << \" \";\n      mono_tuple2_matcher_.DescribeTo(os);\n    }\n\n    bool MatchAndExplain(T x, MatchResultListener* listener) const override {\n      return mono_tuple2_matcher_.MatchAndExplain(ArgTuple(x, second_value_),\n                                                  listener);\n    }\n\n   private:\n    const Matcher<const ArgTuple&> mono_tuple2_matcher_;\n    const Second second_value_;\n  };\n\n  const Tuple2Matcher tuple2_matcher_;\n  const Second second_value_;\n};\n\n// Given a 2-tuple matcher tm and a value second,\n// MatcherBindSecond(tm, second) returns a matcher that matches a\n// value x if and only if tm matches tuple (x, second).  Useful for\n// implementing UnorderedPointwise() in terms of UnorderedElementsAreArray().\ntemplate <typename Tuple2Matcher, typename Second>\nBoundSecondMatcher<Tuple2Matcher, Second> MatcherBindSecond(\n    const Tuple2Matcher& tm, const Second& second) {\n  return BoundSecondMatcher<Tuple2Matcher, Second>(tm, second);\n}\n\n// Returns the description for a matcher defined using the MATCHER*()\n// macro where the user-supplied description string is \"\", if\n// 'negation' is false; otherwise returns the description of the\n// negation of the matcher.  'param_values' contains a list of strings\n// that are the print-out of the matcher's parameters.\nGTEST_API_ std::string FormatMatcherDescription(\n    bool negation, const char* matcher_name,\n    const std::vector<const char*>& param_names, const Strings& param_values);\n\n// Implements a matcher that checks the value of a optional<> type variable.\ntemplate <typename ValueMatcher>\nclass OptionalMatcher {\n public:\n  explicit OptionalMatcher(const ValueMatcher& value_matcher)\n      : value_matcher_(value_matcher) {}\n\n  template <typename Optional>\n  operator Matcher<Optional>() const {\n    return Matcher<Optional>(new Impl<const Optional&>(value_matcher_));\n  }\n\n  template <typename Optional>\n  class Impl : public MatcherInterface<Optional> {\n   public:\n    typedef GTEST_REMOVE_REFERENCE_AND_CONST_(Optional) OptionalView;\n    typedef typename OptionalView::value_type ValueType;\n    explicit Impl(const ValueMatcher& value_matcher)\n        : value_matcher_(MatcherCast<ValueType>(value_matcher)) {}\n\n    void DescribeTo(::std::ostream* os) const override {\n      *os << \"value \";\n      value_matcher_.DescribeTo(os);\n    }\n\n    void DescribeNegationTo(::std::ostream* os) const override {\n      *os << \"value \";\n      value_matcher_.DescribeNegationTo(os);\n    }\n\n    bool MatchAndExplain(Optional optional,\n                         MatchResultListener* listener) const override {\n      if (!optional) {\n        *listener << \"which is not engaged\";\n        return false;\n      }\n      const ValueType& value = *optional;\n      StringMatchResultListener value_listener;\n      const bool match = value_matcher_.MatchAndExplain(value, &value_listener);\n      *listener << \"whose value \" << PrintToString(value)\n                << (match ? \" matches\" : \" doesn't match\");\n      PrintIfNotEmpty(value_listener.str(), listener->stream());\n      return match;\n    }\n\n   private:\n    const Matcher<ValueType> value_matcher_;\n  };\n\n private:\n  const ValueMatcher value_matcher_;\n};\n\nnamespace variant_matcher {\n// Overloads to allow VariantMatcher to do proper ADL lookup.\ntemplate <typename T>\nvoid holds_alternative() {}\ntemplate <typename T>\nvoid get() {}\n\n// Implements a matcher that checks the value of a variant<> type variable.\ntemplate <typename T>\nclass VariantMatcher {\n public:\n  explicit VariantMatcher(::testing::Matcher<const T&> matcher)\n      : matcher_(std::move(matcher)) {}\n\n  template <typename Variant>\n  bool MatchAndExplain(const Variant& value,\n                       ::testing::MatchResultListener* listener) const {\n    using std::get;\n    if (!listener->IsInterested()) {\n      return holds_alternative<T>(value) && matcher_.Matches(get<T>(value));\n    }\n\n    if (!holds_alternative<T>(value)) {\n      *listener << \"whose value is not of type '\" << GetTypeName() << \"'\";\n      return false;\n    }\n\n    const T& elem = get<T>(value);\n    StringMatchResultListener elem_listener;\n    const bool match = matcher_.MatchAndExplain(elem, &elem_listener);\n    *listener << \"whose value \" << PrintToString(elem)\n              << (match ? \" matches\" : \" doesn't match\");\n    PrintIfNotEmpty(elem_listener.str(), listener->stream());\n    return match;\n  }\n\n  void DescribeTo(std::ostream* os) const {\n    *os << \"is a variant<> with value of type '\" << GetTypeName()\n        << \"' and the value \";\n    matcher_.DescribeTo(os);\n  }\n\n  void DescribeNegationTo(std::ostream* os) const {\n    *os << \"is a variant<> with value of type other than '\" << GetTypeName()\n        << \"' or the value \";\n    matcher_.DescribeNegationTo(os);\n  }\n\n private:\n  static std::string GetTypeName() {\n#if GTEST_HAS_RTTI\n    GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(\n        return internal::GetTypeName<T>());\n#endif\n    return \"the element type\";\n  }\n\n  const ::testing::Matcher<const T&> matcher_;\n};\n\n}  // namespace variant_matcher\n\nnamespace any_cast_matcher {\n\n// Overloads to allow AnyCastMatcher to do proper ADL lookup.\ntemplate <typename T>\nvoid any_cast() {}\n\n// Implements a matcher that any_casts the value.\ntemplate <typename T>\nclass AnyCastMatcher {\n public:\n  explicit AnyCastMatcher(const ::testing::Matcher<const T&>& matcher)\n      : matcher_(matcher) {}\n\n  template <typename AnyType>\n  bool MatchAndExplain(const AnyType& value,\n                       ::testing::MatchResultListener* listener) const {\n    if (!listener->IsInterested()) {\n      const T* ptr = any_cast<T>(&value);\n      return ptr != nullptr && matcher_.Matches(*ptr);\n    }\n\n    const T* elem = any_cast<T>(&value);\n    if (elem == nullptr) {\n      *listener << \"whose value is not of type '\" << GetTypeName() << \"'\";\n      return false;\n    }\n\n    StringMatchResultListener elem_listener;\n    const bool match = matcher_.MatchAndExplain(*elem, &elem_listener);\n    *listener << \"whose value \" << PrintToString(*elem)\n              << (match ? \" matches\" : \" doesn't match\");\n    PrintIfNotEmpty(elem_listener.str(), listener->stream());\n    return match;\n  }\n\n  void DescribeTo(std::ostream* os) const {\n    *os << \"is an 'any' type with value of type '\" << GetTypeName()\n        << \"' and the value \";\n    matcher_.DescribeTo(os);\n  }\n\n  void DescribeNegationTo(std::ostream* os) const {\n    *os << \"is an 'any' type with value of type other than '\" << GetTypeName()\n        << \"' or the value \";\n    matcher_.DescribeNegationTo(os);\n  }\n\n private:\n  static std::string GetTypeName() {\n#if GTEST_HAS_RTTI\n    GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(\n        return internal::GetTypeName<T>());\n#endif\n    return \"the element type\";\n  }\n\n  const ::testing::Matcher<const T&> matcher_;\n};\n\n}  // namespace any_cast_matcher\n\n// Implements the Args() matcher.\ntemplate <class ArgsTuple, size_t... k>\nclass ArgsMatcherImpl : public MatcherInterface<ArgsTuple> {\n public:\n  using RawArgsTuple = typename std::decay<ArgsTuple>::type;\n  using SelectedArgs =\n      std::tuple<typename std::tuple_element<k, RawArgsTuple>::type...>;\n  using MonomorphicInnerMatcher = Matcher<const SelectedArgs&>;\n\n  template <typename InnerMatcher>\n  explicit ArgsMatcherImpl(const InnerMatcher& inner_matcher)\n      : inner_matcher_(SafeMatcherCast<const SelectedArgs&>(inner_matcher)) {}\n\n  bool MatchAndExplain(ArgsTuple args,\n                       MatchResultListener* listener) const override {\n    // Workaround spurious C4100 on MSVC<=15.7 when k is empty.\n    (void)args;\n    const SelectedArgs& selected_args =\n        std::forward_as_tuple(std::get<k>(args)...);\n    if (!listener->IsInterested()) return inner_matcher_.Matches(selected_args);\n\n    PrintIndices(listener->stream());\n    *listener << \"are \" << PrintToString(selected_args);\n\n    StringMatchResultListener inner_listener;\n    const bool match =\n        inner_matcher_.MatchAndExplain(selected_args, &inner_listener);\n    PrintIfNotEmpty(inner_listener.str(), listener->stream());\n    return match;\n  }\n\n  void DescribeTo(::std::ostream* os) const override {\n    *os << \"are a tuple \";\n    PrintIndices(os);\n    inner_matcher_.DescribeTo(os);\n  }\n\n  void DescribeNegationTo(::std::ostream* os) const override {\n    *os << \"are a tuple \";\n    PrintIndices(os);\n    inner_matcher_.DescribeNegationTo(os);\n  }\n\n private:\n  // Prints the indices of the selected fields.\n  static void PrintIndices(::std::ostream* os) {\n    *os << \"whose fields (\";\n    const char* sep = \"\";\n    // Workaround spurious C4189 on MSVC<=15.7 when k is empty.\n    (void)sep;\n    const char* dummy[] = {\"\", (*os << sep << \"#\" << k, sep = \", \")...};\n    (void)dummy;\n    *os << \") \";\n  }\n\n  MonomorphicInnerMatcher inner_matcher_;\n};\n\ntemplate <class InnerMatcher, size_t... k>\nclass ArgsMatcher {\n public:\n  explicit ArgsMatcher(InnerMatcher inner_matcher)\n      : inner_matcher_(std::move(inner_matcher)) {}\n\n  template <typename ArgsTuple>\n  operator Matcher<ArgsTuple>() const {  // NOLINT\n    return MakeMatcher(new ArgsMatcherImpl<ArgsTuple, k...>(inner_matcher_));\n  }\n\n private:\n  InnerMatcher inner_matcher_;\n};\n\n}  // namespace internal\n\n// ElementsAreArray(iterator_first, iterator_last)\n// ElementsAreArray(pointer, count)\n// ElementsAreArray(array)\n// ElementsAreArray(container)\n// ElementsAreArray({ e1, e2, ..., en })\n//\n// The ElementsAreArray() functions are like ElementsAre(...), except\n// that they are given a homogeneous sequence rather than taking each\n// element as a function argument. The sequence can be specified as an\n// array, a pointer and count, a vector, an initializer list, or an\n// STL iterator range. In each of these cases, the underlying sequence\n// can be either a sequence of values or a sequence of matchers.\n//\n// All forms of ElementsAreArray() make a copy of the input matcher sequence.\n\ntemplate <typename Iter>\ninline internal::ElementsAreArrayMatcher<\n    typename ::std::iterator_traits<Iter>::value_type>\nElementsAreArray(Iter first, Iter last) {\n  typedef typename ::std::iterator_traits<Iter>::value_type T;\n  return internal::ElementsAreArrayMatcher<T>(first, last);\n}\n\ntemplate <typename T>\ninline auto ElementsAreArray(const T* pointer, size_t count)\n    -> decltype(ElementsAreArray(pointer, pointer + count)) {\n  return ElementsAreArray(pointer, pointer + count);\n}\n\ntemplate <typename T, size_t N>\ninline auto ElementsAreArray(const T (&array)[N])\n    -> decltype(ElementsAreArray(array, N)) {\n  return ElementsAreArray(array, N);\n}\n\ntemplate <typename Container>\ninline auto ElementsAreArray(const Container& container)\n    -> decltype(ElementsAreArray(container.begin(), container.end())) {\n  return ElementsAreArray(container.begin(), container.end());\n}\n\ntemplate <typename T>\ninline auto ElementsAreArray(::std::initializer_list<T> xs)\n    -> decltype(ElementsAreArray(xs.begin(), xs.end())) {\n  return ElementsAreArray(xs.begin(), xs.end());\n}\n\n// UnorderedElementsAreArray(iterator_first, iterator_last)\n// UnorderedElementsAreArray(pointer, count)\n// UnorderedElementsAreArray(array)\n// UnorderedElementsAreArray(container)\n// UnorderedElementsAreArray({ e1, e2, ..., en })\n//\n// UnorderedElementsAreArray() verifies that a bijective mapping onto a\n// collection of matchers exists.\n//\n// The matchers can be specified as an array, a pointer and count, a container,\n// an initializer list, or an STL iterator range. In each of these cases, the\n// underlying matchers can be either values or matchers.\n\ntemplate <typename Iter>\ninline internal::UnorderedElementsAreArrayMatcher<\n    typename ::std::iterator_traits<Iter>::value_type>\nUnorderedElementsAreArray(Iter first, Iter last) {\n  typedef typename ::std::iterator_traits<Iter>::value_type T;\n  return internal::UnorderedElementsAreArrayMatcher<T>(\n      internal::UnorderedMatcherRequire::ExactMatch, first, last);\n}\n\ntemplate <typename T>\ninline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray(\n    const T* pointer, size_t count) {\n  return UnorderedElementsAreArray(pointer, pointer + count);\n}\n\ntemplate <typename T, size_t N>\ninline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray(\n    const T (&array)[N]) {\n  return UnorderedElementsAreArray(array, N);\n}\n\ntemplate <typename Container>\ninline internal::UnorderedElementsAreArrayMatcher<\n    typename Container::value_type>\nUnorderedElementsAreArray(const Container& container) {\n  return UnorderedElementsAreArray(container.begin(), container.end());\n}\n\ntemplate <typename T>\ninline internal::UnorderedElementsAreArrayMatcher<T> UnorderedElementsAreArray(\n    ::std::initializer_list<T> xs) {\n  return UnorderedElementsAreArray(xs.begin(), xs.end());\n}\n\n// _ is a matcher that matches anything of any type.\n//\n// This definition is fine as:\n//\n//   1. The C++ standard permits using the name _ in a namespace that\n//      is not the global namespace or ::std.\n//   2. The AnythingMatcher class has no data member or constructor,\n//      so it's OK to create global variables of this type.\n//   3. c-style has approved of using _ in this case.\nconst internal::AnythingMatcher _ = {};\n// Creates a matcher that matches any value of the given type T.\ntemplate <typename T>\ninline Matcher<T> A() {\n  return _;\n}\n\n// Creates a matcher that matches any value of the given type T.\ntemplate <typename T>\ninline Matcher<T> An() {\n  return _;\n}\n\ntemplate <typename T, typename M>\nMatcher<T> internal::MatcherCastImpl<T, M>::CastImpl(\n    const M& value, std::false_type /* convertible_to_matcher */,\n    std::false_type /* convertible_to_T */) {\n  return Eq(value);\n}\n\n// Creates a polymorphic matcher that matches any NULL pointer.\ninline PolymorphicMatcher<internal::IsNullMatcher> IsNull() {\n  return MakePolymorphicMatcher(internal::IsNullMatcher());\n}\n\n// Creates a polymorphic matcher that matches any non-NULL pointer.\n// This is convenient as Not(NULL) doesn't compile (the compiler\n// thinks that that expression is comparing a pointer with an integer).\ninline PolymorphicMatcher<internal::NotNullMatcher> NotNull() {\n  return MakePolymorphicMatcher(internal::NotNullMatcher());\n}\n\n// Creates a polymorphic matcher that matches any argument that\n// references variable x.\ntemplate <typename T>\ninline internal::RefMatcher<T&> Ref(T& x) {  // NOLINT\n  return internal::RefMatcher<T&>(x);\n}\n\n// Creates a polymorphic matcher that matches any NaN floating point.\ninline PolymorphicMatcher<internal::IsNanMatcher> IsNan() {\n  return MakePolymorphicMatcher(internal::IsNanMatcher());\n}\n\n// Creates a matcher that matches any double argument approximately\n// equal to rhs, where two NANs are considered unequal.\ninline internal::FloatingEqMatcher<double> DoubleEq(double rhs) {\n  return internal::FloatingEqMatcher<double>(rhs, false);\n}\n\n// Creates a matcher that matches any double argument approximately\n// equal to rhs, including NaN values when rhs is NaN.\ninline internal::FloatingEqMatcher<double> NanSensitiveDoubleEq(double rhs) {\n  return internal::FloatingEqMatcher<double>(rhs, true);\n}\n\n// Creates a matcher that matches any double argument approximately equal to\n// rhs, up to the specified max absolute error bound, where two NANs are\n// considered unequal.  The max absolute error bound must be non-negative.\ninline internal::FloatingEqMatcher<double> DoubleNear(double rhs,\n                                                      double max_abs_error) {\n  return internal::FloatingEqMatcher<double>(rhs, false, max_abs_error);\n}\n\n// Creates a matcher that matches any double argument approximately equal to\n// rhs, up to the specified max absolute error bound, including NaN values when\n// rhs is NaN.  The max absolute error bound must be non-negative.\ninline internal::FloatingEqMatcher<double> NanSensitiveDoubleNear(\n    double rhs, double max_abs_error) {\n  return internal::FloatingEqMatcher<double>(rhs, true, max_abs_error);\n}\n\n// Creates a matcher that matches any float argument approximately\n// equal to rhs, where two NANs are considered unequal.\ninline internal::FloatingEqMatcher<float> FloatEq(float rhs) {\n  return internal::FloatingEqMatcher<float>(rhs, false);\n}\n\n// Creates a matcher that matches any float argument approximately\n// equal to rhs, including NaN values when rhs is NaN.\ninline internal::FloatingEqMatcher<float> NanSensitiveFloatEq(float rhs) {\n  return internal::FloatingEqMatcher<float>(rhs, true);\n}\n\n// Creates a matcher that matches any float argument approximately equal to\n// rhs, up to the specified max absolute error bound, where two NANs are\n// considered unequal.  The max absolute error bound must be non-negative.\ninline internal::FloatingEqMatcher<float> FloatNear(float rhs,\n                                                    float max_abs_error) {\n  return internal::FloatingEqMatcher<float>(rhs, false, max_abs_error);\n}\n\n// Creates a matcher that matches any float argument approximately equal to\n// rhs, up to the specified max absolute error bound, including NaN values when\n// rhs is NaN.  The max absolute error bound must be non-negative.\ninline internal::FloatingEqMatcher<float> NanSensitiveFloatNear(\n    float rhs, float max_abs_error) {\n  return internal::FloatingEqMatcher<float>(rhs, true, max_abs_error);\n}\n\n// Creates a matcher that matches a pointer (raw or smart) that points\n// to a value that matches inner_matcher.\ntemplate <typename InnerMatcher>\ninline internal::PointeeMatcher<InnerMatcher> Pointee(\n    const InnerMatcher& inner_matcher) {\n  return internal::PointeeMatcher<InnerMatcher>(inner_matcher);\n}\n\n#if GTEST_HAS_RTTI\n// Creates a matcher that matches a pointer or reference that matches\n// inner_matcher when dynamic_cast<To> is applied.\n// The result of dynamic_cast<To> is forwarded to the inner matcher.\n// If To is a pointer and the cast fails, the inner matcher will receive NULL.\n// If To is a reference and the cast fails, this matcher returns false\n// immediately.\ntemplate <typename To>\ninline PolymorphicMatcher<internal::WhenDynamicCastToMatcher<To>>\nWhenDynamicCastTo(const Matcher<To>& inner_matcher) {\n  return MakePolymorphicMatcher(\n      internal::WhenDynamicCastToMatcher<To>(inner_matcher));\n}\n#endif  // GTEST_HAS_RTTI\n\n// Creates a matcher that matches an object whose given field matches\n// 'matcher'.  For example,\n//   Field(&Foo::number, Ge(5))\n// matches a Foo object x if and only if x.number >= 5.\ntemplate <typename Class, typename FieldType, typename FieldMatcher>\ninline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType>> Field(\n    FieldType Class::*field, const FieldMatcher& matcher) {\n  return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>(\n      field, MatcherCast<const FieldType&>(matcher)));\n  // The call to MatcherCast() is required for supporting inner\n  // matchers of compatible types.  For example, it allows\n  //   Field(&Foo::bar, m)\n  // to compile where bar is an int32 and m is a matcher for int64.\n}\n\n// Same as Field() but also takes the name of the field to provide better error\n// messages.\ntemplate <typename Class, typename FieldType, typename FieldMatcher>\ninline PolymorphicMatcher<internal::FieldMatcher<Class, FieldType>> Field(\n    const std::string& field_name, FieldType Class::*field,\n    const FieldMatcher& matcher) {\n  return MakePolymorphicMatcher(internal::FieldMatcher<Class, FieldType>(\n      field_name, field, MatcherCast<const FieldType&>(matcher)));\n}\n\n// Creates a matcher that matches an object whose given property\n// matches 'matcher'.  For example,\n//   Property(&Foo::str, StartsWith(\"hi\"))\n// matches a Foo object x if and only if x.str() starts with \"hi\".\ntemplate <typename Class, typename PropertyType, typename PropertyMatcher>\ninline PolymorphicMatcher<internal::PropertyMatcher<\n    Class, PropertyType, PropertyType (Class::*)() const>>\nProperty(PropertyType (Class::*property)() const,\n         const PropertyMatcher& matcher) {\n  return MakePolymorphicMatcher(\n      internal::PropertyMatcher<Class, PropertyType,\n                                PropertyType (Class::*)() const>(\n          property, MatcherCast<const PropertyType&>(matcher)));\n  // The call to MatcherCast() is required for supporting inner\n  // matchers of compatible types.  For example, it allows\n  //   Property(&Foo::bar, m)\n  // to compile where bar() returns an int32 and m is a matcher for int64.\n}\n\n// Same as Property() above, but also takes the name of the property to provide\n// better error messages.\ntemplate <typename Class, typename PropertyType, typename PropertyMatcher>\ninline PolymorphicMatcher<internal::PropertyMatcher<\n    Class, PropertyType, PropertyType (Class::*)() const>>\nProperty(const std::string& property_name,\n         PropertyType (Class::*property)() const,\n         const PropertyMatcher& matcher) {\n  return MakePolymorphicMatcher(\n      internal::PropertyMatcher<Class, PropertyType,\n                                PropertyType (Class::*)() const>(\n          property_name, property, MatcherCast<const PropertyType&>(matcher)));\n}\n\n// The same as above but for reference-qualified member functions.\ntemplate <typename Class, typename PropertyType, typename PropertyMatcher>\ninline PolymorphicMatcher<internal::PropertyMatcher<\n    Class, PropertyType, PropertyType (Class::*)() const&>>\nProperty(PropertyType (Class::*property)() const&,\n         const PropertyMatcher& matcher) {\n  return MakePolymorphicMatcher(\n      internal::PropertyMatcher<Class, PropertyType,\n                                PropertyType (Class::*)() const&>(\n          property, MatcherCast<const PropertyType&>(matcher)));\n}\n\n// Three-argument form for reference-qualified member functions.\ntemplate <typename Class, typename PropertyType, typename PropertyMatcher>\ninline PolymorphicMatcher<internal::PropertyMatcher<\n    Class, PropertyType, PropertyType (Class::*)() const&>>\nProperty(const std::string& property_name,\n         PropertyType (Class::*property)() const&,\n         const PropertyMatcher& matcher) {\n  return MakePolymorphicMatcher(\n      internal::PropertyMatcher<Class, PropertyType,\n                                PropertyType (Class::*)() const&>(\n          property_name, property, MatcherCast<const PropertyType&>(matcher)));\n}\n\n// Creates a matcher that matches an object if and only if the result of\n// applying a callable to x matches 'matcher'. For example,\n//   ResultOf(f, StartsWith(\"hi\"))\n// matches a Foo object x if and only if f(x) starts with \"hi\".\n// `callable` parameter can be a function, function pointer, or a functor. It is\n// required to keep no state affecting the results of the calls on it and make\n// no assumptions about how many calls will be made. Any state it keeps must be\n// protected from the concurrent access.\ntemplate <typename Callable, typename InnerMatcher>\ninternal::ResultOfMatcher<Callable, InnerMatcher> ResultOf(\n    Callable callable, InnerMatcher matcher) {\n  return internal::ResultOfMatcher<Callable, InnerMatcher>(std::move(callable),\n                                                           std::move(matcher));\n}\n\n// Same as ResultOf() above, but also takes a description of the `callable`\n// result to provide better error messages.\ntemplate <typename Callable, typename InnerMatcher>\ninternal::ResultOfMatcher<Callable, InnerMatcher> ResultOf(\n    const std::string& result_description, Callable callable,\n    InnerMatcher matcher) {\n  return internal::ResultOfMatcher<Callable, InnerMatcher>(\n      result_description, std::move(callable), std::move(matcher));\n}\n\n// String matchers.\n\n// Matches a string equal to str.\ntemplate <typename T = std::string>\nPolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrEq(\n    const internal::StringLike<T>& str) {\n  return MakePolymorphicMatcher(\n      internal::StrEqualityMatcher<std::string>(std::string(str), true, true));\n}\n\n// Matches a string not equal to str.\ntemplate <typename T = std::string>\nPolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrNe(\n    const internal::StringLike<T>& str) {\n  return MakePolymorphicMatcher(\n      internal::StrEqualityMatcher<std::string>(std::string(str), false, true));\n}\n\n// Matches a string equal to str, ignoring case.\ntemplate <typename T = std::string>\nPolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrCaseEq(\n    const internal::StringLike<T>& str) {\n  return MakePolymorphicMatcher(\n      internal::StrEqualityMatcher<std::string>(std::string(str), true, false));\n}\n\n// Matches a string not equal to str, ignoring case.\ntemplate <typename T = std::string>\nPolymorphicMatcher<internal::StrEqualityMatcher<std::string>> StrCaseNe(\n    const internal::StringLike<T>& str) {\n  return MakePolymorphicMatcher(internal::StrEqualityMatcher<std::string>(\n      std::string(str), false, false));\n}\n\n// Creates a matcher that matches any string, std::string, or C string\n// that contains the given substring.\ntemplate <typename T = std::string>\nPolymorphicMatcher<internal::HasSubstrMatcher<std::string>> HasSubstr(\n    const internal::StringLike<T>& substring) {\n  return MakePolymorphicMatcher(\n      internal::HasSubstrMatcher<std::string>(std::string(substring)));\n}\n\n// Matches a string that starts with 'prefix' (case-sensitive).\ntemplate <typename T = std::string>\nPolymorphicMatcher<internal::StartsWithMatcher<std::string>> StartsWith(\n    const internal::StringLike<T>& prefix) {\n  return MakePolymorphicMatcher(\n      internal::StartsWithMatcher<std::string>(std::string(prefix)));\n}\n\n// Matches a string that ends with 'suffix' (case-sensitive).\ntemplate <typename T = std::string>\nPolymorphicMatcher<internal::EndsWithMatcher<std::string>> EndsWith(\n    const internal::StringLike<T>& suffix) {\n  return MakePolymorphicMatcher(\n      internal::EndsWithMatcher<std::string>(std::string(suffix)));\n}\n\n#if GTEST_HAS_STD_WSTRING\n// Wide string matchers.\n\n// Matches a string equal to str.\ninline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring>> StrEq(\n    const std::wstring& str) {\n  return MakePolymorphicMatcher(\n      internal::StrEqualityMatcher<std::wstring>(str, true, true));\n}\n\n// Matches a string not equal to str.\ninline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring>> StrNe(\n    const std::wstring& str) {\n  return MakePolymorphicMatcher(\n      internal::StrEqualityMatcher<std::wstring>(str, false, true));\n}\n\n// Matches a string equal to str, ignoring case.\ninline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring>> StrCaseEq(\n    const std::wstring& str) {\n  return MakePolymorphicMatcher(\n      internal::StrEqualityMatcher<std::wstring>(str, true, false));\n}\n\n// Matches a string not equal to str, ignoring case.\ninline PolymorphicMatcher<internal::StrEqualityMatcher<std::wstring>> StrCaseNe(\n    const std::wstring& str) {\n  return MakePolymorphicMatcher(\n      internal::StrEqualityMatcher<std::wstring>(str, false, false));\n}\n\n// Creates a matcher that matches any ::wstring, std::wstring, or C wide string\n// that contains the given substring.\ninline PolymorphicMatcher<internal::HasSubstrMatcher<std::wstring>> HasSubstr(\n    const std::wstring& substring) {\n  return MakePolymorphicMatcher(\n      internal::HasSubstrMatcher<std::wstring>(substring));\n}\n\n// Matches a string that starts with 'prefix' (case-sensitive).\ninline PolymorphicMatcher<internal::StartsWithMatcher<std::wstring>> StartsWith(\n    const std::wstring& prefix) {\n  return MakePolymorphicMatcher(\n      internal::StartsWithMatcher<std::wstring>(prefix));\n}\n\n// Matches a string that ends with 'suffix' (case-sensitive).\ninline PolymorphicMatcher<internal::EndsWithMatcher<std::wstring>> EndsWith(\n    const std::wstring& suffix) {\n  return MakePolymorphicMatcher(\n      internal::EndsWithMatcher<std::wstring>(suffix));\n}\n\n#endif  // GTEST_HAS_STD_WSTRING\n\n// Creates a polymorphic matcher that matches a 2-tuple where the\n// first field == the second field.\ninline internal::Eq2Matcher Eq() { return internal::Eq2Matcher(); }\n\n// Creates a polymorphic matcher that matches a 2-tuple where the\n// first field >= the second field.\ninline internal::Ge2Matcher Ge() { return internal::Ge2Matcher(); }\n\n// Creates a polymorphic matcher that matches a 2-tuple where the\n// first field > the second field.\ninline internal::Gt2Matcher Gt() { return internal::Gt2Matcher(); }\n\n// Creates a polymorphic matcher that matches a 2-tuple where the\n// first field <= the second field.\ninline internal::Le2Matcher Le() { return internal::Le2Matcher(); }\n\n// Creates a polymorphic matcher that matches a 2-tuple where the\n// first field < the second field.\ninline internal::Lt2Matcher Lt() { return internal::Lt2Matcher(); }\n\n// Creates a polymorphic matcher that matches a 2-tuple where the\n// first field != the second field.\ninline internal::Ne2Matcher Ne() { return internal::Ne2Matcher(); }\n\n// Creates a polymorphic matcher that matches a 2-tuple where\n// FloatEq(first field) matches the second field.\ninline internal::FloatingEq2Matcher<float> FloatEq() {\n  return internal::FloatingEq2Matcher<float>();\n}\n\n// Creates a polymorphic matcher that matches a 2-tuple where\n// DoubleEq(first field) matches the second field.\ninline internal::FloatingEq2Matcher<double> DoubleEq() {\n  return internal::FloatingEq2Matcher<double>();\n}\n\n// Creates a polymorphic matcher that matches a 2-tuple where\n// FloatEq(first field) matches the second field with NaN equality.\ninline internal::FloatingEq2Matcher<float> NanSensitiveFloatEq() {\n  return internal::FloatingEq2Matcher<float>(true);\n}\n\n// Creates a polymorphic matcher that matches a 2-tuple where\n// DoubleEq(first field) matches the second field with NaN equality.\ninline internal::FloatingEq2Matcher<double> NanSensitiveDoubleEq() {\n  return internal::FloatingEq2Matcher<double>(true);\n}\n\n// Creates a polymorphic matcher that matches a 2-tuple where\n// FloatNear(first field, max_abs_error) matches the second field.\ninline internal::FloatingEq2Matcher<float> FloatNear(float max_abs_error) {\n  return internal::FloatingEq2Matcher<float>(max_abs_error);\n}\n\n// Creates a polymorphic matcher that matches a 2-tuple where\n// DoubleNear(first field, max_abs_error) matches the second field.\ninline internal::FloatingEq2Matcher<double> DoubleNear(double max_abs_error) {\n  return internal::FloatingEq2Matcher<double>(max_abs_error);\n}\n\n// Creates a polymorphic matcher that matches a 2-tuple where\n// FloatNear(first field, max_abs_error) matches the second field with NaN\n// equality.\ninline internal::FloatingEq2Matcher<float> NanSensitiveFloatNear(\n    float max_abs_error) {\n  return internal::FloatingEq2Matcher<float>(max_abs_error, true);\n}\n\n// Creates a polymorphic matcher that matches a 2-tuple where\n// DoubleNear(first field, max_abs_error) matches the second field with NaN\n// equality.\ninline internal::FloatingEq2Matcher<double> NanSensitiveDoubleNear(\n    double max_abs_error) {\n  return internal::FloatingEq2Matcher<double>(max_abs_error, true);\n}\n\n// Creates a matcher that matches any value of type T that m doesn't\n// match.\ntemplate <typename InnerMatcher>\ninline internal::NotMatcher<InnerMatcher> Not(InnerMatcher m) {\n  return internal::NotMatcher<InnerMatcher>(m);\n}\n\n// Returns a matcher that matches anything that satisfies the given\n// predicate.  The predicate can be any unary function or functor\n// whose return type can be implicitly converted to bool.\ntemplate <typename Predicate>\ninline PolymorphicMatcher<internal::TrulyMatcher<Predicate>> Truly(\n    Predicate pred) {\n  return MakePolymorphicMatcher(internal::TrulyMatcher<Predicate>(pred));\n}\n\n// Returns a matcher that matches the container size. The container must\n// support both size() and size_type which all STL-like containers provide.\n// Note that the parameter 'size' can be a value of type size_type as well as\n// matcher. For instance:\n//   EXPECT_THAT(container, SizeIs(2));     // Checks container has 2 elements.\n//   EXPECT_THAT(container, SizeIs(Le(2));  // Checks container has at most 2.\ntemplate <typename SizeMatcher>\ninline internal::SizeIsMatcher<SizeMatcher> SizeIs(\n    const SizeMatcher& size_matcher) {\n  return internal::SizeIsMatcher<SizeMatcher>(size_matcher);\n}\n\n// Returns a matcher that matches the distance between the container's begin()\n// iterator and its end() iterator, i.e. the size of the container. This matcher\n// can be used instead of SizeIs with containers such as std::forward_list which\n// do not implement size(). The container must provide const_iterator (with\n// valid iterator_traits), begin() and end().\ntemplate <typename DistanceMatcher>\ninline internal::BeginEndDistanceIsMatcher<DistanceMatcher> BeginEndDistanceIs(\n    const DistanceMatcher& distance_matcher) {\n  return internal::BeginEndDistanceIsMatcher<DistanceMatcher>(distance_matcher);\n}\n\n// Returns a matcher that matches an equal container.\n// This matcher behaves like Eq(), but in the event of mismatch lists the\n// values that are included in one container but not the other. (Duplicate\n// values and order differences are not explained.)\ntemplate <typename Container>\ninline PolymorphicMatcher<\n    internal::ContainerEqMatcher<typename std::remove_const<Container>::type>>\nContainerEq(const Container& rhs) {\n  return MakePolymorphicMatcher(internal::ContainerEqMatcher<Container>(rhs));\n}\n\n// Returns a matcher that matches a container that, when sorted using\n// the given comparator, matches container_matcher.\ntemplate <typename Comparator, typename ContainerMatcher>\ninline internal::WhenSortedByMatcher<Comparator, ContainerMatcher> WhenSortedBy(\n    const Comparator& comparator, const ContainerMatcher& container_matcher) {\n  return internal::WhenSortedByMatcher<Comparator, ContainerMatcher>(\n      comparator, container_matcher);\n}\n\n// Returns a matcher that matches a container that, when sorted using\n// the < operator, matches container_matcher.\ntemplate <typename ContainerMatcher>\ninline internal::WhenSortedByMatcher<internal::LessComparator, ContainerMatcher>\nWhenSorted(const ContainerMatcher& container_matcher) {\n  return internal::WhenSortedByMatcher<internal::LessComparator,\n                                       ContainerMatcher>(\n      internal::LessComparator(), container_matcher);\n}\n\n// Matches an STL-style container or a native array that contains the\n// same number of elements as in rhs, where its i-th element and rhs's\n// i-th element (as a pair) satisfy the given pair matcher, for all i.\n// TupleMatcher must be able to be safely cast to Matcher<std::tuple<const\n// T1&, const T2&> >, where T1 and T2 are the types of elements in the\n// LHS container and the RHS container respectively.\ntemplate <typename TupleMatcher, typename Container>\ninline internal::PointwiseMatcher<TupleMatcher,\n                                  typename std::remove_const<Container>::type>\nPointwise(const TupleMatcher& tuple_matcher, const Container& rhs) {\n  return internal::PointwiseMatcher<TupleMatcher, Container>(tuple_matcher,\n                                                             rhs);\n}\n\n// Supports the Pointwise(m, {a, b, c}) syntax.\ntemplate <typename TupleMatcher, typename T>\ninline internal::PointwiseMatcher<TupleMatcher, std::vector<T>> Pointwise(\n    const TupleMatcher& tuple_matcher, std::initializer_list<T> rhs) {\n  return Pointwise(tuple_matcher, std::vector<T>(rhs));\n}\n\n// UnorderedPointwise(pair_matcher, rhs) matches an STL-style\n// container or a native array that contains the same number of\n// elements as in rhs, where in some permutation of the container, its\n// i-th element and rhs's i-th element (as a pair) satisfy the given\n// pair matcher, for all i.  Tuple2Matcher must be able to be safely\n// cast to Matcher<std::tuple<const T1&, const T2&> >, where T1 and T2 are\n// the types of elements in the LHS container and the RHS container\n// respectively.\n//\n// This is like Pointwise(pair_matcher, rhs), except that the element\n// order doesn't matter.\ntemplate <typename Tuple2Matcher, typename RhsContainer>\ninline internal::UnorderedElementsAreArrayMatcher<\n    typename internal::BoundSecondMatcher<\n        Tuple2Matcher,\n        typename internal::StlContainerView<\n            typename std::remove_const<RhsContainer>::type>::type::value_type>>\nUnorderedPointwise(const Tuple2Matcher& tuple2_matcher,\n                   const RhsContainer& rhs_container) {\n  // RhsView allows the same code to handle RhsContainer being a\n  // STL-style container and it being a native C-style array.\n  typedef typename internal::StlContainerView<RhsContainer> RhsView;\n  typedef typename RhsView::type RhsStlContainer;\n  typedef typename RhsStlContainer::value_type Second;\n  const RhsStlContainer& rhs_stl_container =\n      RhsView::ConstReference(rhs_container);\n\n  // Create a matcher for each element in rhs_container.\n  ::std::vector<internal::BoundSecondMatcher<Tuple2Matcher, Second>> matchers;\n  for (auto it = rhs_stl_container.begin(); it != rhs_stl_container.end();\n       ++it) {\n    matchers.push_back(internal::MatcherBindSecond(tuple2_matcher, *it));\n  }\n\n  // Delegate the work to UnorderedElementsAreArray().\n  return UnorderedElementsAreArray(matchers);\n}\n\n// Supports the UnorderedPointwise(m, {a, b, c}) syntax.\ntemplate <typename Tuple2Matcher, typename T>\ninline internal::UnorderedElementsAreArrayMatcher<\n    typename internal::BoundSecondMatcher<Tuple2Matcher, T>>\nUnorderedPointwise(const Tuple2Matcher& tuple2_matcher,\n                   std::initializer_list<T> rhs) {\n  return UnorderedPointwise(tuple2_matcher, std::vector<T>(rhs));\n}\n\n// Matches an STL-style container or a native array that contains at\n// least one element matching the given value or matcher.\n//\n// Examples:\n//   ::std::set<int> page_ids;\n//   page_ids.insert(3);\n//   page_ids.insert(1);\n//   EXPECT_THAT(page_ids, Contains(1));\n//   EXPECT_THAT(page_ids, Contains(Gt(2)));\n//   EXPECT_THAT(page_ids, Not(Contains(4)));  // See below for Times(0)\n//\n//   ::std::map<int, size_t> page_lengths;\n//   page_lengths[1] = 100;\n//   EXPECT_THAT(page_lengths,\n//               Contains(::std::pair<const int, size_t>(1, 100)));\n//\n//   const char* user_ids[] = { \"joe\", \"mike\", \"tom\" };\n//   EXPECT_THAT(user_ids, Contains(Eq(::std::string(\"tom\"))));\n//\n// The matcher supports a modifier `Times` that allows to check for arbitrary\n// occurrences including testing for absence with Times(0).\n//\n// Examples:\n//   ::std::vector<int> ids;\n//   ids.insert(1);\n//   ids.insert(1);\n//   ids.insert(3);\n//   EXPECT_THAT(ids, Contains(1).Times(2));      // 1 occurs 2 times\n//   EXPECT_THAT(ids, Contains(2).Times(0));      // 2 is not present\n//   EXPECT_THAT(ids, Contains(3).Times(Ge(1)));  // 3 occurs at least once\n\ntemplate <typename M>\ninline internal::ContainsMatcher<M> Contains(M matcher) {\n  return internal::ContainsMatcher<M>(matcher);\n}\n\n// IsSupersetOf(iterator_first, iterator_last)\n// IsSupersetOf(pointer, count)\n// IsSupersetOf(array)\n// IsSupersetOf(container)\n// IsSupersetOf({e1, e2, ..., en})\n//\n// IsSupersetOf() verifies that a surjective partial mapping onto a collection\n// of matchers exists. In other words, a container matches\n// IsSupersetOf({e1, ..., en}) if and only if there is a permutation\n// {y1, ..., yn} of some of the container's elements where y1 matches e1,\n// ..., and yn matches en. Obviously, the size of the container must be >= n\n// in order to have a match. Examples:\n//\n// - {1, 2, 3} matches IsSupersetOf({Ge(3), Ne(0)}), as 3 matches Ge(3) and\n//   1 matches Ne(0).\n// - {1, 2} doesn't match IsSupersetOf({Eq(1), Lt(2)}), even though 1 matches\n//   both Eq(1) and Lt(2). The reason is that different matchers must be used\n//   for elements in different slots of the container.\n// - {1, 1, 2} matches IsSupersetOf({Eq(1), Lt(2)}), as (the first) 1 matches\n//   Eq(1) and (the second) 1 matches Lt(2).\n// - {1, 2, 3} matches IsSupersetOf(Gt(1), Gt(1)), as 2 matches (the first)\n//   Gt(1) and 3 matches (the second) Gt(1).\n//\n// The matchers can be specified as an array, a pointer and count, a container,\n// an initializer list, or an STL iterator range. In each of these cases, the\n// underlying matchers can be either values or matchers.\n\ntemplate <typename Iter>\ninline internal::UnorderedElementsAreArrayMatcher<\n    typename ::std::iterator_traits<Iter>::value_type>\nIsSupersetOf(Iter first, Iter last) {\n  typedef typename ::std::iterator_traits<Iter>::value_type T;\n  return internal::UnorderedElementsAreArrayMatcher<T>(\n      internal::UnorderedMatcherRequire::Superset, first, last);\n}\n\ntemplate <typename T>\ninline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(\n    const T* pointer, size_t count) {\n  return IsSupersetOf(pointer, pointer + count);\n}\n\ntemplate <typename T, size_t N>\ninline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(\n    const T (&array)[N]) {\n  return IsSupersetOf(array, N);\n}\n\ntemplate <typename Container>\ninline internal::UnorderedElementsAreArrayMatcher<\n    typename Container::value_type>\nIsSupersetOf(const Container& container) {\n  return IsSupersetOf(container.begin(), container.end());\n}\n\ntemplate <typename T>\ninline internal::UnorderedElementsAreArrayMatcher<T> IsSupersetOf(\n    ::std::initializer_list<T> xs) {\n  return IsSupersetOf(xs.begin(), xs.end());\n}\n\n// IsSubsetOf(iterator_first, iterator_last)\n// IsSubsetOf(pointer, count)\n// IsSubsetOf(array)\n// IsSubsetOf(container)\n// IsSubsetOf({e1, e2, ..., en})\n//\n// IsSubsetOf() verifies that an injective mapping onto a collection of matchers\n// exists.  In other words, a container matches IsSubsetOf({e1, ..., en}) if and\n// only if there is a subset of matchers {m1, ..., mk} which would match the\n// container using UnorderedElementsAre.  Obviously, the size of the container\n// must be <= n in order to have a match. Examples:\n//\n// - {1} matches IsSubsetOf({Gt(0), Lt(0)}), as 1 matches Gt(0).\n// - {1, -1} matches IsSubsetOf({Lt(0), Gt(0)}), as 1 matches Gt(0) and -1\n//   matches Lt(0).\n// - {1, 2} doesn't matches IsSubsetOf({Gt(0), Lt(0)}), even though 1 and 2 both\n//   match Gt(0). The reason is that different matchers must be used for\n//   elements in different slots of the container.\n//\n// The matchers can be specified as an array, a pointer and count, a container,\n// an initializer list, or an STL iterator range. In each of these cases, the\n// underlying matchers can be either values or matchers.\n\ntemplate <typename Iter>\ninline internal::UnorderedElementsAreArrayMatcher<\n    typename ::std::iterator_traits<Iter>::value_type>\nIsSubsetOf(Iter first, Iter last) {\n  typedef typename ::std::iterator_traits<Iter>::value_type T;\n  return internal::UnorderedElementsAreArrayMatcher<T>(\n      internal::UnorderedMatcherRequire::Subset, first, last);\n}\n\ntemplate <typename T>\ninline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(\n    const T* pointer, size_t count) {\n  return IsSubsetOf(pointer, pointer + count);\n}\n\ntemplate <typename T, size_t N>\ninline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(\n    const T (&array)[N]) {\n  return IsSubsetOf(array, N);\n}\n\ntemplate <typename Container>\ninline internal::UnorderedElementsAreArrayMatcher<\n    typename Container::value_type>\nIsSubsetOf(const Container& container) {\n  return IsSubsetOf(container.begin(), container.end());\n}\n\ntemplate <typename T>\ninline internal::UnorderedElementsAreArrayMatcher<T> IsSubsetOf(\n    ::std::initializer_list<T> xs) {\n  return IsSubsetOf(xs.begin(), xs.end());\n}\n\n// Matches an STL-style container or a native array that contains only\n// elements matching the given value or matcher.\n//\n// Each(m) is semantically equivalent to `Not(Contains(Not(m)))`. Only\n// the messages are different.\n//\n// Examples:\n//   ::std::set<int> page_ids;\n//   // Each(m) matches an empty container, regardless of what m is.\n//   EXPECT_THAT(page_ids, Each(Eq(1)));\n//   EXPECT_THAT(page_ids, Each(Eq(77)));\n//\n//   page_ids.insert(3);\n//   EXPECT_THAT(page_ids, Each(Gt(0)));\n//   EXPECT_THAT(page_ids, Not(Each(Gt(4))));\n//   page_ids.insert(1);\n//   EXPECT_THAT(page_ids, Not(Each(Lt(2))));\n//\n//   ::std::map<int, size_t> page_lengths;\n//   page_lengths[1] = 100;\n//   page_lengths[2] = 200;\n//   page_lengths[3] = 300;\n//   EXPECT_THAT(page_lengths, Not(Each(Pair(1, 100))));\n//   EXPECT_THAT(page_lengths, Each(Key(Le(3))));\n//\n//   const char* user_ids[] = { \"joe\", \"mike\", \"tom\" };\n//   EXPECT_THAT(user_ids, Not(Each(Eq(::std::string(\"tom\")))));\ntemplate <typename M>\ninline internal::EachMatcher<M> Each(M matcher) {\n  return internal::EachMatcher<M>(matcher);\n}\n\n// Key(inner_matcher) matches an std::pair whose 'first' field matches\n// inner_matcher.  For example, Contains(Key(Ge(5))) can be used to match an\n// std::map that contains at least one element whose key is >= 5.\ntemplate <typename M>\ninline internal::KeyMatcher<M> Key(M inner_matcher) {\n  return internal::KeyMatcher<M>(inner_matcher);\n}\n\n// Pair(first_matcher, second_matcher) matches a std::pair whose 'first' field\n// matches first_matcher and whose 'second' field matches second_matcher.  For\n// example, EXPECT_THAT(map_type, ElementsAre(Pair(Ge(5), \"foo\"))) can be used\n// to match a std::map<int, string> that contains exactly one element whose key\n// is >= 5 and whose value equals \"foo\".\ntemplate <typename FirstMatcher, typename SecondMatcher>\ninline internal::PairMatcher<FirstMatcher, SecondMatcher> Pair(\n    FirstMatcher first_matcher, SecondMatcher second_matcher) {\n  return internal::PairMatcher<FirstMatcher, SecondMatcher>(first_matcher,\n                                                            second_matcher);\n}\n\nnamespace no_adl {\n// Conditional() creates a matcher that conditionally uses either the first or\n// second matcher provided. For example, we could create an `equal if, and only\n// if' matcher using the Conditional wrapper as follows:\n//\n//   EXPECT_THAT(result, Conditional(condition, Eq(expected), Ne(expected)));\ntemplate <typename MatcherTrue, typename MatcherFalse>\ninternal::ConditionalMatcher<MatcherTrue, MatcherFalse> Conditional(\n    bool condition, MatcherTrue matcher_true, MatcherFalse matcher_false) {\n  return internal::ConditionalMatcher<MatcherTrue, MatcherFalse>(\n      condition, std::move(matcher_true), std::move(matcher_false));\n}\n\n// FieldsAre(matchers...) matches piecewise the fields of compatible structs.\n// These include those that support `get<I>(obj)`, and when structured bindings\n// are enabled any class that supports them.\n// In particular, `std::tuple`, `std::pair`, `std::array` and aggregate types.\ntemplate <typename... M>\ninternal::FieldsAreMatcher<typename std::decay<M>::type...> FieldsAre(\n    M&&... matchers) {\n  return internal::FieldsAreMatcher<typename std::decay<M>::type...>(\n      std::forward<M>(matchers)...);\n}\n\n// Creates a matcher that matches a pointer (raw or smart) that matches\n// inner_matcher.\ntemplate <typename InnerMatcher>\ninline internal::PointerMatcher<InnerMatcher> Pointer(\n    const InnerMatcher& inner_matcher) {\n  return internal::PointerMatcher<InnerMatcher>(inner_matcher);\n}\n\n// Creates a matcher that matches an object that has an address that matches\n// inner_matcher.\ntemplate <typename InnerMatcher>\ninline internal::AddressMatcher<InnerMatcher> Address(\n    const InnerMatcher& inner_matcher) {\n  return internal::AddressMatcher<InnerMatcher>(inner_matcher);\n}\n\n// Matches a base64 escaped string, when the unescaped string matches the\n// internal matcher.\ntemplate <typename MatcherType>\ninternal::WhenBase64UnescapedMatcher WhenBase64Unescaped(\n    const MatcherType& internal_matcher) {\n  return internal::WhenBase64UnescapedMatcher(internal_matcher);\n}\n}  // namespace no_adl\n\n// Returns a predicate that is satisfied by anything that matches the\n// given matcher.\ntemplate <typename M>\ninline internal::MatcherAsPredicate<M> Matches(M matcher) {\n  return internal::MatcherAsPredicate<M>(matcher);\n}\n\n// Returns true if and only if the value matches the matcher.\ntemplate <typename T, typename M>\ninline bool Value(const T& value, M matcher) {\n  return testing::Matches(matcher)(value);\n}\n\n// Matches the value against the given matcher and explains the match\n// result to listener.\ntemplate <typename T, typename M>\ninline bool ExplainMatchResult(M matcher, const T& value,\n                               MatchResultListener* listener) {\n  return SafeMatcherCast<const T&>(matcher).MatchAndExplain(value, listener);\n}\n\n// Returns a string representation of the given matcher.  Useful for description\n// strings of matchers defined using MATCHER_P* macros that accept matchers as\n// their arguments.  For example:\n//\n// MATCHER_P(XAndYThat, matcher,\n//           \"X that \" + DescribeMatcher<int>(matcher, negation) +\n//               (negation ? \" or\" : \" and\") + \" Y that \" +\n//               DescribeMatcher<double>(matcher, negation)) {\n//   return ExplainMatchResult(matcher, arg.x(), result_listener) &&\n//          ExplainMatchResult(matcher, arg.y(), result_listener);\n// }\ntemplate <typename T, typename M>\nstd::string DescribeMatcher(const M& matcher, bool negation = false) {\n  ::std::stringstream ss;\n  Matcher<T> monomorphic_matcher = SafeMatcherCast<T>(matcher);\n  if (negation) {\n    monomorphic_matcher.DescribeNegationTo(&ss);\n  } else {\n    monomorphic_matcher.DescribeTo(&ss);\n  }\n  return ss.str();\n}\n\ntemplate <typename... Args>\ninternal::ElementsAreMatcher<\n    std::tuple<typename std::decay<const Args&>::type...>>\nElementsAre(const Args&... matchers) {\n  return internal::ElementsAreMatcher<\n      std::tuple<typename std::decay<const Args&>::type...>>(\n      std::make_tuple(matchers...));\n}\n\ntemplate <typename... Args>\ninternal::UnorderedElementsAreMatcher<\n    std::tuple<typename std::decay<const Args&>::type...>>\nUnorderedElementsAre(const Args&... matchers) {\n  return internal::UnorderedElementsAreMatcher<\n      std::tuple<typename std::decay<const Args&>::type...>>(\n      std::make_tuple(matchers...));\n}\n\n// Define variadic matcher versions.\ntemplate <typename... Args>\ninternal::AllOfMatcher<typename std::decay<const Args&>::type...> AllOf(\n    const Args&... matchers) {\n  return internal::AllOfMatcher<typename std::decay<const Args&>::type...>(\n      matchers...);\n}\n\ntemplate <typename... Args>\ninternal::AnyOfMatcher<typename std::decay<const Args&>::type...> AnyOf(\n    const Args&... matchers) {\n  return internal::AnyOfMatcher<typename std::decay<const Args&>::type...>(\n      matchers...);\n}\n\n// AnyOfArray(array)\n// AnyOfArray(pointer, count)\n// AnyOfArray(container)\n// AnyOfArray({ e1, e2, ..., en })\n// AnyOfArray(iterator_first, iterator_last)\n//\n// AnyOfArray() verifies whether a given value matches any member of a\n// collection of matchers.\n//\n// AllOfArray(array)\n// AllOfArray(pointer, count)\n// AllOfArray(container)\n// AllOfArray({ e1, e2, ..., en })\n// AllOfArray(iterator_first, iterator_last)\n//\n// AllOfArray() verifies whether a given value matches all members of a\n// collection of matchers.\n//\n// The matchers can be specified as an array, a pointer and count, a container,\n// an initializer list, or an STL iterator range. In each of these cases, the\n// underlying matchers can be either values or matchers.\n\ntemplate <typename Iter>\ninline internal::AnyOfArrayMatcher<\n    typename ::std::iterator_traits<Iter>::value_type>\nAnyOfArray(Iter first, Iter last) {\n  return internal::AnyOfArrayMatcher<\n      typename ::std::iterator_traits<Iter>::value_type>(first, last);\n}\n\ntemplate <typename Iter>\ninline internal::AllOfArrayMatcher<\n    typename ::std::iterator_traits<Iter>::value_type>\nAllOfArray(Iter first, Iter last) {\n  return internal::AllOfArrayMatcher<\n      typename ::std::iterator_traits<Iter>::value_type>(first, last);\n}\n\ntemplate <typename T>\ninline internal::AnyOfArrayMatcher<T> AnyOfArray(const T* ptr, size_t count) {\n  return AnyOfArray(ptr, ptr + count);\n}\n\ntemplate <typename T>\ninline internal::AllOfArrayMatcher<T> AllOfArray(const T* ptr, size_t count) {\n  return AllOfArray(ptr, ptr + count);\n}\n\ntemplate <typename T, size_t N>\ninline internal::AnyOfArrayMatcher<T> AnyOfArray(const T (&array)[N]) {\n  return AnyOfArray(array, N);\n}\n\ntemplate <typename T, size_t N>\ninline internal::AllOfArrayMatcher<T> AllOfArray(const T (&array)[N]) {\n  return AllOfArray(array, N);\n}\n\ntemplate <typename Container>\ninline internal::AnyOfArrayMatcher<typename Container::value_type> AnyOfArray(\n    const Container& container) {\n  return AnyOfArray(container.begin(), container.end());\n}\n\ntemplate <typename Container>\ninline internal::AllOfArrayMatcher<typename Container::value_type> AllOfArray(\n    const Container& container) {\n  return AllOfArray(container.begin(), container.end());\n}\n\ntemplate <typename T>\ninline internal::AnyOfArrayMatcher<T> AnyOfArray(\n    ::std::initializer_list<T> xs) {\n  return AnyOfArray(xs.begin(), xs.end());\n}\n\ntemplate <typename T>\ninline internal::AllOfArrayMatcher<T> AllOfArray(\n    ::std::initializer_list<T> xs) {\n  return AllOfArray(xs.begin(), xs.end());\n}\n\n// Args<N1, N2, ..., Nk>(a_matcher) matches a tuple if the selected\n// fields of it matches a_matcher.  C++ doesn't support default\n// arguments for function templates, so we have to overload it.\ntemplate <size_t... k, typename InnerMatcher>\ninternal::ArgsMatcher<typename std::decay<InnerMatcher>::type, k...> Args(\n    InnerMatcher&& matcher) {\n  return internal::ArgsMatcher<typename std::decay<InnerMatcher>::type, k...>(\n      std::forward<InnerMatcher>(matcher));\n}\n\n// AllArgs(m) is a synonym of m.  This is useful in\n//\n//   EXPECT_CALL(foo, Bar(_, _)).With(AllArgs(Eq()));\n//\n// which is easier to read than\n//\n//   EXPECT_CALL(foo, Bar(_, _)).With(Eq());\ntemplate <typename InnerMatcher>\ninline InnerMatcher AllArgs(const InnerMatcher& matcher) {\n  return matcher;\n}\n\n// Returns a matcher that matches the value of an optional<> type variable.\n// The matcher implementation only uses '!arg' and requires that the optional<>\n// type has a 'value_type' member type and that '*arg' is of type 'value_type'\n// and is printable using 'PrintToString'. It is compatible with\n// std::optional/std::experimental::optional.\n// Note that to compare an optional type variable against nullopt you should\n// use Eq(nullopt) and not Eq(Optional(nullopt)). The latter implies that the\n// optional value contains an optional itself.\ntemplate <typename ValueMatcher>\ninline internal::OptionalMatcher<ValueMatcher> Optional(\n    const ValueMatcher& value_matcher) {\n  return internal::OptionalMatcher<ValueMatcher>(value_matcher);\n}\n\n// Returns a matcher that matches the value of a absl::any type variable.\ntemplate <typename T>\nPolymorphicMatcher<internal::any_cast_matcher::AnyCastMatcher<T>> AnyWith(\n    const Matcher<const T&>& matcher) {\n  return MakePolymorphicMatcher(\n      internal::any_cast_matcher::AnyCastMatcher<T>(matcher));\n}\n\n// Returns a matcher that matches the value of a variant<> type variable.\n// The matcher implementation uses ADL to find the holds_alternative and get\n// functions.\n// It is compatible with std::variant.\ntemplate <typename T>\nPolymorphicMatcher<internal::variant_matcher::VariantMatcher<T>> VariantWith(\n    const Matcher<const T&>& matcher) {\n  return MakePolymorphicMatcher(\n      internal::variant_matcher::VariantMatcher<T>(matcher));\n}\n\n#if GTEST_HAS_EXCEPTIONS\n\n// Anything inside the `internal` namespace is internal to the implementation\n// and must not be used in user code!\nnamespace internal {\n\nclass WithWhatMatcherImpl {\n public:\n  WithWhatMatcherImpl(Matcher<std::string> matcher)\n      : matcher_(std::move(matcher)) {}\n\n  void DescribeTo(std::ostream* os) const {\n    *os << \"contains .what() that \";\n    matcher_.DescribeTo(os);\n  }\n\n  void DescribeNegationTo(std::ostream* os) const {\n    *os << \"contains .what() that does not \";\n    matcher_.DescribeTo(os);\n  }\n\n  template <typename Err>\n  bool MatchAndExplain(const Err& err, MatchResultListener* listener) const {\n    *listener << \"which contains .what() (of value = \" << err.what()\n              << \") that \";\n    return matcher_.MatchAndExplain(err.what(), listener);\n  }\n\n private:\n  const Matcher<std::string> matcher_;\n};\n\ninline PolymorphicMatcher<WithWhatMatcherImpl> WithWhat(\n    Matcher<std::string> m) {\n  return MakePolymorphicMatcher(WithWhatMatcherImpl(std::move(m)));\n}\n\ntemplate <typename Err>\nclass ExceptionMatcherImpl {\n  class NeverThrown {\n   public:\n    const char* what() const noexcept {\n      return \"this exception should never be thrown\";\n    }\n  };\n\n  // If the matchee raises an exception of a wrong type, we'd like to\n  // catch it and print its message and type. To do that, we add an additional\n  // catch clause:\n  //\n  //     try { ... }\n  //     catch (const Err&) { /* an expected exception */ }\n  //     catch (const std::exception&) { /* exception of a wrong type */ }\n  //\n  // However, if the `Err` itself is `std::exception`, we'd end up with two\n  // identical `catch` clauses:\n  //\n  //     try { ... }\n  //     catch (const std::exception&) { /* an expected exception */ }\n  //     catch (const std::exception&) { /* exception of a wrong type */ }\n  //\n  // This can cause a warning or an error in some compilers. To resolve\n  // the issue, we use a fake error type whenever `Err` is `std::exception`:\n  //\n  //     try { ... }\n  //     catch (const std::exception&) { /* an expected exception */ }\n  //     catch (const NeverThrown&) { /* exception of a wrong type */ }\n  using DefaultExceptionType = typename std::conditional<\n      std::is_same<typename std::remove_cv<\n                       typename std::remove_reference<Err>::type>::type,\n                   std::exception>::value,\n      const NeverThrown&, const std::exception&>::type;\n\n public:\n  ExceptionMatcherImpl(Matcher<const Err&> matcher)\n      : matcher_(std::move(matcher)) {}\n\n  void DescribeTo(std::ostream* os) const {\n    *os << \"throws an exception which is a \" << GetTypeName<Err>();\n    *os << \" which \";\n    matcher_.DescribeTo(os);\n  }\n\n  void DescribeNegationTo(std::ostream* os) const {\n    *os << \"throws an exception which is not a \" << GetTypeName<Err>();\n    *os << \" which \";\n    matcher_.DescribeNegationTo(os);\n  }\n\n  template <typename T>\n  bool MatchAndExplain(T&& x, MatchResultListener* listener) const {\n    try {\n      (void)(std::forward<T>(x)());\n    } catch (const Err& err) {\n      *listener << \"throws an exception which is a \" << GetTypeName<Err>();\n      *listener << \" \";\n      return matcher_.MatchAndExplain(err, listener);\n    } catch (DefaultExceptionType err) {\n#if GTEST_HAS_RTTI\n      *listener << \"throws an exception of type \" << GetTypeName(typeid(err));\n      *listener << \" \";\n#else\n      *listener << \"throws an std::exception-derived type \";\n#endif\n      *listener << \"with description \\\"\" << err.what() << \"\\\"\";\n      return false;\n    } catch (...) {\n      *listener << \"throws an exception of an unknown type\";\n      return false;\n    }\n\n    *listener << \"does not throw any exception\";\n    return false;\n  }\n\n private:\n  const Matcher<const Err&> matcher_;\n};\n\n}  // namespace internal\n\n// Throws()\n// Throws(exceptionMatcher)\n// ThrowsMessage(messageMatcher)\n//\n// This matcher accepts a callable and verifies that when invoked, it throws\n// an exception with the given type and properties.\n//\n// Examples:\n//\n//   EXPECT_THAT(\n//       []() { throw std::runtime_error(\"message\"); },\n//       Throws<std::runtime_error>());\n//\n//   EXPECT_THAT(\n//       []() { throw std::runtime_error(\"message\"); },\n//       ThrowsMessage<std::runtime_error>(HasSubstr(\"message\")));\n//\n//   EXPECT_THAT(\n//       []() { throw std::runtime_error(\"message\"); },\n//       Throws<std::runtime_error>(\n//           Property(&std::runtime_error::what, HasSubstr(\"message\"))));\n\ntemplate <typename Err>\nPolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> Throws() {\n  return MakePolymorphicMatcher(\n      internal::ExceptionMatcherImpl<Err>(A<const Err&>()));\n}\n\ntemplate <typename Err, typename ExceptionMatcher>\nPolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> Throws(\n    const ExceptionMatcher& exception_matcher) {\n  // Using matcher cast allows users to pass a matcher of a more broad type.\n  // For example user may want to pass Matcher<std::exception>\n  // to Throws<std::runtime_error>, or Matcher<int64> to Throws<int32>.\n  return MakePolymorphicMatcher(internal::ExceptionMatcherImpl<Err>(\n      SafeMatcherCast<const Err&>(exception_matcher)));\n}\n\ntemplate <typename Err, typename MessageMatcher>\nPolymorphicMatcher<internal::ExceptionMatcherImpl<Err>> ThrowsMessage(\n    MessageMatcher&& message_matcher) {\n  static_assert(std::is_base_of<std::exception, Err>::value,\n                \"expected an std::exception-derived type\");\n  return Throws<Err>(internal::WithWhat(\n      MatcherCast<std::string>(std::forward<MessageMatcher>(message_matcher))));\n}\n\n#endif  // GTEST_HAS_EXCEPTIONS\n\n// These macros allow using matchers to check values in Google Test\n// tests.  ASSERT_THAT(value, matcher) and EXPECT_THAT(value, matcher)\n// succeed if and only if the value matches the matcher.  If the assertion\n// fails, the value and the description of the matcher will be printed.\n#define ASSERT_THAT(value, matcher) \\\n  ASSERT_PRED_FORMAT1(              \\\n      ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)\n#define EXPECT_THAT(value, matcher) \\\n  EXPECT_PRED_FORMAT1(              \\\n      ::testing::internal::MakePredicateFormatterFromMatcher(matcher), value)\n\n// MATCHER* macros itself are listed below.\n#define MATCHER(name, description)                                             \\\n  class name##Matcher                                                          \\\n      : public ::testing::internal::MatcherBaseImpl<name##Matcher> {           \\\n   public:                                                                     \\\n    template <typename arg_type>                                               \\\n    class gmock_Impl : public ::testing::MatcherInterface<const arg_type&> {   \\\n     public:                                                                   \\\n      gmock_Impl() {}                                                          \\\n      bool MatchAndExplain(                                                    \\\n          const arg_type& arg,                                                 \\\n          ::testing::MatchResultListener* result_listener) const override;     \\\n      void DescribeTo(::std::ostream* gmock_os) const override {               \\\n        *gmock_os << FormatDescription(false);                                 \\\n      }                                                                        \\\n      void DescribeNegationTo(::std::ostream* gmock_os) const override {       \\\n        *gmock_os << FormatDescription(true);                                  \\\n      }                                                                        \\\n                                                                               \\\n     private:                                                                  \\\n      ::std::string FormatDescription(bool negation) const {                   \\\n        /* NOLINTNEXTLINE readability-redundant-string-init */                 \\\n        ::std::string gmock_description = (description);                       \\\n        if (!gmock_description.empty()) {                                      \\\n          return gmock_description;                                            \\\n        }                                                                      \\\n        return ::testing::internal::FormatMatcherDescription(negation, #name,  \\\n                                                             {}, {});          \\\n      }                                                                        \\\n    };                                                                         \\\n  };                                                                           \\\n  GTEST_ATTRIBUTE_UNUSED_ inline name##Matcher name() { return {}; }           \\\n  template <typename arg_type>                                                 \\\n  bool name##Matcher::gmock_Impl<arg_type>::MatchAndExplain(                   \\\n      const arg_type& arg,                                                     \\\n      ::testing::MatchResultListener* result_listener GTEST_ATTRIBUTE_UNUSED_) \\\n      const\n\n#define MATCHER_P(name, p0, description) \\\n  GMOCK_INTERNAL_MATCHER(name, name##MatcherP, description, (#p0), (p0))\n#define MATCHER_P2(name, p0, p1, description)                            \\\n  GMOCK_INTERNAL_MATCHER(name, name##MatcherP2, description, (#p0, #p1), \\\n                         (p0, p1))\n#define MATCHER_P3(name, p0, p1, p2, description)                             \\\n  GMOCK_INTERNAL_MATCHER(name, name##MatcherP3, description, (#p0, #p1, #p2), \\\n                         (p0, p1, p2))\n#define MATCHER_P4(name, p0, p1, p2, p3, description)        \\\n  GMOCK_INTERNAL_MATCHER(name, name##MatcherP4, description, \\\n                         (#p0, #p1, #p2, #p3), (p0, p1, p2, p3))\n#define MATCHER_P5(name, p0, p1, p2, p3, p4, description)    \\\n  GMOCK_INTERNAL_MATCHER(name, name##MatcherP5, description, \\\n                         (#p0, #p1, #p2, #p3, #p4), (p0, p1, p2, p3, p4))\n#define MATCHER_P6(name, p0, p1, p2, p3, p4, p5, description) \\\n  GMOCK_INTERNAL_MATCHER(name, name##MatcherP6, description,  \\\n                         (#p0, #p1, #p2, #p3, #p4, #p5),      \\\n                         (p0, p1, p2, p3, p4, p5))\n#define MATCHER_P7(name, p0, p1, p2, p3, p4, p5, p6, description) \\\n  GMOCK_INTERNAL_MATCHER(name, name##MatcherP7, description,      \\\n                         (#p0, #p1, #p2, #p3, #p4, #p5, #p6),     \\\n                         (p0, p1, p2, p3, p4, p5, p6))\n#define MATCHER_P8(name, p0, p1, p2, p3, p4, p5, p6, p7, description) \\\n  GMOCK_INTERNAL_MATCHER(name, name##MatcherP8, description,          \\\n                         (#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7),    \\\n                         (p0, p1, p2, p3, p4, p5, p6, p7))\n#define MATCHER_P9(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, description) \\\n  GMOCK_INTERNAL_MATCHER(name, name##MatcherP9, description,              \\\n                         (#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7, #p8),   \\\n                         (p0, p1, p2, p3, p4, p5, p6, p7, p8))\n#define MATCHER_P10(name, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, description) \\\n  GMOCK_INTERNAL_MATCHER(name, name##MatcherP10, description,                  \\\n                         (#p0, #p1, #p2, #p3, #p4, #p5, #p6, #p7, #p8, #p9),   \\\n                         (p0, p1, p2, p3, p4, p5, p6, p7, p8, p9))\n\n#define GMOCK_INTERNAL_MATCHER(name, full_name, description, arg_names, args)  \\\n  template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)>                      \\\n  class full_name : public ::testing::internal::MatcherBaseImpl<               \\\n                        full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>> { \\\n   public:                                                                     \\\n    using full_name::MatcherBaseImpl::MatcherBaseImpl;                         \\\n    template <typename arg_type>                                               \\\n    class gmock_Impl : public ::testing::MatcherInterface<const arg_type&> {   \\\n     public:                                                                   \\\n      explicit gmock_Impl(GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args))          \\\n          : GMOCK_INTERNAL_MATCHER_FORWARD_ARGS(args) {}                       \\\n      bool MatchAndExplain(                                                    \\\n          const arg_type& arg,                                                 \\\n          ::testing::MatchResultListener* result_listener) const override;     \\\n      void DescribeTo(::std::ostream* gmock_os) const override {               \\\n        *gmock_os << FormatDescription(false);                                 \\\n      }                                                                        \\\n      void DescribeNegationTo(::std::ostream* gmock_os) const override {       \\\n        *gmock_os << FormatDescription(true);                                  \\\n      }                                                                        \\\n      GMOCK_INTERNAL_MATCHER_MEMBERS(args)                                     \\\n                                                                               \\\n     private:                                                                  \\\n      ::std::string FormatDescription(bool negation) const {                   \\\n        ::std::string gmock_description = (description);                       \\\n        if (!gmock_description.empty()) {                                      \\\n          return gmock_description;                                            \\\n        }                                                                      \\\n        return ::testing::internal::FormatMatcherDescription(                  \\\n            negation, #name, {GMOCK_PP_REMOVE_PARENS(arg_names)},              \\\n            ::testing::internal::UniversalTersePrintTupleFieldsToStrings(      \\\n                ::std::tuple<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>(        \\\n                    GMOCK_INTERNAL_MATCHER_MEMBERS_USAGE(args))));             \\\n      }                                                                        \\\n    };                                                                         \\\n  };                                                                           \\\n  template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)>                      \\\n  inline full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)> name(             \\\n      GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args)) {                            \\\n    return full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>(                \\\n        GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args));                              \\\n  }                                                                            \\\n  template <GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args)>                      \\\n  template <typename arg_type>                                                 \\\n  bool full_name<GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args)>::gmock_Impl<        \\\n      arg_type>::MatchAndExplain(const arg_type& arg,                          \\\n                                 ::testing::MatchResultListener*               \\\n                                     result_listener GTEST_ATTRIBUTE_UNUSED_)  \\\n      const\n\n#define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAMS(args) \\\n  GMOCK_PP_TAIL(                                     \\\n      GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAM, , args))\n#define GMOCK_INTERNAL_MATCHER_TEMPLATE_PARAM(i_unused, data_unused, arg) \\\n  , typename arg##_type\n\n#define GMOCK_INTERNAL_MATCHER_TYPE_PARAMS(args) \\\n  GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_TYPE_PARAM, , args))\n#define GMOCK_INTERNAL_MATCHER_TYPE_PARAM(i_unused, data_unused, arg) \\\n  , arg##_type\n\n#define GMOCK_INTERNAL_MATCHER_FUNCTION_ARGS(args) \\\n  GMOCK_PP_TAIL(dummy_first GMOCK_PP_FOR_EACH(     \\\n      GMOCK_INTERNAL_MATCHER_FUNCTION_ARG, , args))\n#define GMOCK_INTERNAL_MATCHER_FUNCTION_ARG(i, data_unused, arg) \\\n  , arg##_type gmock_p##i\n\n#define GMOCK_INTERNAL_MATCHER_FORWARD_ARGS(args) \\\n  GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_FORWARD_ARG, , args))\n#define GMOCK_INTERNAL_MATCHER_FORWARD_ARG(i, data_unused, arg) \\\n  , arg(::std::forward<arg##_type>(gmock_p##i))\n\n#define GMOCK_INTERNAL_MATCHER_MEMBERS(args) \\\n  GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_MEMBER, , args)\n#define GMOCK_INTERNAL_MATCHER_MEMBER(i_unused, data_unused, arg) \\\n  const arg##_type arg;\n\n#define GMOCK_INTERNAL_MATCHER_MEMBERS_USAGE(args) \\\n  GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_MEMBER_USAGE, , args))\n#define GMOCK_INTERNAL_MATCHER_MEMBER_USAGE(i_unused, data_unused, arg) , arg\n\n#define GMOCK_INTERNAL_MATCHER_ARGS_USAGE(args) \\\n  GMOCK_PP_TAIL(GMOCK_PP_FOR_EACH(GMOCK_INTERNAL_MATCHER_ARG_USAGE, , args))\n#define GMOCK_INTERNAL_MATCHER_ARG_USAGE(i, data_unused, arg_unused) \\\n  , gmock_p##i\n\n// To prevent ADL on certain functions we put them on a separate namespace.\nusing namespace no_adl;  // NOLINT\n\n}  // namespace testing\n\nGTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251 5046\n\n// Include any custom callback matchers added by the local installation.\n// We must include this header at the end to make sure it can use the\n// declarations from this file.\n#include \"gmock/internal/custom/gmock-matchers.h\"\n\n#endif  // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MATCHERS_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/include/gmock/gmock-more-actions.h",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file implements some commonly used variadic actions.\n\n// IWYU pragma: private, include \"gmock/gmock.h\"\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_\n#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_\n\n#include <memory>\n#include <utility>\n\n#include \"gmock/gmock-actions.h\"\n#include \"gmock/internal/gmock-port.h\"\n\n// Include any custom callback actions added by the local installation.\n#include \"gmock/internal/custom/gmock-generated-actions.h\"\n\n// Sometimes you want to give an action explicit template parameters\n// that cannot be inferred from its value parameters.  ACTION() and\n// ACTION_P*() don't support that.  ACTION_TEMPLATE() remedies that\n// and can be viewed as an extension to ACTION() and ACTION_P*().\n//\n// The syntax:\n//\n//   ACTION_TEMPLATE(ActionName,\n//                   HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m),\n//                   AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; }\n//\n// defines an action template that takes m explicit template\n// parameters and n value parameters.  name_i is the name of the i-th\n// template parameter, and kind_i specifies whether it's a typename,\n// an integral constant, or a template.  p_i is the name of the i-th\n// value parameter.\n//\n// Example:\n//\n//   // DuplicateArg<k, T>(output) converts the k-th argument of the mock\n//   // function to type T and copies it to *output.\n//   ACTION_TEMPLATE(DuplicateArg,\n//                   HAS_2_TEMPLATE_PARAMS(int, k, typename, T),\n//                   AND_1_VALUE_PARAMS(output)) {\n//     *output = T(::std::get<k>(args));\n//   }\n//   ...\n//     int n;\n//     EXPECT_CALL(mock, Foo(_, _))\n//         .WillOnce(DuplicateArg<1, unsigned char>(&n));\n//\n// To create an instance of an action template, write:\n//\n//   ActionName<t1, ..., t_m>(v1, ..., v_n)\n//\n// where the ts are the template arguments and the vs are the value\n// arguments.  The value argument types are inferred by the compiler.\n// If you want to explicitly specify the value argument types, you can\n// provide additional template arguments:\n//\n//   ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n)\n//\n// where u_i is the desired type of v_i.\n//\n// ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded on the\n// number of value parameters, but not on the number of template\n// parameters.  Without the restriction, the meaning of the following\n// is unclear:\n//\n//   OverloadedAction<int, bool>(x);\n//\n// Are we using a single-template-parameter action where 'bool' refers\n// to the type of x, or are we using a two-template-parameter action\n// where the compiler is asked to infer the type of x?\n//\n// Implementation notes:\n//\n// GMOCK_INTERNAL_*_HAS_m_TEMPLATE_PARAMS and\n// GMOCK_INTERNAL_*_AND_n_VALUE_PARAMS are internal macros for\n// implementing ACTION_TEMPLATE.  The main trick we use is to create\n// new macro invocations when expanding a macro.  For example, we have\n//\n//   #define ACTION_TEMPLATE(name, template_params, value_params)\n//       ... GMOCK_INTERNAL_DECL_##template_params ...\n//\n// which causes ACTION_TEMPLATE(..., HAS_1_TEMPLATE_PARAMS(typename, T), ...)\n// to expand to\n//\n//       ... GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(typename, T) ...\n//\n// Since GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS is a macro, the\n// preprocessor will continue to expand it to\n//\n//       ... typename T ...\n//\n// This technique conforms to the C++ standard and is portable.  It\n// allows us to implement action templates using O(N) code, where N is\n// the maximum number of template/value parameters supported.  Without\n// using it, we'd have to devote O(N^2) amount of code to implement all\n// combinations of m and n.\n\n// Declares the template parameters.\n#define GMOCK_INTERNAL_DECL_HAS_1_TEMPLATE_PARAMS(kind0, name0) kind0 name0\n#define GMOCK_INTERNAL_DECL_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, name1) \\\n  kind0 name0, kind1 name1\n#define GMOCK_INTERNAL_DECL_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \\\n                                                  kind2, name2)               \\\n  kind0 name0, kind1 name1, kind2 name2\n#define GMOCK_INTERNAL_DECL_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \\\n                                                  kind2, name2, kind3, name3) \\\n  kind0 name0, kind1 name1, kind2 name2, kind3 name3\n#define GMOCK_INTERNAL_DECL_HAS_5_TEMPLATE_PARAMS(                        \\\n    kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4) \\\n  kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4\n#define GMOCK_INTERNAL_DECL_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \\\n                                                  kind2, name2, kind3, name3, \\\n                                                  kind4, name4, kind5, name5) \\\n  kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4, kind5 name5\n#define GMOCK_INTERNAL_DECL_HAS_7_TEMPLATE_PARAMS(                        \\\n    kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \\\n    kind5, name5, kind6, name6)                                           \\\n  kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4,        \\\n      kind5 name5, kind6 name6\n#define GMOCK_INTERNAL_DECL_HAS_8_TEMPLATE_PARAMS(                        \\\n    kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \\\n    kind5, name5, kind6, name6, kind7, name7)                             \\\n  kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4,        \\\n      kind5 name5, kind6 name6, kind7 name7\n#define GMOCK_INTERNAL_DECL_HAS_9_TEMPLATE_PARAMS(                        \\\n    kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \\\n    kind5, name5, kind6, name6, kind7, name7, kind8, name8)               \\\n  kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4,        \\\n      kind5 name5, kind6 name6, kind7 name7, kind8 name8\n#define GMOCK_INTERNAL_DECL_HAS_10_TEMPLATE_PARAMS(                       \\\n    kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \\\n    kind5, name5, kind6, name6, kind7, name7, kind8, name8, kind9, name9) \\\n  kind0 name0, kind1 name1, kind2 name2, kind3 name3, kind4 name4,        \\\n      kind5 name5, kind6 name6, kind7 name7, kind8 name8, kind9 name9\n\n// Lists the template parameters.\n#define GMOCK_INTERNAL_LIST_HAS_1_TEMPLATE_PARAMS(kind0, name0) name0\n#define GMOCK_INTERNAL_LIST_HAS_2_TEMPLATE_PARAMS(kind0, name0, kind1, name1) \\\n  name0, name1\n#define GMOCK_INTERNAL_LIST_HAS_3_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \\\n                                                  kind2, name2)               \\\n  name0, name1, name2\n#define GMOCK_INTERNAL_LIST_HAS_4_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \\\n                                                  kind2, name2, kind3, name3) \\\n  name0, name1, name2, name3\n#define GMOCK_INTERNAL_LIST_HAS_5_TEMPLATE_PARAMS(                        \\\n    kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4) \\\n  name0, name1, name2, name3, name4\n#define GMOCK_INTERNAL_LIST_HAS_6_TEMPLATE_PARAMS(kind0, name0, kind1, name1, \\\n                                                  kind2, name2, kind3, name3, \\\n                                                  kind4, name4, kind5, name5) \\\n  name0, name1, name2, name3, name4, name5\n#define GMOCK_INTERNAL_LIST_HAS_7_TEMPLATE_PARAMS(                        \\\n    kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \\\n    kind5, name5, kind6, name6)                                           \\\n  name0, name1, name2, name3, name4, name5, name6\n#define GMOCK_INTERNAL_LIST_HAS_8_TEMPLATE_PARAMS(                        \\\n    kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \\\n    kind5, name5, kind6, name6, kind7, name7)                             \\\n  name0, name1, name2, name3, name4, name5, name6, name7\n#define GMOCK_INTERNAL_LIST_HAS_9_TEMPLATE_PARAMS(                        \\\n    kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \\\n    kind5, name5, kind6, name6, kind7, name7, kind8, name8)               \\\n  name0, name1, name2, name3, name4, name5, name6, name7, name8\n#define GMOCK_INTERNAL_LIST_HAS_10_TEMPLATE_PARAMS(                       \\\n    kind0, name0, kind1, name1, kind2, name2, kind3, name3, kind4, name4, \\\n    kind5, name5, kind6, name6, kind7, name7, kind8, name8, kind9, name9) \\\n  name0, name1, name2, name3, name4, name5, name6, name7, name8, name9\n\n// Declares the types of value parameters.\n#define GMOCK_INTERNAL_DECL_TYPE_AND_0_VALUE_PARAMS()\n#define GMOCK_INTERNAL_DECL_TYPE_AND_1_VALUE_PARAMS(p0) , typename p0##_type\n#define GMOCK_INTERNAL_DECL_TYPE_AND_2_VALUE_PARAMS(p0, p1) \\\n  , typename p0##_type, typename p1##_type\n#define GMOCK_INTERNAL_DECL_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) \\\n  , typename p0##_type, typename p1##_type, typename p2##_type\n#define GMOCK_INTERNAL_DECL_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \\\n  , typename p0##_type, typename p1##_type, typename p2##_type,     \\\n      typename p3##_type\n#define GMOCK_INTERNAL_DECL_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \\\n  , typename p0##_type, typename p1##_type, typename p2##_type,         \\\n      typename p3##_type, typename p4##_type\n#define GMOCK_INTERNAL_DECL_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \\\n  , typename p0##_type, typename p1##_type, typename p2##_type,             \\\n      typename p3##_type, typename p4##_type, typename p5##_type\n#define GMOCK_INTERNAL_DECL_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \\\n                                                    p6)                     \\\n  , typename p0##_type, typename p1##_type, typename p2##_type,             \\\n      typename p3##_type, typename p4##_type, typename p5##_type,           \\\n      typename p6##_type\n#define GMOCK_INTERNAL_DECL_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \\\n                                                    p6, p7)                 \\\n  , typename p0##_type, typename p1##_type, typename p2##_type,             \\\n      typename p3##_type, typename p4##_type, typename p5##_type,           \\\n      typename p6##_type, typename p7##_type\n#define GMOCK_INTERNAL_DECL_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \\\n                                                    p6, p7, p8)             \\\n  , typename p0##_type, typename p1##_type, typename p2##_type,             \\\n      typename p3##_type, typename p4##_type, typename p5##_type,           \\\n      typename p6##_type, typename p7##_type, typename p8##_type\n#define GMOCK_INTERNAL_DECL_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \\\n                                                     p6, p7, p8, p9)         \\\n  , typename p0##_type, typename p1##_type, typename p2##_type,              \\\n      typename p3##_type, typename p4##_type, typename p5##_type,            \\\n      typename p6##_type, typename p7##_type, typename p8##_type,            \\\n      typename p9##_type\n\n// Initializes the value parameters.\n#define GMOCK_INTERNAL_INIT_AND_0_VALUE_PARAMS() ()\n#define GMOCK_INTERNAL_INIT_AND_1_VALUE_PARAMS(p0) \\\n  (p0##_type gmock_p0) : p0(::std::move(gmock_p0))\n#define GMOCK_INTERNAL_INIT_AND_2_VALUE_PARAMS(p0, p1) \\\n  (p0##_type gmock_p0, p1##_type gmock_p1)             \\\n      : p0(::std::move(gmock_p0)), p1(::std::move(gmock_p1))\n#define GMOCK_INTERNAL_INIT_AND_3_VALUE_PARAMS(p0, p1, p2)     \\\n  (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2) \\\n      : p0(::std::move(gmock_p0)),                             \\\n        p1(::std::move(gmock_p1)),                             \\\n        p2(::std::move(gmock_p2))\n#define GMOCK_INTERNAL_INIT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \\\n  (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2, \\\n   p3##_type gmock_p3)                                         \\\n      : p0(::std::move(gmock_p0)),                             \\\n        p1(::std::move(gmock_p1)),                             \\\n        p2(::std::move(gmock_p2)),                             \\\n        p3(::std::move(gmock_p3))\n#define GMOCK_INTERNAL_INIT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \\\n  (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2,     \\\n   p3##_type gmock_p3, p4##_type gmock_p4)                         \\\n      : p0(::std::move(gmock_p0)),                                 \\\n        p1(::std::move(gmock_p1)),                                 \\\n        p2(::std::move(gmock_p2)),                                 \\\n        p3(::std::move(gmock_p3)),                                 \\\n        p4(::std::move(gmock_p4))\n#define GMOCK_INTERNAL_INIT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \\\n  (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2,         \\\n   p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5)         \\\n      : p0(::std::move(gmock_p0)),                                     \\\n        p1(::std::move(gmock_p1)),                                     \\\n        p2(::std::move(gmock_p2)),                                     \\\n        p3(::std::move(gmock_p3)),                                     \\\n        p4(::std::move(gmock_p4)),                                     \\\n        p5(::std::move(gmock_p5))\n#define GMOCK_INTERNAL_INIT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \\\n  (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2,             \\\n   p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5,             \\\n   p6##_type gmock_p6)                                                     \\\n      : p0(::std::move(gmock_p0)),                                         \\\n        p1(::std::move(gmock_p1)),                                         \\\n        p2(::std::move(gmock_p2)),                                         \\\n        p3(::std::move(gmock_p3)),                                         \\\n        p4(::std::move(gmock_p4)),                                         \\\n        p5(::std::move(gmock_p5)),                                         \\\n        p6(::std::move(gmock_p6))\n#define GMOCK_INTERNAL_INIT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \\\n  (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2,                 \\\n   p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5,                 \\\n   p6##_type gmock_p6, p7##_type gmock_p7)                                     \\\n      : p0(::std::move(gmock_p0)),                                             \\\n        p1(::std::move(gmock_p1)),                                             \\\n        p2(::std::move(gmock_p2)),                                             \\\n        p3(::std::move(gmock_p3)),                                             \\\n        p4(::std::move(gmock_p4)),                                             \\\n        p5(::std::move(gmock_p5)),                                             \\\n        p6(::std::move(gmock_p6)),                                             \\\n        p7(::std::move(gmock_p7))\n#define GMOCK_INTERNAL_INIT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \\\n                                               p8)                             \\\n  (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2,                 \\\n   p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5,                 \\\n   p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8)                 \\\n      : p0(::std::move(gmock_p0)),                                             \\\n        p1(::std::move(gmock_p1)),                                             \\\n        p2(::std::move(gmock_p2)),                                             \\\n        p3(::std::move(gmock_p3)),                                             \\\n        p4(::std::move(gmock_p4)),                                             \\\n        p5(::std::move(gmock_p5)),                                             \\\n        p6(::std::move(gmock_p6)),                                             \\\n        p7(::std::move(gmock_p7)),                                             \\\n        p8(::std::move(gmock_p8))\n#define GMOCK_INTERNAL_INIT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \\\n                                                p7, p8, p9)                 \\\n  (p0##_type gmock_p0, p1##_type gmock_p1, p2##_type gmock_p2,              \\\n   p3##_type gmock_p3, p4##_type gmock_p4, p5##_type gmock_p5,              \\\n   p6##_type gmock_p6, p7##_type gmock_p7, p8##_type gmock_p8,              \\\n   p9##_type gmock_p9)                                                      \\\n      : p0(::std::move(gmock_p0)),                                          \\\n        p1(::std::move(gmock_p1)),                                          \\\n        p2(::std::move(gmock_p2)),                                          \\\n        p3(::std::move(gmock_p3)),                                          \\\n        p4(::std::move(gmock_p4)),                                          \\\n        p5(::std::move(gmock_p5)),                                          \\\n        p6(::std::move(gmock_p6)),                                          \\\n        p7(::std::move(gmock_p7)),                                          \\\n        p8(::std::move(gmock_p8)),                                          \\\n        p9(::std::move(gmock_p9))\n\n// Defines the copy constructor\n#define GMOCK_INTERNAL_DEFN_COPY_AND_0_VALUE_PARAMS() \\\n  {}  // Avoid https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82134\n#define GMOCK_INTERNAL_DEFN_COPY_AND_1_VALUE_PARAMS(...) = default;\n#define GMOCK_INTERNAL_DEFN_COPY_AND_2_VALUE_PARAMS(...) = default;\n#define GMOCK_INTERNAL_DEFN_COPY_AND_3_VALUE_PARAMS(...) = default;\n#define GMOCK_INTERNAL_DEFN_COPY_AND_4_VALUE_PARAMS(...) = default;\n#define GMOCK_INTERNAL_DEFN_COPY_AND_5_VALUE_PARAMS(...) = default;\n#define GMOCK_INTERNAL_DEFN_COPY_AND_6_VALUE_PARAMS(...) = default;\n#define GMOCK_INTERNAL_DEFN_COPY_AND_7_VALUE_PARAMS(...) = default;\n#define GMOCK_INTERNAL_DEFN_COPY_AND_8_VALUE_PARAMS(...) = default;\n#define GMOCK_INTERNAL_DEFN_COPY_AND_9_VALUE_PARAMS(...) = default;\n#define GMOCK_INTERNAL_DEFN_COPY_AND_10_VALUE_PARAMS(...) = default;\n\n// Declares the fields for storing the value parameters.\n#define GMOCK_INTERNAL_DEFN_AND_0_VALUE_PARAMS()\n#define GMOCK_INTERNAL_DEFN_AND_1_VALUE_PARAMS(p0) p0##_type p0;\n#define GMOCK_INTERNAL_DEFN_AND_2_VALUE_PARAMS(p0, p1) \\\n  p0##_type p0;                                        \\\n  p1##_type p1;\n#define GMOCK_INTERNAL_DEFN_AND_3_VALUE_PARAMS(p0, p1, p2) \\\n  p0##_type p0;                                            \\\n  p1##_type p1;                                            \\\n  p2##_type p2;\n#define GMOCK_INTERNAL_DEFN_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \\\n  p0##_type p0;                                                \\\n  p1##_type p1;                                                \\\n  p2##_type p2;                                                \\\n  p3##_type p3;\n#define GMOCK_INTERNAL_DEFN_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \\\n  p0##_type p0;                                                    \\\n  p1##_type p1;                                                    \\\n  p2##_type p2;                                                    \\\n  p3##_type p3;                                                    \\\n  p4##_type p4;\n#define GMOCK_INTERNAL_DEFN_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \\\n  p0##_type p0;                                                        \\\n  p1##_type p1;                                                        \\\n  p2##_type p2;                                                        \\\n  p3##_type p3;                                                        \\\n  p4##_type p4;                                                        \\\n  p5##_type p5;\n#define GMOCK_INTERNAL_DEFN_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \\\n  p0##_type p0;                                                            \\\n  p1##_type p1;                                                            \\\n  p2##_type p2;                                                            \\\n  p3##_type p3;                                                            \\\n  p4##_type p4;                                                            \\\n  p5##_type p5;                                                            \\\n  p6##_type p6;\n#define GMOCK_INTERNAL_DEFN_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \\\n  p0##_type p0;                                                                \\\n  p1##_type p1;                                                                \\\n  p2##_type p2;                                                                \\\n  p3##_type p3;                                                                \\\n  p4##_type p4;                                                                \\\n  p5##_type p5;                                                                \\\n  p6##_type p6;                                                                \\\n  p7##_type p7;\n#define GMOCK_INTERNAL_DEFN_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \\\n                                               p8)                             \\\n  p0##_type p0;                                                                \\\n  p1##_type p1;                                                                \\\n  p2##_type p2;                                                                \\\n  p3##_type p3;                                                                \\\n  p4##_type p4;                                                                \\\n  p5##_type p5;                                                                \\\n  p6##_type p6;                                                                \\\n  p7##_type p7;                                                                \\\n  p8##_type p8;\n#define GMOCK_INTERNAL_DEFN_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \\\n                                                p7, p8, p9)                 \\\n  p0##_type p0;                                                             \\\n  p1##_type p1;                                                             \\\n  p2##_type p2;                                                             \\\n  p3##_type p3;                                                             \\\n  p4##_type p4;                                                             \\\n  p5##_type p5;                                                             \\\n  p6##_type p6;                                                             \\\n  p7##_type p7;                                                             \\\n  p8##_type p8;                                                             \\\n  p9##_type p9;\n\n// Lists the value parameters.\n#define GMOCK_INTERNAL_LIST_AND_0_VALUE_PARAMS()\n#define GMOCK_INTERNAL_LIST_AND_1_VALUE_PARAMS(p0) p0\n#define GMOCK_INTERNAL_LIST_AND_2_VALUE_PARAMS(p0, p1) p0, p1\n#define GMOCK_INTERNAL_LIST_AND_3_VALUE_PARAMS(p0, p1, p2) p0, p1, p2\n#define GMOCK_INTERNAL_LIST_AND_4_VALUE_PARAMS(p0, p1, p2, p3) p0, p1, p2, p3\n#define GMOCK_INTERNAL_LIST_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \\\n  p0, p1, p2, p3, p4\n#define GMOCK_INTERNAL_LIST_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \\\n  p0, p1, p2, p3, p4, p5\n#define GMOCK_INTERNAL_LIST_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \\\n  p0, p1, p2, p3, p4, p5, p6\n#define GMOCK_INTERNAL_LIST_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \\\n  p0, p1, p2, p3, p4, p5, p6, p7\n#define GMOCK_INTERNAL_LIST_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \\\n                                               p8)                             \\\n  p0, p1, p2, p3, p4, p5, p6, p7, p8\n#define GMOCK_INTERNAL_LIST_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \\\n                                                p7, p8, p9)                 \\\n  p0, p1, p2, p3, p4, p5, p6, p7, p8, p9\n\n// Lists the value parameter types.\n#define GMOCK_INTERNAL_LIST_TYPE_AND_0_VALUE_PARAMS()\n#define GMOCK_INTERNAL_LIST_TYPE_AND_1_VALUE_PARAMS(p0) , p0##_type\n#define GMOCK_INTERNAL_LIST_TYPE_AND_2_VALUE_PARAMS(p0, p1) \\\n  , p0##_type, p1##_type\n#define GMOCK_INTERNAL_LIST_TYPE_AND_3_VALUE_PARAMS(p0, p1, p2) \\\n  , p0##_type, p1##_type, p2##_type\n#define GMOCK_INTERNAL_LIST_TYPE_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \\\n  , p0##_type, p1##_type, p2##_type, p3##_type\n#define GMOCK_INTERNAL_LIST_TYPE_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \\\n  , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type\n#define GMOCK_INTERNAL_LIST_TYPE_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) \\\n  , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type\n#define GMOCK_INTERNAL_LIST_TYPE_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \\\n                                                    p6)                     \\\n  , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type, p6##_type\n#define GMOCK_INTERNAL_LIST_TYPE_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \\\n                                                    p6, p7)                 \\\n  , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type,       \\\n      p6##_type, p7##_type\n#define GMOCK_INTERNAL_LIST_TYPE_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \\\n                                                    p6, p7, p8)             \\\n  , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type,       \\\n      p6##_type, p7##_type, p8##_type\n#define GMOCK_INTERNAL_LIST_TYPE_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, \\\n                                                     p6, p7, p8, p9)         \\\n  , p0##_type, p1##_type, p2##_type, p3##_type, p4##_type, p5##_type,        \\\n      p6##_type, p7##_type, p8##_type, p9##_type\n\n// Declares the value parameters.\n#define GMOCK_INTERNAL_DECL_AND_0_VALUE_PARAMS()\n#define GMOCK_INTERNAL_DECL_AND_1_VALUE_PARAMS(p0) p0##_type p0\n#define GMOCK_INTERNAL_DECL_AND_2_VALUE_PARAMS(p0, p1) \\\n  p0##_type p0, p1##_type p1\n#define GMOCK_INTERNAL_DECL_AND_3_VALUE_PARAMS(p0, p1, p2) \\\n  p0##_type p0, p1##_type p1, p2##_type p2\n#define GMOCK_INTERNAL_DECL_AND_4_VALUE_PARAMS(p0, p1, p2, p3) \\\n  p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3\n#define GMOCK_INTERNAL_DECL_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) \\\n  p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4\n#define GMOCK_INTERNAL_DECL_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5)  \\\n  p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4, \\\n      p5##_type p5\n#define GMOCK_INTERNAL_DECL_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) \\\n  p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4,    \\\n      p5##_type p5, p6##_type p6\n#define GMOCK_INTERNAL_DECL_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7) \\\n  p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4,        \\\n      p5##_type p5, p6##_type p6, p7##_type p7\n#define GMOCK_INTERNAL_DECL_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, p7, \\\n                                               p8)                             \\\n  p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4,        \\\n      p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8\n#define GMOCK_INTERNAL_DECL_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \\\n                                                p7, p8, p9)                 \\\n  p0##_type p0, p1##_type p1, p2##_type p2, p3##_type p3, p4##_type p4,     \\\n      p5##_type p5, p6##_type p6, p7##_type p7, p8##_type p8, p9##_type p9\n\n// The suffix of the class template implementing the action template.\n#define GMOCK_INTERNAL_COUNT_AND_0_VALUE_PARAMS()\n#define GMOCK_INTERNAL_COUNT_AND_1_VALUE_PARAMS(p0) P\n#define GMOCK_INTERNAL_COUNT_AND_2_VALUE_PARAMS(p0, p1) P2\n#define GMOCK_INTERNAL_COUNT_AND_3_VALUE_PARAMS(p0, p1, p2) P3\n#define GMOCK_INTERNAL_COUNT_AND_4_VALUE_PARAMS(p0, p1, p2, p3) P4\n#define GMOCK_INTERNAL_COUNT_AND_5_VALUE_PARAMS(p0, p1, p2, p3, p4) P5\n#define GMOCK_INTERNAL_COUNT_AND_6_VALUE_PARAMS(p0, p1, p2, p3, p4, p5) P6\n#define GMOCK_INTERNAL_COUNT_AND_7_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6) P7\n#define GMOCK_INTERNAL_COUNT_AND_8_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \\\n                                                p7)                         \\\n  P8\n#define GMOCK_INTERNAL_COUNT_AND_9_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \\\n                                                p7, p8)                     \\\n  P9\n#define GMOCK_INTERNAL_COUNT_AND_10_VALUE_PARAMS(p0, p1, p2, p3, p4, p5, p6, \\\n                                                 p7, p8, p9)                 \\\n  P10\n\n// The name of the class template implementing the action template.\n#define GMOCK_ACTION_CLASS_(name, value_params) \\\n  GTEST_CONCAT_TOKEN_(name##Action, GMOCK_INTERNAL_COUNT_##value_params)\n\n#define ACTION_TEMPLATE(name, template_params, value_params)                   \\\n  template <GMOCK_INTERNAL_DECL_##template_params                              \\\n                GMOCK_INTERNAL_DECL_TYPE_##value_params>                       \\\n  class GMOCK_ACTION_CLASS_(name, value_params) {                              \\\n   public:                                                                     \\\n    explicit GMOCK_ACTION_CLASS_(name, value_params)(                          \\\n        GMOCK_INTERNAL_DECL_##value_params)                                    \\\n        GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params),    \\\n                    = default;                                                 \\\n                    ,                                                          \\\n                    : impl_(std::make_shared<gmock_Impl>(                      \\\n                        GMOCK_INTERNAL_LIST_##value_params)){})                \\\n            GMOCK_ACTION_CLASS_(name, value_params)(const GMOCK_ACTION_CLASS_( \\\n                name, value_params) &) noexcept GMOCK_INTERNAL_DEFN_COPY_      \\\n        ##value_params GMOCK_ACTION_CLASS_(name, value_params)(                \\\n            GMOCK_ACTION_CLASS_(name, value_params) &&) noexcept               \\\n        GMOCK_INTERNAL_DEFN_COPY_##value_params template <typename F>          \\\n        operator ::testing::Action<F>() const {                                \\\n      return GMOCK_PP_IF(                                                      \\\n          GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params),              \\\n          (::testing::internal::MakeAction<F, gmock_Impl>()),                  \\\n          (::testing::internal::MakeAction<F>(impl_)));                        \\\n    }                                                                          \\\n                                                                               \\\n   private:                                                                    \\\n    class gmock_Impl {                                                         \\\n     public:                                                                   \\\n      explicit gmock_Impl GMOCK_INTERNAL_INIT_##value_params {}                \\\n      template <typename function_type, typename return_type,                  \\\n                typename args_type, GMOCK_ACTION_TEMPLATE_ARGS_NAMES_>         \\\n      return_type gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_) const;  \\\n      GMOCK_INTERNAL_DEFN_##value_params                                       \\\n    };                                                                         \\\n    GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(GMOCK_INTERNAL_COUNT_##value_params), ,      \\\n                std::shared_ptr<const gmock_Impl> impl_;)                      \\\n  };                                                                           \\\n  template <GMOCK_INTERNAL_DECL_##template_params                              \\\n                GMOCK_INTERNAL_DECL_TYPE_##value_params>                       \\\n  GMOCK_ACTION_CLASS_(                                                         \\\n      name, value_params)<GMOCK_INTERNAL_LIST_##template_params                \\\n                              GMOCK_INTERNAL_LIST_TYPE_##value_params>         \\\n      name(GMOCK_INTERNAL_DECL_##value_params) GTEST_MUST_USE_RESULT_;         \\\n  template <GMOCK_INTERNAL_DECL_##template_params                              \\\n                GMOCK_INTERNAL_DECL_TYPE_##value_params>                       \\\n  inline GMOCK_ACTION_CLASS_(                                                  \\\n      name, value_params)<GMOCK_INTERNAL_LIST_##template_params                \\\n                              GMOCK_INTERNAL_LIST_TYPE_##value_params>         \\\n  name(GMOCK_INTERNAL_DECL_##value_params) {                                   \\\n    return GMOCK_ACTION_CLASS_(                                                \\\n        name, value_params)<GMOCK_INTERNAL_LIST_##template_params              \\\n                                GMOCK_INTERNAL_LIST_TYPE_##value_params>(      \\\n        GMOCK_INTERNAL_LIST_##value_params);                                   \\\n  }                                                                            \\\n  template <GMOCK_INTERNAL_DECL_##template_params                              \\\n                GMOCK_INTERNAL_DECL_TYPE_##value_params>                       \\\n  template <typename function_type, typename return_type, typename args_type,  \\\n            GMOCK_ACTION_TEMPLATE_ARGS_NAMES_>                                 \\\n  return_type GMOCK_ACTION_CLASS_(                                             \\\n      name, value_params)<GMOCK_INTERNAL_LIST_##template_params                \\\n                              GMOCK_INTERNAL_LIST_TYPE_##value_params>::       \\\n      gmock_Impl::gmock_PerformImpl(GMOCK_ACTION_ARG_TYPES_AND_NAMES_UNUSED_)  \\\n          const\n\nnamespace testing {\n\n// The ACTION*() macros trigger warning C4100 (unreferenced formal\n// parameter) in MSVC with -W4.  Unfortunately they cannot be fixed in\n// the macro definition, as the warnings are generated when the macro\n// is expanded and macro expansion cannot contain #pragma.  Therefore\n// we suppress them here.\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 4100)\n#endif\n\nnamespace internal {\n\n// internal::InvokeArgument - a helper for InvokeArgument action.\n// The basic overloads are provided here for generic functors.\n// Overloads for other custom-callables are provided in the\n// internal/custom/gmock-generated-actions.h header.\ntemplate <typename F, typename... Args>\nauto InvokeArgument(F f, Args... args) -> decltype(f(args...)) {\n  return f(args...);\n}\n\ntemplate <std::size_t index, typename... Params>\nstruct InvokeArgumentAction {\n  template <typename... Args,\n            typename = typename std::enable_if<(index < sizeof...(Args))>::type>\n  auto operator()(Args&&... args) const -> decltype(internal::InvokeArgument(\n      std::get<index>(std::forward_as_tuple(std::forward<Args>(args)...)),\n      std::declval<const Params&>()...)) {\n    internal::FlatTuple<Args&&...> args_tuple(FlatTupleConstructTag{},\n                                              std::forward<Args>(args)...);\n    return params.Apply([&](const Params&... unpacked_params) {\n      auto&& callable = args_tuple.template Get<index>();\n      return internal::InvokeArgument(\n          std::forward<decltype(callable)>(callable), unpacked_params...);\n    });\n  }\n\n  internal::FlatTuple<Params...> params;\n};\n\n}  // namespace internal\n\n// The InvokeArgument<N>(a1, a2, ..., a_k) action invokes the N-th\n// (0-based) argument, which must be a k-ary callable, of the mock\n// function, with arguments a1, a2, ..., a_k.\n//\n// Notes:\n//\n//   1. The arguments are passed by value by default.  If you need to\n//   pass an argument by reference, wrap it inside std::ref().  For\n//   example,\n//\n//     InvokeArgument<1>(5, string(\"Hello\"), std::ref(foo))\n//\n//   passes 5 and string(\"Hello\") by value, and passes foo by\n//   reference.\n//\n//   2. If the callable takes an argument by reference but std::ref() is\n//   not used, it will receive the reference to a copy of the value,\n//   instead of the original value.  For example, when the 0-th\n//   argument of the mock function takes a const string&, the action\n//\n//     InvokeArgument<0>(string(\"Hello\"))\n//\n//   makes a copy of the temporary string(\"Hello\") object and passes a\n//   reference of the copy, instead of the original temporary object,\n//   to the callable.  This makes it easy for a user to define an\n//   InvokeArgument action from temporary values and have it performed\n//   later.\ntemplate <std::size_t index, typename... Params>\ninternal::InvokeArgumentAction<index, typename std::decay<Params>::type...>\nInvokeArgument(Params&&... params) {\n  return {internal::FlatTuple<typename std::decay<Params>::type...>(\n      internal::FlatTupleConstructTag{}, std::forward<Params>(params)...)};\n}\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n}  // namespace testing\n\n#endif  // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_ACTIONS_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/include/gmock/gmock-more-matchers.h",
    "content": "// Copyright 2013, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file implements some matchers that depend on gmock-matchers.h.\n//\n// Note that tests are implemented in gmock-matchers_test.cc rather than\n// gmock-more-matchers-test.cc.\n\n// IWYU pragma: private, include \"gmock/gmock.h\"\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_\n#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_\n\n#include \"gmock/gmock-matchers.h\"\n\nnamespace testing {\n\n// Silence C4100 (unreferenced formal\n// parameter) for MSVC\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 4100)\n#if (_MSC_VER == 1900)\n// and silence C4800 (C4800: 'int *const ': forcing value\n// to bool 'true' or 'false') for MSVC 14\n#pragma warning(disable : 4800)\n#endif\n#endif\n\n// Defines a matcher that matches an empty container. The container must\n// support both size() and empty(), which all STL-like containers provide.\nMATCHER(IsEmpty, negation ? \"isn't empty\" : \"is empty\") {\n  if (arg.empty()) {\n    return true;\n  }\n  *result_listener << \"whose size is \" << arg.size();\n  return false;\n}\n\n// Define a matcher that matches a value that evaluates in boolean\n// context to true.  Useful for types that define \"explicit operator\n// bool\" operators and so can't be compared for equality with true\n// and false.\nMATCHER(IsTrue, negation ? \"is false\" : \"is true\") {\n  return static_cast<bool>(arg);\n}\n\n// Define a matcher that matches a value that evaluates in boolean\n// context to false.  Useful for types that define \"explicit operator\n// bool\" operators and so can't be compared for equality with true\n// and false.\nMATCHER(IsFalse, negation ? \"is true\" : \"is false\") {\n  return !static_cast<bool>(arg);\n}\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n}  // namespace testing\n\n#endif  // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_MORE_MATCHERS_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/include/gmock/gmock-nice-strict.h",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Implements class templates NiceMock, NaggyMock, and StrictMock.\n//\n// Given a mock class MockFoo that is created using Google Mock,\n// NiceMock<MockFoo> is a subclass of MockFoo that allows\n// uninteresting calls (i.e. calls to mock methods that have no\n// EXPECT_CALL specs), NaggyMock<MockFoo> is a subclass of MockFoo\n// that prints a warning when an uninteresting call occurs, and\n// StrictMock<MockFoo> is a subclass of MockFoo that treats all\n// uninteresting calls as errors.\n//\n// Currently a mock is naggy by default, so MockFoo and\n// NaggyMock<MockFoo> behave like the same.  However, we will soon\n// switch the default behavior of mocks to be nice, as that in general\n// leads to more maintainable tests.  When that happens, MockFoo will\n// stop behaving like NaggyMock<MockFoo> and start behaving like\n// NiceMock<MockFoo>.\n//\n// NiceMock, NaggyMock, and StrictMock \"inherit\" the constructors of\n// their respective base class.  Therefore you can write\n// NiceMock<MockFoo>(5, \"a\") to construct a nice mock where MockFoo\n// has a constructor that accepts (int, const char*), for example.\n//\n// A known limitation is that NiceMock<MockFoo>, NaggyMock<MockFoo>,\n// and StrictMock<MockFoo> only works for mock methods defined using\n// the MOCK_METHOD* family of macros DIRECTLY in the MockFoo class.\n// If a mock method is defined in a base class of MockFoo, the \"nice\"\n// or \"strict\" modifier may not affect it, depending on the compiler.\n// In particular, nesting NiceMock, NaggyMock, and StrictMock is NOT\n// supported.\n\n// IWYU pragma: private, include \"gmock/gmock.h\"\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_\n#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_\n\n#include <cstdint>\n#include <type_traits>\n\n#include \"gmock/gmock-spec-builders.h\"\n#include \"gmock/internal/gmock-port.h\"\n\nnamespace testing {\ntemplate <class MockClass>\nclass NiceMock;\ntemplate <class MockClass>\nclass NaggyMock;\ntemplate <class MockClass>\nclass StrictMock;\n\nnamespace internal {\ntemplate <typename T>\nstd::true_type StrictnessModifierProbe(const NiceMock<T>&);\ntemplate <typename T>\nstd::true_type StrictnessModifierProbe(const NaggyMock<T>&);\ntemplate <typename T>\nstd::true_type StrictnessModifierProbe(const StrictMock<T>&);\nstd::false_type StrictnessModifierProbe(...);\n\ntemplate <typename T>\nconstexpr bool HasStrictnessModifier() {\n  return decltype(StrictnessModifierProbe(std::declval<const T&>()))::value;\n}\n\n// Base classes that register and deregister with testing::Mock to alter the\n// default behavior around uninteresting calls. Inheriting from one of these\n// classes first and then MockClass ensures the MockClass constructor is run\n// after registration, and that the MockClass destructor runs before\n// deregistration. This guarantees that MockClass's constructor and destructor\n// run with the same level of strictness as its instance methods.\n\n#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW && \\\n    (defined(_MSC_VER) || defined(__clang__))\n// We need to mark these classes with this declspec to ensure that\n// the empty base class optimization is performed.\n#define GTEST_INTERNAL_EMPTY_BASE_CLASS __declspec(empty_bases)\n#else\n#define GTEST_INTERNAL_EMPTY_BASE_CLASS\n#endif\n\ntemplate <typename Base>\nclass NiceMockImpl {\n public:\n  NiceMockImpl() {\n    ::testing::Mock::AllowUninterestingCalls(reinterpret_cast<uintptr_t>(this));\n  }\n\n  ~NiceMockImpl() {\n    ::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this));\n  }\n};\n\ntemplate <typename Base>\nclass NaggyMockImpl {\n public:\n  NaggyMockImpl() {\n    ::testing::Mock::WarnUninterestingCalls(reinterpret_cast<uintptr_t>(this));\n  }\n\n  ~NaggyMockImpl() {\n    ::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this));\n  }\n};\n\ntemplate <typename Base>\nclass StrictMockImpl {\n public:\n  StrictMockImpl() {\n    ::testing::Mock::FailUninterestingCalls(reinterpret_cast<uintptr_t>(this));\n  }\n\n  ~StrictMockImpl() {\n    ::testing::Mock::UnregisterCallReaction(reinterpret_cast<uintptr_t>(this));\n  }\n};\n\n}  // namespace internal\n\ntemplate <class MockClass>\nclass GTEST_INTERNAL_EMPTY_BASE_CLASS NiceMock\n    : private internal::NiceMockImpl<MockClass>,\n      public MockClass {\n public:\n  static_assert(!internal::HasStrictnessModifier<MockClass>(),\n                \"Can't apply NiceMock to a class hierarchy that already has a \"\n                \"strictness modifier. See \"\n                \"https://google.github.io/googletest/\"\n                \"gmock_cook_book.html#NiceStrictNaggy\");\n  NiceMock() : MockClass() {\n    static_assert(sizeof(*this) == sizeof(MockClass),\n                  \"The impl subclass shouldn't introduce any padding\");\n  }\n\n  // Ideally, we would inherit base class's constructors through a using\n  // declaration, which would preserve their visibility. However, many existing\n  // tests rely on the fact that current implementation reexports protected\n  // constructors as public. These tests would need to be cleaned up first.\n\n  // Single argument constructor is special-cased so that it can be\n  // made explicit.\n  template <typename A>\n  explicit NiceMock(A&& arg) : MockClass(std::forward<A>(arg)) {\n    static_assert(sizeof(*this) == sizeof(MockClass),\n                  \"The impl subclass shouldn't introduce any padding\");\n  }\n\n  template <typename TArg1, typename TArg2, typename... An>\n  NiceMock(TArg1&& arg1, TArg2&& arg2, An&&... args)\n      : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2),\n                  std::forward<An>(args)...) {\n    static_assert(sizeof(*this) == sizeof(MockClass),\n                  \"The impl subclass shouldn't introduce any padding\");\n  }\n\n private:\n  NiceMock(const NiceMock&) = delete;\n  NiceMock& operator=(const NiceMock&) = delete;\n};\n\ntemplate <class MockClass>\nclass GTEST_INTERNAL_EMPTY_BASE_CLASS NaggyMock\n    : private internal::NaggyMockImpl<MockClass>,\n      public MockClass {\n  static_assert(!internal::HasStrictnessModifier<MockClass>(),\n                \"Can't apply NaggyMock to a class hierarchy that already has a \"\n                \"strictness modifier. See \"\n                \"https://google.github.io/googletest/\"\n                \"gmock_cook_book.html#NiceStrictNaggy\");\n\n public:\n  NaggyMock() : MockClass() {\n    static_assert(sizeof(*this) == sizeof(MockClass),\n                  \"The impl subclass shouldn't introduce any padding\");\n  }\n\n  // Ideally, we would inherit base class's constructors through a using\n  // declaration, which would preserve their visibility. However, many existing\n  // tests rely on the fact that current implementation reexports protected\n  // constructors as public. These tests would need to be cleaned up first.\n\n  // Single argument constructor is special-cased so that it can be\n  // made explicit.\n  template <typename A>\n  explicit NaggyMock(A&& arg) : MockClass(std::forward<A>(arg)) {\n    static_assert(sizeof(*this) == sizeof(MockClass),\n                  \"The impl subclass shouldn't introduce any padding\");\n  }\n\n  template <typename TArg1, typename TArg2, typename... An>\n  NaggyMock(TArg1&& arg1, TArg2&& arg2, An&&... args)\n      : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2),\n                  std::forward<An>(args)...) {\n    static_assert(sizeof(*this) == sizeof(MockClass),\n                  \"The impl subclass shouldn't introduce any padding\");\n  }\n\n private:\n  NaggyMock(const NaggyMock&) = delete;\n  NaggyMock& operator=(const NaggyMock&) = delete;\n};\n\ntemplate <class MockClass>\nclass GTEST_INTERNAL_EMPTY_BASE_CLASS StrictMock\n    : private internal::StrictMockImpl<MockClass>,\n      public MockClass {\n public:\n  static_assert(\n      !internal::HasStrictnessModifier<MockClass>(),\n      \"Can't apply StrictMock to a class hierarchy that already has a \"\n      \"strictness modifier. See \"\n      \"https://google.github.io/googletest/\"\n      \"gmock_cook_book.html#NiceStrictNaggy\");\n  StrictMock() : MockClass() {\n    static_assert(sizeof(*this) == sizeof(MockClass),\n                  \"The impl subclass shouldn't introduce any padding\");\n  }\n\n  // Ideally, we would inherit base class's constructors through a using\n  // declaration, which would preserve their visibility. However, many existing\n  // tests rely on the fact that current implementation reexports protected\n  // constructors as public. These tests would need to be cleaned up first.\n\n  // Single argument constructor is special-cased so that it can be\n  // made explicit.\n  template <typename A>\n  explicit StrictMock(A&& arg) : MockClass(std::forward<A>(arg)) {\n    static_assert(sizeof(*this) == sizeof(MockClass),\n                  \"The impl subclass shouldn't introduce any padding\");\n  }\n\n  template <typename TArg1, typename TArg2, typename... An>\n  StrictMock(TArg1&& arg1, TArg2&& arg2, An&&... args)\n      : MockClass(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2),\n                  std::forward<An>(args)...) {\n    static_assert(sizeof(*this) == sizeof(MockClass),\n                  \"The impl subclass shouldn't introduce any padding\");\n  }\n\n private:\n  StrictMock(const StrictMock&) = delete;\n  StrictMock& operator=(const StrictMock&) = delete;\n};\n\n#undef GTEST_INTERNAL_EMPTY_BASE_CLASS\n\n}  // namespace testing\n\n#endif  // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_NICE_STRICT_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/include/gmock/gmock-spec-builders.h",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file implements the ON_CALL() and EXPECT_CALL() macros.\n//\n// A user can use the ON_CALL() macro to specify the default action of\n// a mock method.  The syntax is:\n//\n//   ON_CALL(mock_object, Method(argument-matchers))\n//       .With(multi-argument-matcher)\n//       .WillByDefault(action);\n//\n//  where the .With() clause is optional.\n//\n// A user can use the EXPECT_CALL() macro to specify an expectation on\n// a mock method.  The syntax is:\n//\n//   EXPECT_CALL(mock_object, Method(argument-matchers))\n//       .With(multi-argument-matchers)\n//       .Times(cardinality)\n//       .InSequence(sequences)\n//       .After(expectations)\n//       .WillOnce(action)\n//       .WillRepeatedly(action)\n//       .RetiresOnSaturation();\n//\n// where all clauses are optional, and .InSequence()/.After()/\n// .WillOnce() can appear any number of times.\n\n// IWYU pragma: private, include \"gmock/gmock.h\"\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_\n#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_\n\n#include <cstdint>\n#include <functional>\n#include <map>\n#include <memory>\n#include <set>\n#include <sstream>\n#include <string>\n#include <type_traits>\n#include <utility>\n#include <vector>\n\n#include \"gmock/gmock-actions.h\"\n#include \"gmock/gmock-cardinalities.h\"\n#include \"gmock/gmock-matchers.h\"\n#include \"gmock/internal/gmock-internal-utils.h\"\n#include \"gmock/internal/gmock-port.h\"\n#include \"gtest/gtest.h\"\n\n#if GTEST_HAS_EXCEPTIONS\n#include <stdexcept>  // NOLINT\n#endif\n\nGTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \\\n/* class A needs to have dll-interface to be used by clients of class B */)\n\nnamespace testing {\n\n// An abstract handle of an expectation.\nclass Expectation;\n\n// A set of expectation handles.\nclass ExpectationSet;\n\n// Anything inside the 'internal' namespace IS INTERNAL IMPLEMENTATION\n// and MUST NOT BE USED IN USER CODE!!!\nnamespace internal {\n\n// Implements a mock function.\ntemplate <typename F>\nclass FunctionMocker;\n\n// Base class for expectations.\nclass ExpectationBase;\n\n// Implements an expectation.\ntemplate <typename F>\nclass TypedExpectation;\n\n// Helper class for testing the Expectation class template.\nclass ExpectationTester;\n\n// Helper classes for implementing NiceMock, StrictMock, and NaggyMock.\ntemplate <typename MockClass>\nclass NiceMockImpl;\ntemplate <typename MockClass>\nclass StrictMockImpl;\ntemplate <typename MockClass>\nclass NaggyMockImpl;\n\n// Protects the mock object registry (in class Mock), all function\n// mockers, and all expectations.\n//\n// The reason we don't use more fine-grained protection is: when a\n// mock function Foo() is called, it needs to consult its expectations\n// to see which one should be picked.  If another thread is allowed to\n// call a mock function (either Foo() or a different one) at the same\n// time, it could affect the \"retired\" attributes of Foo()'s\n// expectations when InSequence() is used, and thus affect which\n// expectation gets picked.  Therefore, we sequence all mock function\n// calls to ensure the integrity of the mock objects' states.\nGTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);\n\n// Abstract base class of FunctionMocker.  This is the\n// type-agnostic part of the function mocker interface.  Its pure\n// virtual methods are implemented by FunctionMocker.\nclass GTEST_API_ UntypedFunctionMockerBase {\n public:\n  UntypedFunctionMockerBase();\n  virtual ~UntypedFunctionMockerBase();\n\n  // Verifies that all expectations on this mock function have been\n  // satisfied.  Reports one or more Google Test non-fatal failures\n  // and returns false if not.\n  bool VerifyAndClearExpectationsLocked()\n      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);\n\n  // Clears the ON_CALL()s set on this mock function.\n  virtual void ClearDefaultActionsLocked()\n      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;\n\n  // In all of the following Untyped* functions, it's the caller's\n  // responsibility to guarantee the correctness of the arguments'\n  // types.\n\n  // Writes a message that the call is uninteresting (i.e. neither\n  // explicitly expected nor explicitly unexpected) to the given\n  // ostream.\n  virtual void UntypedDescribeUninterestingCall(const void* untyped_args,\n                                                ::std::ostream* os) const\n      GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;\n\n  // Returns the expectation that matches the given function arguments\n  // (or NULL is there's no match); when a match is found,\n  // untyped_action is set to point to the action that should be\n  // performed (or NULL if the action is \"do default\"), and\n  // is_excessive is modified to indicate whether the call exceeds the\n  // expected number.\n  virtual const ExpectationBase* UntypedFindMatchingExpectation(\n      const void* untyped_args, const void** untyped_action, bool* is_excessive,\n      ::std::ostream* what, ::std::ostream* why)\n      GTEST_LOCK_EXCLUDED_(g_gmock_mutex) = 0;\n\n  // Prints the given function arguments to the ostream.\n  virtual void UntypedPrintArgs(const void* untyped_args,\n                                ::std::ostream* os) const = 0;\n\n  // Sets the mock object this mock method belongs to, and registers\n  // this information in the global mock registry.  Will be called\n  // whenever an EXPECT_CALL() or ON_CALL() is executed on this mock\n  // method.\n  void RegisterOwner(const void* mock_obj) GTEST_LOCK_EXCLUDED_(g_gmock_mutex);\n\n  // Sets the mock object this mock method belongs to, and sets the\n  // name of the mock function.  Will be called upon each invocation\n  // of this mock function.\n  void SetOwnerAndName(const void* mock_obj, const char* name)\n      GTEST_LOCK_EXCLUDED_(g_gmock_mutex);\n\n  // Returns the mock object this mock method belongs to.  Must be\n  // called after RegisterOwner() or SetOwnerAndName() has been\n  // called.\n  const void* MockObject() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex);\n\n  // Returns the name of this mock method.  Must be called after\n  // SetOwnerAndName() has been called.\n  const char* Name() const GTEST_LOCK_EXCLUDED_(g_gmock_mutex);\n\n protected:\n  typedef std::vector<const void*> UntypedOnCallSpecs;\n\n  using UntypedExpectations = std::vector<std::shared_ptr<ExpectationBase>>;\n\n  // Returns an Expectation object that references and co-owns exp,\n  // which must be an expectation on this mock function.\n  Expectation GetHandleOf(ExpectationBase* exp);\n\n  // Address of the mock object this mock method belongs to.  Only\n  // valid after this mock method has been called or\n  // ON_CALL/EXPECT_CALL has been invoked on it.\n  const void* mock_obj_;  // Protected by g_gmock_mutex.\n\n  // Name of the function being mocked.  Only valid after this mock\n  // method has been called.\n  const char* name_;  // Protected by g_gmock_mutex.\n\n  // All default action specs for this function mocker.\n  UntypedOnCallSpecs untyped_on_call_specs_;\n\n  // All expectations for this function mocker.\n  //\n  // It's undefined behavior to interleave expectations (EXPECT_CALLs\n  // or ON_CALLs) and mock function calls.  Also, the order of\n  // expectations is important.  Therefore it's a logic race condition\n  // to read/write untyped_expectations_ concurrently.  In order for\n  // tools like tsan to catch concurrent read/write accesses to\n  // untyped_expectations, we deliberately leave accesses to it\n  // unprotected.\n  UntypedExpectations untyped_expectations_;\n};  // class UntypedFunctionMockerBase\n\n// Untyped base class for OnCallSpec<F>.\nclass UntypedOnCallSpecBase {\n public:\n  // The arguments are the location of the ON_CALL() statement.\n  UntypedOnCallSpecBase(const char* a_file, int a_line)\n      : file_(a_file), line_(a_line), last_clause_(kNone) {}\n\n  // Where in the source file was the default action spec defined?\n  const char* file() const { return file_; }\n  int line() const { return line_; }\n\n protected:\n  // Gives each clause in the ON_CALL() statement a name.\n  enum Clause {\n    // Do not change the order of the enum members!  The run-time\n    // syntax checking relies on it.\n    kNone,\n    kWith,\n    kWillByDefault\n  };\n\n  // Asserts that the ON_CALL() statement has a certain property.\n  void AssertSpecProperty(bool property,\n                          const std::string& failure_message) const {\n    Assert(property, file_, line_, failure_message);\n  }\n\n  // Expects that the ON_CALL() statement has a certain property.\n  void ExpectSpecProperty(bool property,\n                          const std::string& failure_message) const {\n    Expect(property, file_, line_, failure_message);\n  }\n\n  const char* file_;\n  int line_;\n\n  // The last clause in the ON_CALL() statement as seen so far.\n  // Initially kNone and changes as the statement is parsed.\n  Clause last_clause_;\n};  // class UntypedOnCallSpecBase\n\n// This template class implements an ON_CALL spec.\ntemplate <typename F>\nclass OnCallSpec : public UntypedOnCallSpecBase {\n public:\n  typedef typename Function<F>::ArgumentTuple ArgumentTuple;\n  typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;\n\n  // Constructs an OnCallSpec object from the information inside\n  // the parenthesis of an ON_CALL() statement.\n  OnCallSpec(const char* a_file, int a_line,\n             const ArgumentMatcherTuple& matchers)\n      : UntypedOnCallSpecBase(a_file, a_line),\n        matchers_(matchers),\n        // By default, extra_matcher_ should match anything.  However,\n        // we cannot initialize it with _ as that causes ambiguity between\n        // Matcher's copy and move constructor for some argument types.\n        extra_matcher_(A<const ArgumentTuple&>()) {}\n\n  // Implements the .With() clause.\n  OnCallSpec& With(const Matcher<const ArgumentTuple&>& m) {\n    // Makes sure this is called at most once.\n    ExpectSpecProperty(last_clause_ < kWith,\n                       \".With() cannot appear \"\n                       \"more than once in an ON_CALL().\");\n    last_clause_ = kWith;\n\n    extra_matcher_ = m;\n    return *this;\n  }\n\n  // Implements the .WillByDefault() clause.\n  OnCallSpec& WillByDefault(const Action<F>& action) {\n    ExpectSpecProperty(last_clause_ < kWillByDefault,\n                       \".WillByDefault() must appear \"\n                       \"exactly once in an ON_CALL().\");\n    last_clause_ = kWillByDefault;\n\n    ExpectSpecProperty(!action.IsDoDefault(),\n                       \"DoDefault() cannot be used in ON_CALL().\");\n    action_ = action;\n    return *this;\n  }\n\n  // Returns true if and only if the given arguments match the matchers.\n  bool Matches(const ArgumentTuple& args) const {\n    return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);\n  }\n\n  // Returns the action specified by the user.\n  const Action<F>& GetAction() const {\n    AssertSpecProperty(last_clause_ == kWillByDefault,\n                       \".WillByDefault() must appear exactly \"\n                       \"once in an ON_CALL().\");\n    return action_;\n  }\n\n private:\n  // The information in statement\n  //\n  //   ON_CALL(mock_object, Method(matchers))\n  //       .With(multi-argument-matcher)\n  //       .WillByDefault(action);\n  //\n  // is recorded in the data members like this:\n  //\n  //   source file that contains the statement => file_\n  //   line number of the statement            => line_\n  //   matchers                                => matchers_\n  //   multi-argument-matcher                  => extra_matcher_\n  //   action                                  => action_\n  ArgumentMatcherTuple matchers_;\n  Matcher<const ArgumentTuple&> extra_matcher_;\n  Action<F> action_;\n};  // class OnCallSpec\n\n// Possible reactions on uninteresting calls.\nenum CallReaction {\n  kAllow,\n  kWarn,\n  kFail,\n};\n\n}  // namespace internal\n\n// Utilities for manipulating mock objects.\nclass GTEST_API_ Mock {\n public:\n  // The following public methods can be called concurrently.\n\n  // Tells Google Mock to ignore mock_obj when checking for leaked\n  // mock objects.\n  static void AllowLeak(const void* mock_obj)\n      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);\n\n  // Verifies and clears all expectations on the given mock object.\n  // If the expectations aren't satisfied, generates one or more\n  // Google Test non-fatal failures and returns false.\n  static bool VerifyAndClearExpectations(void* mock_obj)\n      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);\n\n  // Verifies all expectations on the given mock object and clears its\n  // default actions and expectations.  Returns true if and only if the\n  // verification was successful.\n  static bool VerifyAndClear(void* mock_obj)\n      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);\n\n  // Returns whether the mock was created as a naggy mock (default)\n  static bool IsNaggy(void* mock_obj)\n      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);\n  // Returns whether the mock was created as a nice mock\n  static bool IsNice(void* mock_obj)\n      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);\n  // Returns whether the mock was created as a strict mock\n  static bool IsStrict(void* mock_obj)\n      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);\n\n private:\n  friend class internal::UntypedFunctionMockerBase;\n\n  // Needed for a function mocker to register itself (so that we know\n  // how to clear a mock object).\n  template <typename F>\n  friend class internal::FunctionMocker;\n\n  template <typename MockClass>\n  friend class internal::NiceMockImpl;\n  template <typename MockClass>\n  friend class internal::NaggyMockImpl;\n  template <typename MockClass>\n  friend class internal::StrictMockImpl;\n\n  // Tells Google Mock to allow uninteresting calls on the given mock\n  // object.\n  static void AllowUninterestingCalls(uintptr_t mock_obj)\n      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);\n\n  // Tells Google Mock to warn the user about uninteresting calls on\n  // the given mock object.\n  static void WarnUninterestingCalls(uintptr_t mock_obj)\n      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);\n\n  // Tells Google Mock to fail uninteresting calls on the given mock\n  // object.\n  static void FailUninterestingCalls(uintptr_t mock_obj)\n      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);\n\n  // Tells Google Mock the given mock object is being destroyed and\n  // its entry in the call-reaction table should be removed.\n  static void UnregisterCallReaction(uintptr_t mock_obj)\n      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);\n\n  // Returns the reaction Google Mock will have on uninteresting calls\n  // made on the given mock object.\n  static internal::CallReaction GetReactionOnUninterestingCalls(\n      const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);\n\n  // Verifies that all expectations on the given mock object have been\n  // satisfied.  Reports one or more Google Test non-fatal failures\n  // and returns false if not.\n  static bool VerifyAndClearExpectationsLocked(void* mock_obj)\n      GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);\n\n  // Clears all ON_CALL()s set on the given mock object.\n  static void ClearDefaultActionsLocked(void* mock_obj)\n      GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);\n\n  // Registers a mock object and a mock method it owns.\n  static void Register(const void* mock_obj,\n                       internal::UntypedFunctionMockerBase* mocker)\n      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);\n\n  // Tells Google Mock where in the source code mock_obj is used in an\n  // ON_CALL or EXPECT_CALL.  In case mock_obj is leaked, this\n  // information helps the user identify which object it is.\n  static void RegisterUseByOnCallOrExpectCall(const void* mock_obj,\n                                              const char* file, int line)\n      GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);\n\n  // Unregisters a mock method; removes the owning mock object from\n  // the registry when the last mock method associated with it has\n  // been unregistered.  This is called only in the destructor of\n  // FunctionMocker.\n  static void UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)\n      GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);\n};  // class Mock\n\n// An abstract handle of an expectation.  Useful in the .After()\n// clause of EXPECT_CALL() for setting the (partial) order of\n// expectations.  The syntax:\n//\n//   Expectation e1 = EXPECT_CALL(...)...;\n//   EXPECT_CALL(...).After(e1)...;\n//\n// sets two expectations where the latter can only be matched after\n// the former has been satisfied.\n//\n// Notes:\n//   - This class is copyable and has value semantics.\n//   - Constness is shallow: a const Expectation object itself cannot\n//     be modified, but the mutable methods of the ExpectationBase\n//     object it references can be called via expectation_base().\n\nclass GTEST_API_ Expectation {\n public:\n  // Constructs a null object that doesn't reference any expectation.\n  Expectation();\n  Expectation(Expectation&&) = default;\n  Expectation(const Expectation&) = default;\n  Expectation& operator=(Expectation&&) = default;\n  Expectation& operator=(const Expectation&) = default;\n  ~Expectation();\n\n  // This single-argument ctor must not be explicit, in order to support the\n  //   Expectation e = EXPECT_CALL(...);\n  // syntax.\n  //\n  // A TypedExpectation object stores its pre-requisites as\n  // Expectation objects, and needs to call the non-const Retire()\n  // method on the ExpectationBase objects they reference.  Therefore\n  // Expectation must receive a *non-const* reference to the\n  // ExpectationBase object.\n  Expectation(internal::ExpectationBase& exp);  // NOLINT\n\n  // The compiler-generated copy ctor and operator= work exactly as\n  // intended, so we don't need to define our own.\n\n  // Returns true if and only if rhs references the same expectation as this\n  // object does.\n  bool operator==(const Expectation& rhs) const {\n    return expectation_base_ == rhs.expectation_base_;\n  }\n\n  bool operator!=(const Expectation& rhs) const { return !(*this == rhs); }\n\n private:\n  friend class ExpectationSet;\n  friend class Sequence;\n  friend class ::testing::internal::ExpectationBase;\n  friend class ::testing::internal::UntypedFunctionMockerBase;\n\n  template <typename F>\n  friend class ::testing::internal::FunctionMocker;\n\n  template <typename F>\n  friend class ::testing::internal::TypedExpectation;\n\n  // This comparator is needed for putting Expectation objects into a set.\n  class Less {\n   public:\n    bool operator()(const Expectation& lhs, const Expectation& rhs) const {\n      return lhs.expectation_base_.get() < rhs.expectation_base_.get();\n    }\n  };\n\n  typedef ::std::set<Expectation, Less> Set;\n\n  Expectation(\n      const std::shared_ptr<internal::ExpectationBase>& expectation_base);\n\n  // Returns the expectation this object references.\n  const std::shared_ptr<internal::ExpectationBase>& expectation_base() const {\n    return expectation_base_;\n  }\n\n  // A shared_ptr that co-owns the expectation this handle references.\n  std::shared_ptr<internal::ExpectationBase> expectation_base_;\n};\n\n// A set of expectation handles.  Useful in the .After() clause of\n// EXPECT_CALL() for setting the (partial) order of expectations.  The\n// syntax:\n//\n//   ExpectationSet es;\n//   es += EXPECT_CALL(...)...;\n//   es += EXPECT_CALL(...)...;\n//   EXPECT_CALL(...).After(es)...;\n//\n// sets three expectations where the last one can only be matched\n// after the first two have both been satisfied.\n//\n// This class is copyable and has value semantics.\nclass ExpectationSet {\n public:\n  // A bidirectional iterator that can read a const element in the set.\n  typedef Expectation::Set::const_iterator const_iterator;\n\n  // An object stored in the set.  This is an alias of Expectation.\n  typedef Expectation::Set::value_type value_type;\n\n  // Constructs an empty set.\n  ExpectationSet() {}\n\n  // This single-argument ctor must not be explicit, in order to support the\n  //   ExpectationSet es = EXPECT_CALL(...);\n  // syntax.\n  ExpectationSet(internal::ExpectationBase& exp) {  // NOLINT\n    *this += Expectation(exp);\n  }\n\n  // This single-argument ctor implements implicit conversion from\n  // Expectation and thus must not be explicit.  This allows either an\n  // Expectation or an ExpectationSet to be used in .After().\n  ExpectationSet(const Expectation& e) {  // NOLINT\n    *this += e;\n  }\n\n  // The compiler-generator ctor and operator= works exactly as\n  // intended, so we don't need to define our own.\n\n  // Returns true if and only if rhs contains the same set of Expectation\n  // objects as this does.\n  bool operator==(const ExpectationSet& rhs) const {\n    return expectations_ == rhs.expectations_;\n  }\n\n  bool operator!=(const ExpectationSet& rhs) const { return !(*this == rhs); }\n\n  // Implements the syntax\n  //   expectation_set += EXPECT_CALL(...);\n  ExpectationSet& operator+=(const Expectation& e) {\n    expectations_.insert(e);\n    return *this;\n  }\n\n  int size() const { return static_cast<int>(expectations_.size()); }\n\n  const_iterator begin() const { return expectations_.begin(); }\n  const_iterator end() const { return expectations_.end(); }\n\n private:\n  Expectation::Set expectations_;\n};\n\n// Sequence objects are used by a user to specify the relative order\n// in which the expectations should match.  They are copyable (we rely\n// on the compiler-defined copy constructor and assignment operator).\nclass GTEST_API_ Sequence {\n public:\n  // Constructs an empty sequence.\n  Sequence() : last_expectation_(new Expectation) {}\n\n  // Adds an expectation to this sequence.  The caller must ensure\n  // that no other thread is accessing this Sequence object.\n  void AddExpectation(const Expectation& expectation) const;\n\n private:\n  // The last expectation in this sequence.\n  std::shared_ptr<Expectation> last_expectation_;\n};  // class Sequence\n\n// An object of this type causes all EXPECT_CALL() statements\n// encountered in its scope to be put in an anonymous sequence.  The\n// work is done in the constructor and destructor.  You should only\n// create an InSequence object on the stack.\n//\n// The sole purpose for this class is to support easy definition of\n// sequential expectations, e.g.\n//\n//   {\n//     InSequence dummy;  // The name of the object doesn't matter.\n//\n//     // The following expectations must match in the order they appear.\n//     EXPECT_CALL(a, Bar())...;\n//     EXPECT_CALL(a, Baz())...;\n//     ...\n//     EXPECT_CALL(b, Xyz())...;\n//   }\n//\n// You can create InSequence objects in multiple threads, as long as\n// they are used to affect different mock objects.  The idea is that\n// each thread can create and set up its own mocks as if it's the only\n// thread.  However, for clarity of your tests we recommend you to set\n// up mocks in the main thread unless you have a good reason not to do\n// so.\nclass GTEST_API_ InSequence {\n public:\n  InSequence();\n  ~InSequence();\n\n private:\n  bool sequence_created_;\n\n  InSequence(const InSequence&) = delete;\n  InSequence& operator=(const InSequence&) = delete;\n} GTEST_ATTRIBUTE_UNUSED_;\n\nnamespace internal {\n\n// Points to the implicit sequence introduced by a living InSequence\n// object (if any) in the current thread or NULL.\nGTEST_API_ extern ThreadLocal<Sequence*> g_gmock_implicit_sequence;\n\n// Base class for implementing expectations.\n//\n// There are two reasons for having a type-agnostic base class for\n// Expectation:\n//\n//   1. We need to store collections of expectations of different\n//   types (e.g. all pre-requisites of a particular expectation, all\n//   expectations in a sequence).  Therefore these expectation objects\n//   must share a common base class.\n//\n//   2. We can avoid binary code bloat by moving methods not depending\n//   on the template argument of Expectation to the base class.\n//\n// This class is internal and mustn't be used by user code directly.\nclass GTEST_API_ ExpectationBase {\n public:\n  // source_text is the EXPECT_CALL(...) source that created this Expectation.\n  ExpectationBase(const char* file, int line, const std::string& source_text);\n\n  virtual ~ExpectationBase();\n\n  // Where in the source file was the expectation spec defined?\n  const char* file() const { return file_; }\n  int line() const { return line_; }\n  const char* source_text() const { return source_text_.c_str(); }\n  // Returns the cardinality specified in the expectation spec.\n  const Cardinality& cardinality() const { return cardinality_; }\n\n  // Describes the source file location of this expectation.\n  void DescribeLocationTo(::std::ostream* os) const {\n    *os << FormatFileLocation(file(), line()) << \" \";\n  }\n\n  // Describes how many times a function call matching this\n  // expectation has occurred.\n  void DescribeCallCountTo(::std::ostream* os) const\n      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);\n\n  // If this mock method has an extra matcher (i.e. .With(matcher)),\n  // describes it to the ostream.\n  virtual void MaybeDescribeExtraMatcherTo(::std::ostream* os) = 0;\n\n protected:\n  friend class ::testing::Expectation;\n  friend class UntypedFunctionMockerBase;\n\n  enum Clause {\n    // Don't change the order of the enum members!\n    kNone,\n    kWith,\n    kTimes,\n    kInSequence,\n    kAfter,\n    kWillOnce,\n    kWillRepeatedly,\n    kRetiresOnSaturation\n  };\n\n  typedef std::vector<const void*> UntypedActions;\n\n  // Returns an Expectation object that references and co-owns this\n  // expectation.\n  virtual Expectation GetHandle() = 0;\n\n  // Asserts that the EXPECT_CALL() statement has the given property.\n  void AssertSpecProperty(bool property,\n                          const std::string& failure_message) const {\n    Assert(property, file_, line_, failure_message);\n  }\n\n  // Expects that the EXPECT_CALL() statement has the given property.\n  void ExpectSpecProperty(bool property,\n                          const std::string& failure_message) const {\n    Expect(property, file_, line_, failure_message);\n  }\n\n  // Explicitly specifies the cardinality of this expectation.  Used\n  // by the subclasses to implement the .Times() clause.\n  void SpecifyCardinality(const Cardinality& cardinality);\n\n  // Returns true if and only if the user specified the cardinality\n  // explicitly using a .Times().\n  bool cardinality_specified() const { return cardinality_specified_; }\n\n  // Sets the cardinality of this expectation spec.\n  void set_cardinality(const Cardinality& a_cardinality) {\n    cardinality_ = a_cardinality;\n  }\n\n  // The following group of methods should only be called after the\n  // EXPECT_CALL() statement, and only when g_gmock_mutex is held by\n  // the current thread.\n\n  // Retires all pre-requisites of this expectation.\n  void RetireAllPreRequisites() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);\n\n  // Returns true if and only if this expectation is retired.\n  bool is_retired() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n    g_gmock_mutex.AssertHeld();\n    return retired_;\n  }\n\n  // Retires this expectation.\n  void Retire() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n    g_gmock_mutex.AssertHeld();\n    retired_ = true;\n  }\n\n  // Returns true if and only if this expectation is satisfied.\n  bool IsSatisfied() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n    g_gmock_mutex.AssertHeld();\n    return cardinality().IsSatisfiedByCallCount(call_count_);\n  }\n\n  // Returns true if and only if this expectation is saturated.\n  bool IsSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n    g_gmock_mutex.AssertHeld();\n    return cardinality().IsSaturatedByCallCount(call_count_);\n  }\n\n  // Returns true if and only if this expectation is over-saturated.\n  bool IsOverSaturated() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n    g_gmock_mutex.AssertHeld();\n    return cardinality().IsOverSaturatedByCallCount(call_count_);\n  }\n\n  // Returns true if and only if all pre-requisites of this expectation are\n  // satisfied.\n  bool AllPrerequisitesAreSatisfied() const\n      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);\n\n  // Adds unsatisfied pre-requisites of this expectation to 'result'.\n  void FindUnsatisfiedPrerequisites(ExpectationSet* result) const\n      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);\n\n  // Returns the number this expectation has been invoked.\n  int call_count() const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n    g_gmock_mutex.AssertHeld();\n    return call_count_;\n  }\n\n  // Increments the number this expectation has been invoked.\n  void IncrementCallCount() GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n    g_gmock_mutex.AssertHeld();\n    call_count_++;\n  }\n\n  // Checks the action count (i.e. the number of WillOnce() and\n  // WillRepeatedly() clauses) against the cardinality if this hasn't\n  // been done before.  Prints a warning if there are too many or too\n  // few actions.\n  void CheckActionCountIfNotDone() const GTEST_LOCK_EXCLUDED_(mutex_);\n\n  friend class ::testing::Sequence;\n  friend class ::testing::internal::ExpectationTester;\n\n  template <typename Function>\n  friend class TypedExpectation;\n\n  // Implements the .Times() clause.\n  void UntypedTimes(const Cardinality& a_cardinality);\n\n  // This group of fields are part of the spec and won't change after\n  // an EXPECT_CALL() statement finishes.\n  const char* file_;               // The file that contains the expectation.\n  int line_;                       // The line number of the expectation.\n  const std::string source_text_;  // The EXPECT_CALL(...) source text.\n  // True if and only if the cardinality is specified explicitly.\n  bool cardinality_specified_;\n  Cardinality cardinality_;  // The cardinality of the expectation.\n  // The immediate pre-requisites (i.e. expectations that must be\n  // satisfied before this expectation can be matched) of this\n  // expectation.  We use std::shared_ptr in the set because we want an\n  // Expectation object to be co-owned by its FunctionMocker and its\n  // successors.  This allows multiple mock objects to be deleted at\n  // different times.\n  ExpectationSet immediate_prerequisites_;\n\n  // This group of fields are the current state of the expectation,\n  // and can change as the mock function is called.\n  int call_count_;  // How many times this expectation has been invoked.\n  bool retired_;    // True if and only if this expectation has retired.\n  UntypedActions untyped_actions_;\n  bool extra_matcher_specified_;\n  bool repeated_action_specified_;  // True if a WillRepeatedly() was specified.\n  bool retires_on_saturation_;\n  Clause last_clause_;\n  mutable bool action_count_checked_;  // Under mutex_.\n  mutable Mutex mutex_;                // Protects action_count_checked_.\n};                                     // class ExpectationBase\n\ntemplate <typename F>\nclass TypedExpectation;\n\n// Implements an expectation for the given function type.\ntemplate <typename R, typename... Args>\nclass TypedExpectation<R(Args...)> : public ExpectationBase {\n private:\n  using F = R(Args...);\n\n public:\n  typedef typename Function<F>::ArgumentTuple ArgumentTuple;\n  typedef typename Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;\n  typedef typename Function<F>::Result Result;\n\n  TypedExpectation(FunctionMocker<F>* owner, const char* a_file, int a_line,\n                   const std::string& a_source_text,\n                   const ArgumentMatcherTuple& m)\n      : ExpectationBase(a_file, a_line, a_source_text),\n        owner_(owner),\n        matchers_(m),\n        // By default, extra_matcher_ should match anything.  However,\n        // we cannot initialize it with _ as that causes ambiguity between\n        // Matcher's copy and move constructor for some argument types.\n        extra_matcher_(A<const ArgumentTuple&>()),\n        repeated_action_(DoDefault()) {}\n\n  ~TypedExpectation() override {\n    // Check the validity of the action count if it hasn't been done\n    // yet (for example, if the expectation was never used).\n    CheckActionCountIfNotDone();\n    for (UntypedActions::const_iterator it = untyped_actions_.begin();\n         it != untyped_actions_.end(); ++it) {\n      delete static_cast<const Action<F>*>(*it);\n    }\n  }\n\n  // Implements the .With() clause.\n  TypedExpectation& With(const Matcher<const ArgumentTuple&>& m) {\n    if (last_clause_ == kWith) {\n      ExpectSpecProperty(false,\n                         \".With() cannot appear \"\n                         \"more than once in an EXPECT_CALL().\");\n    } else {\n      ExpectSpecProperty(last_clause_ < kWith,\n                         \".With() must be the first \"\n                         \"clause in an EXPECT_CALL().\");\n    }\n    last_clause_ = kWith;\n\n    extra_matcher_ = m;\n    extra_matcher_specified_ = true;\n    return *this;\n  }\n\n  // Implements the .Times() clause.\n  TypedExpectation& Times(const Cardinality& a_cardinality) {\n    ExpectationBase::UntypedTimes(a_cardinality);\n    return *this;\n  }\n\n  // Implements the .Times() clause.\n  TypedExpectation& Times(int n) { return Times(Exactly(n)); }\n\n  // Implements the .InSequence() clause.\n  TypedExpectation& InSequence(const Sequence& s) {\n    ExpectSpecProperty(last_clause_ <= kInSequence,\n                       \".InSequence() cannot appear after .After(),\"\n                       \" .WillOnce(), .WillRepeatedly(), or \"\n                       \".RetiresOnSaturation().\");\n    last_clause_ = kInSequence;\n\n    s.AddExpectation(GetHandle());\n    return *this;\n  }\n  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2) {\n    return InSequence(s1).InSequence(s2);\n  }\n  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,\n                               const Sequence& s3) {\n    return InSequence(s1, s2).InSequence(s3);\n  }\n  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,\n                               const Sequence& s3, const Sequence& s4) {\n    return InSequence(s1, s2, s3).InSequence(s4);\n  }\n  TypedExpectation& InSequence(const Sequence& s1, const Sequence& s2,\n                               const Sequence& s3, const Sequence& s4,\n                               const Sequence& s5) {\n    return InSequence(s1, s2, s3, s4).InSequence(s5);\n  }\n\n  // Implements that .After() clause.\n  TypedExpectation& After(const ExpectationSet& s) {\n    ExpectSpecProperty(last_clause_ <= kAfter,\n                       \".After() cannot appear after .WillOnce(),\"\n                       \" .WillRepeatedly(), or \"\n                       \".RetiresOnSaturation().\");\n    last_clause_ = kAfter;\n\n    for (ExpectationSet::const_iterator it = s.begin(); it != s.end(); ++it) {\n      immediate_prerequisites_ += *it;\n    }\n    return *this;\n  }\n  TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2) {\n    return After(s1).After(s2);\n  }\n  TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,\n                          const ExpectationSet& s3) {\n    return After(s1, s2).After(s3);\n  }\n  TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,\n                          const ExpectationSet& s3, const ExpectationSet& s4) {\n    return After(s1, s2, s3).After(s4);\n  }\n  TypedExpectation& After(const ExpectationSet& s1, const ExpectationSet& s2,\n                          const ExpectationSet& s3, const ExpectationSet& s4,\n                          const ExpectationSet& s5) {\n    return After(s1, s2, s3, s4).After(s5);\n  }\n\n  // Preferred, type-safe overload: consume anything that can be directly\n  // converted to a OnceAction, except for Action<F> objects themselves.\n  TypedExpectation& WillOnce(OnceAction<F> once_action) {\n    // Call the overload below, smuggling the OnceAction as a copyable callable.\n    // We know this is safe because a WillOnce action will not be called more\n    // than once.\n    return WillOnce(Action<F>(ActionAdaptor{\n        std::make_shared<OnceAction<F>>(std::move(once_action)),\n    }));\n  }\n\n  // Fallback overload: accept Action<F> objects and those actions that define\n  // `operator Action<F>` but not `operator OnceAction<F>`.\n  //\n  // This is templated in order to cause the overload above to be preferred\n  // when the input is convertible to either type.\n  template <int&... ExplicitArgumentBarrier, typename = void>\n  TypedExpectation& WillOnce(Action<F> action) {\n    ExpectSpecProperty(last_clause_ <= kWillOnce,\n                       \".WillOnce() cannot appear after \"\n                       \".WillRepeatedly() or .RetiresOnSaturation().\");\n    last_clause_ = kWillOnce;\n\n    untyped_actions_.push_back(new Action<F>(std::move(action)));\n\n    if (!cardinality_specified()) {\n      set_cardinality(Exactly(static_cast<int>(untyped_actions_.size())));\n    }\n    return *this;\n  }\n\n  // Implements the .WillRepeatedly() clause.\n  TypedExpectation& WillRepeatedly(const Action<F>& action) {\n    if (last_clause_ == kWillRepeatedly) {\n      ExpectSpecProperty(false,\n                         \".WillRepeatedly() cannot appear \"\n                         \"more than once in an EXPECT_CALL().\");\n    } else {\n      ExpectSpecProperty(last_clause_ < kWillRepeatedly,\n                         \".WillRepeatedly() cannot appear \"\n                         \"after .RetiresOnSaturation().\");\n    }\n    last_clause_ = kWillRepeatedly;\n    repeated_action_specified_ = true;\n\n    repeated_action_ = action;\n    if (!cardinality_specified()) {\n      set_cardinality(AtLeast(static_cast<int>(untyped_actions_.size())));\n    }\n\n    // Now that no more action clauses can be specified, we check\n    // whether their count makes sense.\n    CheckActionCountIfNotDone();\n    return *this;\n  }\n\n  // Implements the .RetiresOnSaturation() clause.\n  TypedExpectation& RetiresOnSaturation() {\n    ExpectSpecProperty(last_clause_ < kRetiresOnSaturation,\n                       \".RetiresOnSaturation() cannot appear \"\n                       \"more than once.\");\n    last_clause_ = kRetiresOnSaturation;\n    retires_on_saturation_ = true;\n\n    // Now that no more action clauses can be specified, we check\n    // whether their count makes sense.\n    CheckActionCountIfNotDone();\n    return *this;\n  }\n\n  // Returns the matchers for the arguments as specified inside the\n  // EXPECT_CALL() macro.\n  const ArgumentMatcherTuple& matchers() const { return matchers_; }\n\n  // Returns the matcher specified by the .With() clause.\n  const Matcher<const ArgumentTuple&>& extra_matcher() const {\n    return extra_matcher_;\n  }\n\n  // Returns the action specified by the .WillRepeatedly() clause.\n  const Action<F>& repeated_action() const { return repeated_action_; }\n\n  // If this mock method has an extra matcher (i.e. .With(matcher)),\n  // describes it to the ostream.\n  void MaybeDescribeExtraMatcherTo(::std::ostream* os) override {\n    if (extra_matcher_specified_) {\n      *os << \"    Expected args: \";\n      extra_matcher_.DescribeTo(os);\n      *os << \"\\n\";\n    }\n  }\n\n private:\n  template <typename Function>\n  friend class FunctionMocker;\n\n  // An adaptor that turns a OneAction<F> into something compatible with\n  // Action<F>. Must be called at most once.\n  struct ActionAdaptor {\n    std::shared_ptr<OnceAction<R(Args...)>> once_action;\n\n    R operator()(Args&&... args) const {\n      return std::move(*once_action).Call(std::forward<Args>(args)...);\n    }\n  };\n\n  // Returns an Expectation object that references and co-owns this\n  // expectation.\n  Expectation GetHandle() override { return owner_->GetHandleOf(this); }\n\n  // The following methods will be called only after the EXPECT_CALL()\n  // statement finishes and when the current thread holds\n  // g_gmock_mutex.\n\n  // Returns true if and only if this expectation matches the given arguments.\n  bool Matches(const ArgumentTuple& args) const\n      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n    g_gmock_mutex.AssertHeld();\n    return TupleMatches(matchers_, args) && extra_matcher_.Matches(args);\n  }\n\n  // Returns true if and only if this expectation should handle the given\n  // arguments.\n  bool ShouldHandleArguments(const ArgumentTuple& args) const\n      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n    g_gmock_mutex.AssertHeld();\n\n    // In case the action count wasn't checked when the expectation\n    // was defined (e.g. if this expectation has no WillRepeatedly()\n    // or RetiresOnSaturation() clause), we check it when the\n    // expectation is used for the first time.\n    CheckActionCountIfNotDone();\n    return !is_retired() && AllPrerequisitesAreSatisfied() && Matches(args);\n  }\n\n  // Describes the result of matching the arguments against this\n  // expectation to the given ostream.\n  void ExplainMatchResultTo(const ArgumentTuple& args, ::std::ostream* os) const\n      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n    g_gmock_mutex.AssertHeld();\n\n    if (is_retired()) {\n      *os << \"         Expected: the expectation is active\\n\"\n          << \"           Actual: it is retired\\n\";\n    } else if (!Matches(args)) {\n      if (!TupleMatches(matchers_, args)) {\n        ExplainMatchFailureTupleTo(matchers_, args, os);\n      }\n      StringMatchResultListener listener;\n      if (!extra_matcher_.MatchAndExplain(args, &listener)) {\n        *os << \"    Expected args: \";\n        extra_matcher_.DescribeTo(os);\n        *os << \"\\n           Actual: don't match\";\n\n        internal::PrintIfNotEmpty(listener.str(), os);\n        *os << \"\\n\";\n      }\n    } else if (!AllPrerequisitesAreSatisfied()) {\n      *os << \"         Expected: all pre-requisites are satisfied\\n\"\n          << \"           Actual: the following immediate pre-requisites \"\n          << \"are not satisfied:\\n\";\n      ExpectationSet unsatisfied_prereqs;\n      FindUnsatisfiedPrerequisites(&unsatisfied_prereqs);\n      int i = 0;\n      for (ExpectationSet::const_iterator it = unsatisfied_prereqs.begin();\n           it != unsatisfied_prereqs.end(); ++it) {\n        it->expectation_base()->DescribeLocationTo(os);\n        *os << \"pre-requisite #\" << i++ << \"\\n\";\n      }\n      *os << \"                   (end of pre-requisites)\\n\";\n    } else {\n      // This line is here just for completeness' sake.  It will never\n      // be executed as currently the ExplainMatchResultTo() function\n      // is called only when the mock function call does NOT match the\n      // expectation.\n      *os << \"The call matches the expectation.\\n\";\n    }\n  }\n\n  // Returns the action that should be taken for the current invocation.\n  const Action<F>& GetCurrentAction(const FunctionMocker<F>* mocker,\n                                    const ArgumentTuple& args) const\n      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n    g_gmock_mutex.AssertHeld();\n    const int count = call_count();\n    Assert(count >= 1, __FILE__, __LINE__,\n           \"call_count() is <= 0 when GetCurrentAction() is \"\n           \"called - this should never happen.\");\n\n    const int action_count = static_cast<int>(untyped_actions_.size());\n    if (action_count > 0 && !repeated_action_specified_ &&\n        count > action_count) {\n      // If there is at least one WillOnce() and no WillRepeatedly(),\n      // we warn the user when the WillOnce() clauses ran out.\n      ::std::stringstream ss;\n      DescribeLocationTo(&ss);\n      ss << \"Actions ran out in \" << source_text() << \"...\\n\"\n         << \"Called \" << count << \" times, but only \" << action_count\n         << \" WillOnce()\" << (action_count == 1 ? \" is\" : \"s are\")\n         << \" specified - \";\n      mocker->DescribeDefaultActionTo(args, &ss);\n      Log(kWarning, ss.str(), 1);\n    }\n\n    return count <= action_count\n               ? *static_cast<const Action<F>*>(\n                     untyped_actions_[static_cast<size_t>(count - 1)])\n               : repeated_action();\n  }\n\n  // Given the arguments of a mock function call, if the call will\n  // over-saturate this expectation, returns the default action;\n  // otherwise, returns the next action in this expectation.  Also\n  // describes *what* happened to 'what', and explains *why* Google\n  // Mock does it to 'why'.  This method is not const as it calls\n  // IncrementCallCount().  A return value of NULL means the default\n  // action.\n  const Action<F>* GetActionForArguments(const FunctionMocker<F>* mocker,\n                                         const ArgumentTuple& args,\n                                         ::std::ostream* what,\n                                         ::std::ostream* why)\n      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n    g_gmock_mutex.AssertHeld();\n    if (IsSaturated()) {\n      // We have an excessive call.\n      IncrementCallCount();\n      *what << \"Mock function called more times than expected - \";\n      mocker->DescribeDefaultActionTo(args, what);\n      DescribeCallCountTo(why);\n\n      return nullptr;\n    }\n\n    IncrementCallCount();\n    RetireAllPreRequisites();\n\n    if (retires_on_saturation_ && IsSaturated()) {\n      Retire();\n    }\n\n    // Must be done after IncrementCount()!\n    *what << \"Mock function call matches \" << source_text() << \"...\\n\";\n    return &(GetCurrentAction(mocker, args));\n  }\n\n  // All the fields below won't change once the EXPECT_CALL()\n  // statement finishes.\n  FunctionMocker<F>* const owner_;\n  ArgumentMatcherTuple matchers_;\n  Matcher<const ArgumentTuple&> extra_matcher_;\n  Action<F> repeated_action_;\n\n  TypedExpectation(const TypedExpectation&) = delete;\n  TypedExpectation& operator=(const TypedExpectation&) = delete;\n};  // class TypedExpectation\n\n// A MockSpec object is used by ON_CALL() or EXPECT_CALL() for\n// specifying the default behavior of, or expectation on, a mock\n// function.\n\n// Note: class MockSpec really belongs to the ::testing namespace.\n// However if we define it in ::testing, MSVC will complain when\n// classes in ::testing::internal declare it as a friend class\n// template.  To workaround this compiler bug, we define MockSpec in\n// ::testing::internal and import it into ::testing.\n\n// Logs a message including file and line number information.\nGTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,\n                                const char* file, int line,\n                                const std::string& message);\n\ntemplate <typename F>\nclass MockSpec {\n public:\n  typedef typename internal::Function<F>::ArgumentTuple ArgumentTuple;\n  typedef\n      typename internal::Function<F>::ArgumentMatcherTuple ArgumentMatcherTuple;\n\n  // Constructs a MockSpec object, given the function mocker object\n  // that the spec is associated with.\n  MockSpec(internal::FunctionMocker<F>* function_mocker,\n           const ArgumentMatcherTuple& matchers)\n      : function_mocker_(function_mocker), matchers_(matchers) {}\n\n  // Adds a new default action spec to the function mocker and returns\n  // the newly created spec.\n  internal::OnCallSpec<F>& InternalDefaultActionSetAt(const char* file,\n                                                      int line, const char* obj,\n                                                      const char* call) {\n    LogWithLocation(internal::kInfo, file, line,\n                    std::string(\"ON_CALL(\") + obj + \", \" + call + \") invoked\");\n    return function_mocker_->AddNewOnCallSpec(file, line, matchers_);\n  }\n\n  // Adds a new expectation spec to the function mocker and returns\n  // the newly created spec.\n  internal::TypedExpectation<F>& InternalExpectedAt(const char* file, int line,\n                                                    const char* obj,\n                                                    const char* call) {\n    const std::string source_text(std::string(\"EXPECT_CALL(\") + obj + \", \" +\n                                  call + \")\");\n    LogWithLocation(internal::kInfo, file, line, source_text + \" invoked\");\n    return function_mocker_->AddNewExpectation(file, line, source_text,\n                                               matchers_);\n  }\n\n  // This operator overload is used to swallow the superfluous parameter list\n  // introduced by the ON/EXPECT_CALL macros. See the macro comments for more\n  // explanation.\n  MockSpec<F>& operator()(const internal::WithoutMatchers&, void* const) {\n    return *this;\n  }\n\n private:\n  template <typename Function>\n  friend class internal::FunctionMocker;\n\n  // The function mocker that owns this spec.\n  internal::FunctionMocker<F>* const function_mocker_;\n  // The argument matchers specified in the spec.\n  ArgumentMatcherTuple matchers_;\n};  // class MockSpec\n\n// Wrapper type for generically holding an ordinary value or lvalue reference.\n// If T is not a reference type, it must be copyable or movable.\n// ReferenceOrValueWrapper<T> is movable, and will also be copyable unless\n// T is a move-only value type (which means that it will always be copyable\n// if the current platform does not support move semantics).\n//\n// The primary template defines handling for values, but function header\n// comments describe the contract for the whole template (including\n// specializations).\ntemplate <typename T>\nclass ReferenceOrValueWrapper {\n public:\n  // Constructs a wrapper from the given value/reference.\n  explicit ReferenceOrValueWrapper(T value) : value_(std::move(value)) {}\n\n  // Unwraps and returns the underlying value/reference, exactly as\n  // originally passed. The behavior of calling this more than once on\n  // the same object is unspecified.\n  T Unwrap() { return std::move(value_); }\n\n  // Provides nondestructive access to the underlying value/reference.\n  // Always returns a const reference (more precisely,\n  // const std::add_lvalue_reference<T>::type). The behavior of calling this\n  // after calling Unwrap on the same object is unspecified.\n  const T& Peek() const { return value_; }\n\n private:\n  T value_;\n};\n\n// Specialization for lvalue reference types. See primary template\n// for documentation.\ntemplate <typename T>\nclass ReferenceOrValueWrapper<T&> {\n public:\n  // Workaround for debatable pass-by-reference lint warning (c-library-team\n  // policy precludes NOLINT in this context)\n  typedef T& reference;\n  explicit ReferenceOrValueWrapper(reference ref) : value_ptr_(&ref) {}\n  T& Unwrap() { return *value_ptr_; }\n  const T& Peek() const { return *value_ptr_; }\n\n private:\n  T* value_ptr_;\n};\n\n// Prints the held value as an action's result to os.\ntemplate <typename T>\nvoid PrintAsActionResult(const T& result, std::ostream& os) {\n  os << \"\\n          Returns: \";\n  // T may be a reference type, so we don't use UniversalPrint().\n  UniversalPrinter<T>::Print(result, &os);\n}\n\n// Reports an uninteresting call (whose description is in msg) in the\n// manner specified by 'reaction'.\nGTEST_API_ void ReportUninterestingCall(CallReaction reaction,\n                                        const std::string& msg);\n\n// A generic RAII type that runs a user-provided function in its destructor.\nclass Cleanup final {\n public:\n  explicit Cleanup(std::function<void()> f) : f_(std::move(f)) {}\n  ~Cleanup() { f_(); }\n\n private:\n  std::function<void()> f_;\n};\n\ntemplate <typename F>\nclass FunctionMocker;\n\ntemplate <typename R, typename... Args>\nclass FunctionMocker<R(Args...)> final : public UntypedFunctionMockerBase {\n  using F = R(Args...);\n\n public:\n  using Result = R;\n  using ArgumentTuple = std::tuple<Args...>;\n  using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;\n\n  FunctionMocker() {}\n\n  // There is no generally useful and implementable semantics of\n  // copying a mock object, so copying a mock is usually a user error.\n  // Thus we disallow copying function mockers.  If the user really\n  // wants to copy a mock object, they should implement their own copy\n  // operation, for example:\n  //\n  //   class MockFoo : public Foo {\n  //    public:\n  //     // Defines a copy constructor explicitly.\n  //     MockFoo(const MockFoo& src) {}\n  //     ...\n  //   };\n  FunctionMocker(const FunctionMocker&) = delete;\n  FunctionMocker& operator=(const FunctionMocker&) = delete;\n\n  // The destructor verifies that all expectations on this mock\n  // function have been satisfied.  If not, it will report Google Test\n  // non-fatal failures for the violations.\n  ~FunctionMocker() override GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {\n    MutexLock l(&g_gmock_mutex);\n    VerifyAndClearExpectationsLocked();\n    Mock::UnregisterLocked(this);\n    ClearDefaultActionsLocked();\n  }\n\n  // Returns the ON_CALL spec that matches this mock function with the\n  // given arguments; returns NULL if no matching ON_CALL is found.\n  // L = *\n  const OnCallSpec<F>* FindOnCallSpec(const ArgumentTuple& args) const {\n    for (UntypedOnCallSpecs::const_reverse_iterator it =\n             untyped_on_call_specs_.rbegin();\n         it != untyped_on_call_specs_.rend(); ++it) {\n      const OnCallSpec<F>* spec = static_cast<const OnCallSpec<F>*>(*it);\n      if (spec->Matches(args)) return spec;\n    }\n\n    return nullptr;\n  }\n\n  // Performs the default action of this mock function on the given\n  // arguments and returns the result. Asserts (or throws if\n  // exceptions are enabled) with a helpful call description if there\n  // is no valid return value. This method doesn't depend on the\n  // mutable state of this object, and thus can be called concurrently\n  // without locking.\n  // L = *\n  Result PerformDefaultAction(ArgumentTuple&& args,\n                              const std::string& call_description) const {\n    const OnCallSpec<F>* const spec = this->FindOnCallSpec(args);\n    if (spec != nullptr) {\n      return spec->GetAction().Perform(std::move(args));\n    }\n    const std::string message =\n        call_description +\n        \"\\n    The mock function has no default action \"\n        \"set, and its return type has no default value set.\";\n#if GTEST_HAS_EXCEPTIONS\n    if (!DefaultValue<Result>::Exists()) {\n      throw std::runtime_error(message);\n    }\n#else\n    Assert(DefaultValue<Result>::Exists(), \"\", -1, message);\n#endif\n    return DefaultValue<Result>::Get();\n  }\n\n  // Implements UntypedFunctionMockerBase::ClearDefaultActionsLocked():\n  // clears the ON_CALL()s set on this mock function.\n  void ClearDefaultActionsLocked() override\n      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n    g_gmock_mutex.AssertHeld();\n\n    // Deleting our default actions may trigger other mock objects to be\n    // deleted, for example if an action contains a reference counted smart\n    // pointer to that mock object, and that is the last reference. So if we\n    // delete our actions within the context of the global mutex we may deadlock\n    // when this method is called again. Instead, make a copy of the set of\n    // actions to delete, clear our set within the mutex, and then delete the\n    // actions outside of the mutex.\n    UntypedOnCallSpecs specs_to_delete;\n    untyped_on_call_specs_.swap(specs_to_delete);\n\n    g_gmock_mutex.Unlock();\n    for (UntypedOnCallSpecs::const_iterator it = specs_to_delete.begin();\n         it != specs_to_delete.end(); ++it) {\n      delete static_cast<const OnCallSpec<F>*>(*it);\n    }\n\n    // Lock the mutex again, since the caller expects it to be locked when we\n    // return.\n    g_gmock_mutex.Lock();\n  }\n\n  // Returns the result of invoking this mock function with the given\n  // arguments.  This function can be safely called from multiple\n  // threads concurrently.\n  Result Invoke(Args... args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {\n    return InvokeWith(ArgumentTuple(std::forward<Args>(args)...));\n  }\n\n  MockSpec<F> With(Matcher<Args>... m) {\n    return MockSpec<F>(this, ::std::make_tuple(std::move(m)...));\n  }\n\n protected:\n  template <typename Function>\n  friend class MockSpec;\n\n  // Adds and returns a default action spec for this mock function.\n  OnCallSpec<F>& AddNewOnCallSpec(const char* file, int line,\n                                  const ArgumentMatcherTuple& m)\n      GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {\n    Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);\n    OnCallSpec<F>* const on_call_spec = new OnCallSpec<F>(file, line, m);\n    untyped_on_call_specs_.push_back(on_call_spec);\n    return *on_call_spec;\n  }\n\n  // Adds and returns an expectation spec for this mock function.\n  TypedExpectation<F>& AddNewExpectation(const char* file, int line,\n                                         const std::string& source_text,\n                                         const ArgumentMatcherTuple& m)\n      GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {\n    Mock::RegisterUseByOnCallOrExpectCall(MockObject(), file, line);\n    TypedExpectation<F>* const expectation =\n        new TypedExpectation<F>(this, file, line, source_text, m);\n    const std::shared_ptr<ExpectationBase> untyped_expectation(expectation);\n    // See the definition of untyped_expectations_ for why access to\n    // it is unprotected here.\n    untyped_expectations_.push_back(untyped_expectation);\n\n    // Adds this expectation into the implicit sequence if there is one.\n    Sequence* const implicit_sequence = g_gmock_implicit_sequence.get();\n    if (implicit_sequence != nullptr) {\n      implicit_sequence->AddExpectation(Expectation(untyped_expectation));\n    }\n\n    return *expectation;\n  }\n\n private:\n  template <typename Func>\n  friend class TypedExpectation;\n\n  // Some utilities needed for implementing UntypedInvokeWith().\n\n  // Describes what default action will be performed for the given\n  // arguments.\n  // L = *\n  void DescribeDefaultActionTo(const ArgumentTuple& args,\n                               ::std::ostream* os) const {\n    const OnCallSpec<F>* const spec = FindOnCallSpec(args);\n\n    if (spec == nullptr) {\n      *os << (std::is_void<Result>::value ? \"returning directly.\\n\"\n                                          : \"returning default value.\\n\");\n    } else {\n      *os << \"taking default action specified at:\\n\"\n          << FormatFileLocation(spec->file(), spec->line()) << \"\\n\";\n    }\n  }\n\n  // Writes a message that the call is uninteresting (i.e. neither\n  // explicitly expected nor explicitly unexpected) to the given\n  // ostream.\n  void UntypedDescribeUninterestingCall(const void* untyped_args,\n                                        ::std::ostream* os) const override\n      GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {\n    const ArgumentTuple& args =\n        *static_cast<const ArgumentTuple*>(untyped_args);\n    *os << \"Uninteresting mock function call - \";\n    DescribeDefaultActionTo(args, os);\n    *os << \"    Function call: \" << Name();\n    UniversalPrint(args, os);\n  }\n\n  // Returns the expectation that matches the given function arguments\n  // (or NULL is there's no match); when a match is found,\n  // untyped_action is set to point to the action that should be\n  // performed (or NULL if the action is \"do default\"), and\n  // is_excessive is modified to indicate whether the call exceeds the\n  // expected number.\n  //\n  // Critical section: We must find the matching expectation and the\n  // corresponding action that needs to be taken in an ATOMIC\n  // transaction.  Otherwise another thread may call this mock\n  // method in the middle and mess up the state.\n  //\n  // However, performing the action has to be left out of the critical\n  // section.  The reason is that we have no control on what the\n  // action does (it can invoke an arbitrary user function or even a\n  // mock function) and excessive locking could cause a dead lock.\n  const ExpectationBase* UntypedFindMatchingExpectation(\n      const void* untyped_args, const void** untyped_action, bool* is_excessive,\n      ::std::ostream* what, ::std::ostream* why) override\n      GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {\n    const ArgumentTuple& args =\n        *static_cast<const ArgumentTuple*>(untyped_args);\n    MutexLock l(&g_gmock_mutex);\n    TypedExpectation<F>* exp = this->FindMatchingExpectationLocked(args);\n    if (exp == nullptr) {  // A match wasn't found.\n      this->FormatUnexpectedCallMessageLocked(args, what, why);\n      return nullptr;\n    }\n\n    // This line must be done before calling GetActionForArguments(),\n    // which will increment the call count for *exp and thus affect\n    // its saturation status.\n    *is_excessive = exp->IsSaturated();\n    const Action<F>* action = exp->GetActionForArguments(this, args, what, why);\n    if (action != nullptr && action->IsDoDefault())\n      action = nullptr;  // Normalize \"do default\" to NULL.\n    *untyped_action = action;\n    return exp;\n  }\n\n  // Prints the given function arguments to the ostream.\n  void UntypedPrintArgs(const void* untyped_args,\n                        ::std::ostream* os) const override {\n    const ArgumentTuple& args =\n        *static_cast<const ArgumentTuple*>(untyped_args);\n    UniversalPrint(args, os);\n  }\n\n  // Returns the expectation that matches the arguments, or NULL if no\n  // expectation matches them.\n  TypedExpectation<F>* FindMatchingExpectationLocked(const ArgumentTuple& args)\n      const GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n    g_gmock_mutex.AssertHeld();\n    // See the definition of untyped_expectations_ for why access to\n    // it is unprotected here.\n    for (typename UntypedExpectations::const_reverse_iterator it =\n             untyped_expectations_.rbegin();\n         it != untyped_expectations_.rend(); ++it) {\n      TypedExpectation<F>* const exp =\n          static_cast<TypedExpectation<F>*>(it->get());\n      if (exp->ShouldHandleArguments(args)) {\n        return exp;\n      }\n    }\n    return nullptr;\n  }\n\n  // Returns a message that the arguments don't match any expectation.\n  void FormatUnexpectedCallMessageLocked(const ArgumentTuple& args,\n                                         ::std::ostream* os,\n                                         ::std::ostream* why) const\n      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n    g_gmock_mutex.AssertHeld();\n    *os << \"\\nUnexpected mock function call - \";\n    DescribeDefaultActionTo(args, os);\n    PrintTriedExpectationsLocked(args, why);\n  }\n\n  // Prints a list of expectations that have been tried against the\n  // current mock function call.\n  void PrintTriedExpectationsLocked(const ArgumentTuple& args,\n                                    ::std::ostream* why) const\n      GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n    g_gmock_mutex.AssertHeld();\n    const size_t count = untyped_expectations_.size();\n    *why << \"Google Mock tried the following \" << count << \" \"\n         << (count == 1 ? \"expectation, but it didn't match\"\n                        : \"expectations, but none matched\")\n         << \":\\n\";\n    for (size_t i = 0; i < count; i++) {\n      TypedExpectation<F>* const expectation =\n          static_cast<TypedExpectation<F>*>(untyped_expectations_[i].get());\n      *why << \"\\n\";\n      expectation->DescribeLocationTo(why);\n      if (count > 1) {\n        *why << \"tried expectation #\" << i << \": \";\n      }\n      *why << expectation->source_text() << \"...\\n\";\n      expectation->ExplainMatchResultTo(args, why);\n      expectation->DescribeCallCountTo(why);\n    }\n  }\n\n  // Performs the given action (or the default if it's null) with the given\n  // arguments and returns the action's result.\n  // L = *\n  R PerformAction(const void* untyped_action, ArgumentTuple&& args,\n                  const std::string& call_description) const {\n    if (untyped_action == nullptr) {\n      return PerformDefaultAction(std::move(args), call_description);\n    }\n\n    // Make a copy of the action before performing it, in case the\n    // action deletes the mock object (and thus deletes itself).\n    const Action<F> action = *static_cast<const Action<F>*>(untyped_action);\n    return action.Perform(std::move(args));\n  }\n\n  // Is it possible to store an object of the supplied type in a local variable\n  // for the sake of printing it, then return it on to the caller?\n  template <typename T>\n  using can_print_result = internal::conjunction<\n      // void can't be stored as an object (and we also don't need to print it).\n      internal::negation<std::is_void<T>>,\n      // Non-moveable types can't be returned on to the user, so there's no way\n      // for us to intercept and print them.\n      std::is_move_constructible<T>>;\n\n  // Perform the supplied action, printing the result to os.\n  template <typename T = R,\n            typename std::enable_if<can_print_result<T>::value, int>::type = 0>\n  R PerformActionAndPrintResult(const void* const untyped_action,\n                                ArgumentTuple&& args,\n                                const std::string& call_description,\n                                std::ostream& os) {\n    R result = PerformAction(untyped_action, std::move(args), call_description);\n\n    PrintAsActionResult(result, os);\n    return std::forward<R>(result);\n  }\n\n  // An overload for when it's not possible to print the result. In this case we\n  // simply perform the action.\n  template <typename T = R,\n            typename std::enable_if<\n                internal::negation<can_print_result<T>>::value, int>::type = 0>\n  R PerformActionAndPrintResult(const void* const untyped_action,\n                                ArgumentTuple&& args,\n                                const std::string& call_description,\n                                std::ostream&) {\n    return PerformAction(untyped_action, std::move(args), call_description);\n  }\n\n  // Returns the result of invoking this mock function with the given\n  // arguments. This function can be safely called from multiple\n  // threads concurrently.\n  R InvokeWith(ArgumentTuple&& args) GTEST_LOCK_EXCLUDED_(g_gmock_mutex);\n};  // class FunctionMocker\n\n// Calculates the result of invoking this mock function with the given\n// arguments, prints it, and returns it.\ntemplate <typename R, typename... Args>\nR FunctionMocker<R(Args...)>::InvokeWith(ArgumentTuple&& args)\n    GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {\n  // See the definition of untyped_expectations_ for why access to it\n  // is unprotected here.\n  if (untyped_expectations_.size() == 0) {\n    // No expectation is set on this mock method - we have an\n    // uninteresting call.\n\n    // We must get Google Mock's reaction on uninteresting calls\n    // made on this mock object BEFORE performing the action,\n    // because the action may DELETE the mock object and make the\n    // following expression meaningless.\n    const CallReaction reaction =\n        Mock::GetReactionOnUninterestingCalls(MockObject());\n\n    // True if and only if we need to print this call's arguments and return\n    // value.  This definition must be kept in sync with\n    // the behavior of ReportUninterestingCall().\n    const bool need_to_report_uninteresting_call =\n        // If the user allows this uninteresting call, we print it\n        // only when they want informational messages.\n        reaction == kAllow ? LogIsVisible(kInfo) :\n                           // If the user wants this to be a warning, we print\n                           // it only when they want to see warnings.\n            reaction == kWarn\n            ? LogIsVisible(kWarning)\n            :\n            // Otherwise, the user wants this to be an error, and we\n            // should always print detailed information in the error.\n            true;\n\n    if (!need_to_report_uninteresting_call) {\n      // Perform the action without printing the call information.\n      return this->PerformDefaultAction(\n          std::move(args), \"Function call: \" + std::string(Name()));\n    }\n\n    // Warns about the uninteresting call.\n    ::std::stringstream ss;\n    this->UntypedDescribeUninterestingCall(&args, &ss);\n\n    // Perform the action, print the result, and then report the uninteresting\n    // call.\n    //\n    // We use RAII to do the latter in case R is void or a non-moveable type. In\n    // either case we can't assign it to a local variable.\n    const Cleanup report_uninteresting_call(\n        [&] { ReportUninterestingCall(reaction, ss.str()); });\n\n    return PerformActionAndPrintResult(nullptr, std::move(args), ss.str(), ss);\n  }\n\n  bool is_excessive = false;\n  ::std::stringstream ss;\n  ::std::stringstream why;\n  ::std::stringstream loc;\n  const void* untyped_action = nullptr;\n\n  // The UntypedFindMatchingExpectation() function acquires and\n  // releases g_gmock_mutex.\n\n  const ExpectationBase* const untyped_expectation =\n      this->UntypedFindMatchingExpectation(&args, &untyped_action,\n                                           &is_excessive, &ss, &why);\n  const bool found = untyped_expectation != nullptr;\n\n  // True if and only if we need to print the call's arguments\n  // and return value.\n  // This definition must be kept in sync with the uses of Expect()\n  // and Log() in this function.\n  const bool need_to_report_call =\n      !found || is_excessive || LogIsVisible(kInfo);\n  if (!need_to_report_call) {\n    // Perform the action without printing the call information.\n    return PerformAction(untyped_action, std::move(args), \"\");\n  }\n\n  ss << \"    Function call: \" << Name();\n  this->UntypedPrintArgs(&args, &ss);\n\n  // In case the action deletes a piece of the expectation, we\n  // generate the message beforehand.\n  if (found && !is_excessive) {\n    untyped_expectation->DescribeLocationTo(&loc);\n  }\n\n  // Perform the action, print the result, and then fail or log in whatever way\n  // is appropriate.\n  //\n  // We use RAII to do the latter in case R is void or a non-moveable type. In\n  // either case we can't assign it to a local variable.\n  const Cleanup handle_failures([&] {\n    ss << \"\\n\" << why.str();\n\n    if (!found) {\n      // No expectation matches this call - reports a failure.\n      Expect(false, nullptr, -1, ss.str());\n    } else if (is_excessive) {\n      // We had an upper-bound violation and the failure message is in ss.\n      Expect(false, untyped_expectation->file(), untyped_expectation->line(),\n             ss.str());\n    } else {\n      // We had an expected call and the matching expectation is\n      // described in ss.\n      Log(kInfo, loc.str() + ss.str(), 2);\n    }\n  });\n\n  return PerformActionAndPrintResult(untyped_action, std::move(args), ss.str(),\n                                     ss);\n}\n\n}  // namespace internal\n\nnamespace internal {\n\ntemplate <typename F>\nclass MockFunction;\n\ntemplate <typename R, typename... Args>\nclass MockFunction<R(Args...)> {\n public:\n  MockFunction(const MockFunction&) = delete;\n  MockFunction& operator=(const MockFunction&) = delete;\n\n  std::function<R(Args...)> AsStdFunction() {\n    return [this](Args... args) -> R {\n      return this->Call(std::forward<Args>(args)...);\n    };\n  }\n\n  // Implementation detail: the expansion of the MOCK_METHOD macro.\n  R Call(Args... args) {\n    mock_.SetOwnerAndName(this, \"Call\");\n    return mock_.Invoke(std::forward<Args>(args)...);\n  }\n\n  MockSpec<R(Args...)> gmock_Call(Matcher<Args>... m) {\n    mock_.RegisterOwner(this);\n    return mock_.With(std::move(m)...);\n  }\n\n  MockSpec<R(Args...)> gmock_Call(const WithoutMatchers&, R (*)(Args...)) {\n    return this->gmock_Call(::testing::A<Args>()...);\n  }\n\n protected:\n  MockFunction() = default;\n  ~MockFunction() = default;\n\n private:\n  FunctionMocker<R(Args...)> mock_;\n};\n\n/*\nThe SignatureOf<F> struct is a meta-function returning function signature\ncorresponding to the provided F argument.\n\nIt makes use of MockFunction easier by allowing it to accept more F arguments\nthan just function signatures.\n\nSpecializations provided here cover a signature type itself and any template\nthat can be parameterized with a signature, including std::function and\nboost::function.\n*/\n\ntemplate <typename F, typename = void>\nstruct SignatureOf;\n\ntemplate <typename R, typename... Args>\nstruct SignatureOf<R(Args...)> {\n  using type = R(Args...);\n};\n\ntemplate <template <typename> class C, typename F>\nstruct SignatureOf<C<F>,\n                   typename std::enable_if<std::is_function<F>::value>::type>\n    : SignatureOf<F> {};\n\ntemplate <typename F>\nusing SignatureOfT = typename SignatureOf<F>::type;\n\n}  // namespace internal\n\n// A MockFunction<F> type has one mock method whose type is\n// internal::SignatureOfT<F>.  It is useful when you just want your\n// test code to emit some messages and have Google Mock verify the\n// right messages are sent (and perhaps at the right times).  For\n// example, if you are exercising code:\n//\n//   Foo(1);\n//   Foo(2);\n//   Foo(3);\n//\n// and want to verify that Foo(1) and Foo(3) both invoke\n// mock.Bar(\"a\"), but Foo(2) doesn't invoke anything, you can write:\n//\n// TEST(FooTest, InvokesBarCorrectly) {\n//   MyMock mock;\n//   MockFunction<void(string check_point_name)> check;\n//   {\n//     InSequence s;\n//\n//     EXPECT_CALL(mock, Bar(\"a\"));\n//     EXPECT_CALL(check, Call(\"1\"));\n//     EXPECT_CALL(check, Call(\"2\"));\n//     EXPECT_CALL(mock, Bar(\"a\"));\n//   }\n//   Foo(1);\n//   check.Call(\"1\");\n//   Foo(2);\n//   check.Call(\"2\");\n//   Foo(3);\n// }\n//\n// The expectation spec says that the first Bar(\"a\") must happen\n// before check point \"1\", the second Bar(\"a\") must happen after check\n// point \"2\", and nothing should happen between the two check\n// points. The explicit check points make it easy to tell which\n// Bar(\"a\") is called by which call to Foo().\n//\n// MockFunction<F> can also be used to exercise code that accepts\n// std::function<internal::SignatureOfT<F>> callbacks. To do so, use\n// AsStdFunction() method to create std::function proxy forwarding to\n// original object's Call. Example:\n//\n// TEST(FooTest, RunsCallbackWithBarArgument) {\n//   MockFunction<int(string)> callback;\n//   EXPECT_CALL(callback, Call(\"bar\")).WillOnce(Return(1));\n//   Foo(callback.AsStdFunction());\n// }\n//\n// The internal::SignatureOfT<F> indirection allows to use other types\n// than just function signature type. This is typically useful when\n// providing a mock for a predefined std::function type. Example:\n//\n// using FilterPredicate = std::function<bool(string)>;\n// void MyFilterAlgorithm(FilterPredicate predicate);\n//\n// TEST(FooTest, FilterPredicateAlwaysAccepts) {\n//   MockFunction<FilterPredicate> predicateMock;\n//   EXPECT_CALL(predicateMock, Call(_)).WillRepeatedly(Return(true));\n//   MyFilterAlgorithm(predicateMock.AsStdFunction());\n// }\ntemplate <typename F>\nclass MockFunction : public internal::MockFunction<internal::SignatureOfT<F>> {\n  using Base = internal::MockFunction<internal::SignatureOfT<F>>;\n\n public:\n  using Base::Base;\n};\n\n// The style guide prohibits \"using\" statements in a namespace scope\n// inside a header file.  However, the MockSpec class template is\n// meant to be defined in the ::testing namespace.  The following line\n// is just a trick for working around a bug in MSVC 8.0, which cannot\n// handle it if we define MockSpec in ::testing.\nusing internal::MockSpec;\n\n// Const(x) is a convenient function for obtaining a const reference\n// to x.  This is useful for setting expectations on an overloaded\n// const mock method, e.g.\n//\n//   class MockFoo : public FooInterface {\n//    public:\n//     MOCK_METHOD0(Bar, int());\n//     MOCK_CONST_METHOD0(Bar, int&());\n//   };\n//\n//   MockFoo foo;\n//   // Expects a call to non-const MockFoo::Bar().\n//   EXPECT_CALL(foo, Bar());\n//   // Expects a call to const MockFoo::Bar().\n//   EXPECT_CALL(Const(foo), Bar());\ntemplate <typename T>\ninline const T& Const(const T& x) {\n  return x;\n}\n\n// Constructs an Expectation object that references and co-owns exp.\ninline Expectation::Expectation(internal::ExpectationBase& exp)  // NOLINT\n    : expectation_base_(exp.GetHandle().expectation_base()) {}\n\n}  // namespace testing\n\nGTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251\n\n// Implementation for ON_CALL and EXPECT_CALL macros. A separate macro is\n// required to avoid compile errors when the name of the method used in call is\n// a result of macro expansion. See CompilesWithMethodNameExpandedFromMacro\n// tests in internal/gmock-spec-builders_test.cc for more details.\n//\n// This macro supports statements both with and without parameter matchers. If\n// the parameter list is omitted, gMock will accept any parameters, which allows\n// tests to be written that don't need to encode the number of method\n// parameter. This technique may only be used for non-overloaded methods.\n//\n//   // These are the same:\n//   ON_CALL(mock, NoArgsMethod()).WillByDefault(...);\n//   ON_CALL(mock, NoArgsMethod).WillByDefault(...);\n//\n//   // As are these:\n//   ON_CALL(mock, TwoArgsMethod(_, _)).WillByDefault(...);\n//   ON_CALL(mock, TwoArgsMethod).WillByDefault(...);\n//\n//   // Can also specify args if you want, of course:\n//   ON_CALL(mock, TwoArgsMethod(_, 45)).WillByDefault(...);\n//\n//   // Overloads work as long as you specify parameters:\n//   ON_CALL(mock, OverloadedMethod(_)).WillByDefault(...);\n//   ON_CALL(mock, OverloadedMethod(_, _)).WillByDefault(...);\n//\n//   // Oops! Which overload did you want?\n//   ON_CALL(mock, OverloadedMethod).WillByDefault(...);\n//     => ERROR: call to member function 'gmock_OverloadedMethod' is ambiguous\n//\n// How this works: The mock class uses two overloads of the gmock_Method\n// expectation setter method plus an operator() overload on the MockSpec object.\n// In the matcher list form, the macro expands to:\n//\n//   // This statement:\n//   ON_CALL(mock, TwoArgsMethod(_, 45))...\n//\n//   // ...expands to:\n//   mock.gmock_TwoArgsMethod(_, 45)(WithoutMatchers(), nullptr)...\n//   |-------------v---------------||------------v-------------|\n//       invokes first overload        swallowed by operator()\n//\n//   // ...which is essentially:\n//   mock.gmock_TwoArgsMethod(_, 45)...\n//\n// Whereas the form without a matcher list:\n//\n//   // This statement:\n//   ON_CALL(mock, TwoArgsMethod)...\n//\n//   // ...expands to:\n//   mock.gmock_TwoArgsMethod(WithoutMatchers(), nullptr)...\n//   |-----------------------v--------------------------|\n//                 invokes second overload\n//\n//   // ...which is essentially:\n//   mock.gmock_TwoArgsMethod(_, _)...\n//\n// The WithoutMatchers() argument is used to disambiguate overloads and to\n// block the caller from accidentally invoking the second overload directly. The\n// second argument is an internal type derived from the method signature. The\n// failure to disambiguate two overloads of this method in the ON_CALL statement\n// is how we block callers from setting expectations on overloaded methods.\n#define GMOCK_ON_CALL_IMPL_(mock_expr, Setter, call)                    \\\n  ((mock_expr).gmock_##call)(::testing::internal::GetWithoutMatchers(), \\\n                             nullptr)                                   \\\n      .Setter(__FILE__, __LINE__, #mock_expr, #call)\n\n#define ON_CALL(obj, call) \\\n  GMOCK_ON_CALL_IMPL_(obj, InternalDefaultActionSetAt, call)\n\n#define EXPECT_CALL(obj, call) \\\n  GMOCK_ON_CALL_IMPL_(obj, InternalExpectedAt, call)\n\n#endif  // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/include/gmock/gmock.h",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This is the main header file a user should include.\n\n#ifndef GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_\n#define GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_\n\n// This file implements the following syntax:\n//\n//   ON_CALL(mock_object, Method(...))\n//     .With(...) ?\n//     .WillByDefault(...);\n//\n// where With() is optional and WillByDefault() must appear exactly\n// once.\n//\n//   EXPECT_CALL(mock_object, Method(...))\n//     .With(...) ?\n//     .Times(...) ?\n//     .InSequence(...) *\n//     .WillOnce(...) *\n//     .WillRepeatedly(...) ?\n//     .RetiresOnSaturation() ? ;\n//\n// where all clauses are optional and WillOnce() can be repeated.\n\n#include \"gmock/gmock-actions.h\"\n#include \"gmock/gmock-cardinalities.h\"\n#include \"gmock/gmock-function-mocker.h\"\n#include \"gmock/gmock-matchers.h\"\n#include \"gmock/gmock-more-actions.h\"\n#include \"gmock/gmock-more-matchers.h\"\n#include \"gmock/gmock-nice-strict.h\"\n#include \"gmock/internal/gmock-internal-utils.h\"\n#include \"gmock/internal/gmock-port.h\"\n\n// Declares Google Mock flags that we want a user to use programmatically.\nGMOCK_DECLARE_bool_(catch_leaked_mocks);\nGMOCK_DECLARE_string_(verbose);\nGMOCK_DECLARE_int32_(default_mock_behavior);\n\nnamespace testing {\n\n// Initializes Google Mock.  This must be called before running the\n// tests.  In particular, it parses the command line for the flags\n// that Google Mock recognizes.  Whenever a Google Mock flag is seen,\n// it is removed from argv, and *argc is decremented.\n//\n// No value is returned.  Instead, the Google Mock flag variables are\n// updated.\n//\n// Since Google Test is needed for Google Mock to work, this function\n// also initializes Google Test and parses its flags, if that hasn't\n// been done.\nGTEST_API_ void InitGoogleMock(int* argc, char** argv);\n\n// This overloaded version can be used in Windows programs compiled in\n// UNICODE mode.\nGTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv);\n\n// This overloaded version can be used on Arduino/embedded platforms where\n// there is no argc/argv.\nGTEST_API_ void InitGoogleMock();\n\n}  // namespace testing\n\n#endif  // GOOGLEMOCK_INCLUDE_GMOCK_GMOCK_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/include/gmock/internal/custom/README.md",
    "content": "# Customization Points\n\nThe custom directory is an injection point for custom user configurations.\n\n## Header `gmock-port.h`\n\nThe following macros can be defined:\n\n### Flag related macros:\n\n*   `GMOCK_DECLARE_bool_(name)`\n*   `GMOCK_DECLARE_int32_(name)`\n*   `GMOCK_DECLARE_string_(name)`\n*   `GMOCK_DEFINE_bool_(name, default_val, doc)`\n*   `GMOCK_DEFINE_int32_(name, default_val, doc)`\n*   `GMOCK_DEFINE_string_(name, default_val, doc)`\n*   `GMOCK_FLAG_GET(flag_name)`\n*   `GMOCK_FLAG_SET(flag_name, value)`\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/include/gmock/internal/custom/gmock-generated-actions.h",
    "content": "// IWYU pragma: private, include \"gmock/gmock.h\"\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_\n#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_\n\n#endif  // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_GENERATED_ACTIONS_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/include/gmock/internal/custom/gmock-matchers.h",
    "content": "// Copyright 2015, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Injection point for custom user configurations. See README for details\n\n// IWYU pragma: private, include \"gmock/gmock.h\"\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_\n#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_\n#endif  // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_MATCHERS_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/include/gmock/internal/custom/gmock-port.h",
    "content": "// Copyright 2015, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Injection point for custom user configurations. See README for details\n//\n// ** Custom implementation starts here **\n\n// IWYU pragma: private, include \"gmock/gmock.h\"\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_\n#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_\n\n#endif  // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_CUSTOM_GMOCK_PORT_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/include/gmock/internal/gmock-internal-utils.h",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file defines some utilities useful for implementing Google\n// Mock.  They are subject to change without notice, so please DO NOT\n// USE THEM IN USER CODE.\n\n// IWYU pragma: private, include \"gmock/gmock.h\"\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_\n#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_\n\n#include <stdio.h>\n\n#include <ostream>  // NOLINT\n#include <string>\n#include <type_traits>\n#include <vector>\n\n#include \"gmock/internal/gmock-port.h\"\n#include \"gtest/gtest.h\"\n\nnamespace testing {\n\ntemplate <typename>\nclass Matcher;\n\nnamespace internal {\n\n// Silence MSVC C4100 (unreferenced formal parameter) and\n// C4805('==': unsafe mix of type 'const int' and type 'const bool')\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 4100)\n#pragma warning(disable : 4805)\n#endif\n\n// Joins a vector of strings as if they are fields of a tuple; returns\n// the joined string.\nGTEST_API_ std::string JoinAsKeyValueTuple(\n    const std::vector<const char*>& names, const Strings& values);\n\n// Converts an identifier name to a space-separated list of lower-case\n// words.  Each maximum substring of the form [A-Za-z][a-z]*|\\d+ is\n// treated as one word.  For example, both \"FooBar123\" and\n// \"foo_bar_123\" are converted to \"foo bar 123\".\nGTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name);\n\n// GetRawPointer(p) returns the raw pointer underlying p when p is a\n// smart pointer, or returns p itself when p is already a raw pointer.\n// The following default implementation is for the smart pointer case.\ntemplate <typename Pointer>\ninline const typename Pointer::element_type* GetRawPointer(const Pointer& p) {\n  return p.get();\n}\n// This overload version is for std::reference_wrapper, which does not work with\n// the overload above, as it does not have an `element_type`.\ntemplate <typename Element>\ninline const Element* GetRawPointer(const std::reference_wrapper<Element>& r) {\n  return &r.get();\n}\n\n// This overloaded version is for the raw pointer case.\ntemplate <typename Element>\ninline Element* GetRawPointer(Element* p) {\n  return p;\n}\n\n// MSVC treats wchar_t as a native type usually, but treats it as the\n// same as unsigned short when the compiler option /Zc:wchar_t- is\n// specified.  It defines _NATIVE_WCHAR_T_DEFINED symbol when wchar_t\n// is a native type.\n#if defined(_MSC_VER) && !defined(_NATIVE_WCHAR_T_DEFINED)\n// wchar_t is a typedef.\n#else\n#define GMOCK_WCHAR_T_IS_NATIVE_ 1\n#endif\n\n// In what follows, we use the term \"kind\" to indicate whether a type\n// is bool, an integer type (excluding bool), a floating-point type,\n// or none of them.  This categorization is useful for determining\n// when a matcher argument type can be safely converted to another\n// type in the implementation of SafeMatcherCast.\nenum TypeKind { kBool, kInteger, kFloatingPoint, kOther };\n\n// KindOf<T>::value is the kind of type T.\ntemplate <typename T>\nstruct KindOf {\n  enum { value = kOther };  // The default kind.\n};\n\n// This macro declares that the kind of 'type' is 'kind'.\n#define GMOCK_DECLARE_KIND_(type, kind) \\\n  template <>                           \\\n  struct KindOf<type> {                 \\\n    enum { value = kind };              \\\n  }\n\nGMOCK_DECLARE_KIND_(bool, kBool);\n\n// All standard integer types.\nGMOCK_DECLARE_KIND_(char, kInteger);\nGMOCK_DECLARE_KIND_(signed char, kInteger);\nGMOCK_DECLARE_KIND_(unsigned char, kInteger);\nGMOCK_DECLARE_KIND_(short, kInteger);           // NOLINT\nGMOCK_DECLARE_KIND_(unsigned short, kInteger);  // NOLINT\nGMOCK_DECLARE_KIND_(int, kInteger);\nGMOCK_DECLARE_KIND_(unsigned int, kInteger);\nGMOCK_DECLARE_KIND_(long, kInteger);                // NOLINT\nGMOCK_DECLARE_KIND_(unsigned long, kInteger);       // NOLINT\nGMOCK_DECLARE_KIND_(long long, kInteger);           // NOLINT\nGMOCK_DECLARE_KIND_(unsigned long long, kInteger);  // NOLINT\n\n#if GMOCK_WCHAR_T_IS_NATIVE_\nGMOCK_DECLARE_KIND_(wchar_t, kInteger);\n#endif\n\n// All standard floating-point types.\nGMOCK_DECLARE_KIND_(float, kFloatingPoint);\nGMOCK_DECLARE_KIND_(double, kFloatingPoint);\nGMOCK_DECLARE_KIND_(long double, kFloatingPoint);\n\n#undef GMOCK_DECLARE_KIND_\n\n// Evaluates to the kind of 'type'.\n#define GMOCK_KIND_OF_(type)                   \\\n  static_cast< ::testing::internal::TypeKind>( \\\n      ::testing::internal::KindOf<type>::value)\n\n// LosslessArithmeticConvertibleImpl<kFromKind, From, kToKind, To>::value\n// is true if and only if arithmetic type From can be losslessly converted to\n// arithmetic type To.\n//\n// It's the user's responsibility to ensure that both From and To are\n// raw (i.e. has no CV modifier, is not a pointer, and is not a\n// reference) built-in arithmetic types, kFromKind is the kind of\n// From, and kToKind is the kind of To; the value is\n// implementation-defined when the above pre-condition is violated.\ntemplate <TypeKind kFromKind, typename From, TypeKind kToKind, typename To>\nusing LosslessArithmeticConvertibleImpl = std::integral_constant<\n    bool,\n    // clang-format off\n      // Converting from bool is always lossless\n      (kFromKind == kBool) ? true\n      // Converting between any other type kinds will be lossy if the type\n      // kinds are not the same.\n    : (kFromKind != kToKind) ? false\n    : (kFromKind == kInteger &&\n       // Converting between integers of different widths is allowed so long\n       // as the conversion does not go from signed to unsigned.\n      (((sizeof(From) < sizeof(To)) &&\n        !(std::is_signed<From>::value && !std::is_signed<To>::value)) ||\n       // Converting between integers of the same width only requires the\n       // two types to have the same signedness.\n       ((sizeof(From) == sizeof(To)) &&\n        (std::is_signed<From>::value == std::is_signed<To>::value)))\n       ) ? true\n      // Floating point conversions are lossless if and only if `To` is at least\n      // as wide as `From`.\n    : (kFromKind == kFloatingPoint && (sizeof(From) <= sizeof(To))) ? true\n    : false\n    // clang-format on\n    >;\n\n// LosslessArithmeticConvertible<From, To>::value is true if and only if\n// arithmetic type From can be losslessly converted to arithmetic type To.\n//\n// It's the user's responsibility to ensure that both From and To are\n// raw (i.e. has no CV modifier, is not a pointer, and is not a\n// reference) built-in arithmetic types; the value is\n// implementation-defined when the above pre-condition is violated.\ntemplate <typename From, typename To>\nusing LosslessArithmeticConvertible =\n    LosslessArithmeticConvertibleImpl<GMOCK_KIND_OF_(From), From,\n                                      GMOCK_KIND_OF_(To), To>;\n\n// This interface knows how to report a Google Mock failure (either\n// non-fatal or fatal).\nclass FailureReporterInterface {\n public:\n  // The type of a failure (either non-fatal or fatal).\n  enum FailureType { kNonfatal, kFatal };\n\n  virtual ~FailureReporterInterface() {}\n\n  // Reports a failure that occurred at the given source file location.\n  virtual void ReportFailure(FailureType type, const char* file, int line,\n                             const std::string& message) = 0;\n};\n\n// Returns the failure reporter used by Google Mock.\nGTEST_API_ FailureReporterInterface* GetFailureReporter();\n\n// Asserts that condition is true; aborts the process with the given\n// message if condition is false.  We cannot use LOG(FATAL) or CHECK()\n// as Google Mock might be used to mock the log sink itself.  We\n// inline this function to prevent it from showing up in the stack\n// trace.\ninline void Assert(bool condition, const char* file, int line,\n                   const std::string& msg) {\n  if (!condition) {\n    GetFailureReporter()->ReportFailure(FailureReporterInterface::kFatal, file,\n                                        line, msg);\n  }\n}\ninline void Assert(bool condition, const char* file, int line) {\n  Assert(condition, file, line, \"Assertion failed.\");\n}\n\n// Verifies that condition is true; generates a non-fatal failure if\n// condition is false.\ninline void Expect(bool condition, const char* file, int line,\n                   const std::string& msg) {\n  if (!condition) {\n    GetFailureReporter()->ReportFailure(FailureReporterInterface::kNonfatal,\n                                        file, line, msg);\n  }\n}\ninline void Expect(bool condition, const char* file, int line) {\n  Expect(condition, file, line, \"Expectation failed.\");\n}\n\n// Severity level of a log.\nenum LogSeverity { kInfo = 0, kWarning = 1 };\n\n// Valid values for the --gmock_verbose flag.\n\n// All logs (informational and warnings) are printed.\nconst char kInfoVerbosity[] = \"info\";\n// Only warnings are printed.\nconst char kWarningVerbosity[] = \"warning\";\n// No logs are printed.\nconst char kErrorVerbosity[] = \"error\";\n\n// Returns true if and only if a log with the given severity is visible\n// according to the --gmock_verbose flag.\nGTEST_API_ bool LogIsVisible(LogSeverity severity);\n\n// Prints the given message to stdout if and only if 'severity' >= the level\n// specified by the --gmock_verbose flag.  If stack_frames_to_skip >=\n// 0, also prints the stack trace excluding the top\n// stack_frames_to_skip frames.  In opt mode, any positive\n// stack_frames_to_skip is treated as 0, since we don't know which\n// function calls will be inlined by the compiler and need to be\n// conservative.\nGTEST_API_ void Log(LogSeverity severity, const std::string& message,\n                    int stack_frames_to_skip);\n\n// A marker class that is used to resolve parameterless expectations to the\n// correct overload. This must not be instantiable, to prevent client code from\n// accidentally resolving to the overload; for example:\n//\n//    ON_CALL(mock, Method({}, nullptr))...\n//\nclass WithoutMatchers {\n private:\n  WithoutMatchers() {}\n  friend GTEST_API_ WithoutMatchers GetWithoutMatchers();\n};\n\n// Internal use only: access the singleton instance of WithoutMatchers.\nGTEST_API_ WithoutMatchers GetWithoutMatchers();\n\n// Disable MSVC warnings for infinite recursion, since in this case the\n// recursion is unreachable.\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 4717)\n#endif\n\n// Invalid<T>() is usable as an expression of type T, but will terminate\n// the program with an assertion failure if actually run.  This is useful\n// when a value of type T is needed for compilation, but the statement\n// will not really be executed (or we don't care if the statement\n// crashes).\ntemplate <typename T>\ninline T Invalid() {\n  Assert(false, \"\", -1, \"Internal error: attempt to return invalid value\");\n#if defined(__GNUC__) || defined(__clang__)\n  __builtin_unreachable();\n#elif defined(_MSC_VER)\n  __assume(0);\n#else\n  return Invalid<T>();\n#endif\n}\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n// Given a raw type (i.e. having no top-level reference or const\n// modifier) RawContainer that's either an STL-style container or a\n// native array, class StlContainerView<RawContainer> has the\n// following members:\n//\n//   - type is a type that provides an STL-style container view to\n//     (i.e. implements the STL container concept for) RawContainer;\n//   - const_reference is a type that provides a reference to a const\n//     RawContainer;\n//   - ConstReference(raw_container) returns a const reference to an STL-style\n//     container view to raw_container, which is a RawContainer.\n//   - Copy(raw_container) returns an STL-style container view of a\n//     copy of raw_container, which is a RawContainer.\n//\n// This generic version is used when RawContainer itself is already an\n// STL-style container.\ntemplate <class RawContainer>\nclass StlContainerView {\n public:\n  typedef RawContainer type;\n  typedef const type& const_reference;\n\n  static const_reference ConstReference(const RawContainer& container) {\n    static_assert(!std::is_const<RawContainer>::value,\n                  \"RawContainer type must not be const\");\n    return container;\n  }\n  static type Copy(const RawContainer& container) { return container; }\n};\n\n// This specialization is used when RawContainer is a native array type.\ntemplate <typename Element, size_t N>\nclass StlContainerView<Element[N]> {\n public:\n  typedef typename std::remove_const<Element>::type RawElement;\n  typedef internal::NativeArray<RawElement> type;\n  // NativeArray<T> can represent a native array either by value or by\n  // reference (selected by a constructor argument), so 'const type'\n  // can be used to reference a const native array.  We cannot\n  // 'typedef const type& const_reference' here, as that would mean\n  // ConstReference() has to return a reference to a local variable.\n  typedef const type const_reference;\n\n  static const_reference ConstReference(const Element (&array)[N]) {\n    static_assert(std::is_same<Element, RawElement>::value,\n                  \"Element type must not be const\");\n    return type(array, N, RelationToSourceReference());\n  }\n  static type Copy(const Element (&array)[N]) {\n    return type(array, N, RelationToSourceCopy());\n  }\n};\n\n// This specialization is used when RawContainer is a native array\n// represented as a (pointer, size) tuple.\ntemplate <typename ElementPointer, typename Size>\nclass StlContainerView< ::std::tuple<ElementPointer, Size> > {\n public:\n  typedef typename std::remove_const<\n      typename std::pointer_traits<ElementPointer>::element_type>::type\n      RawElement;\n  typedef internal::NativeArray<RawElement> type;\n  typedef const type const_reference;\n\n  static const_reference ConstReference(\n      const ::std::tuple<ElementPointer, Size>& array) {\n    return type(std::get<0>(array), std::get<1>(array),\n                RelationToSourceReference());\n  }\n  static type Copy(const ::std::tuple<ElementPointer, Size>& array) {\n    return type(std::get<0>(array), std::get<1>(array), RelationToSourceCopy());\n  }\n};\n\n// The following specialization prevents the user from instantiating\n// StlContainer with a reference type.\ntemplate <typename T>\nclass StlContainerView<T&>;\n\n// A type transform to remove constness from the first part of a pair.\n// Pairs like that are used as the value_type of associative containers,\n// and this transform produces a similar but assignable pair.\ntemplate <typename T>\nstruct RemoveConstFromKey {\n  typedef T type;\n};\n\n// Partially specialized to remove constness from std::pair<const K, V>.\ntemplate <typename K, typename V>\nstruct RemoveConstFromKey<std::pair<const K, V> > {\n  typedef std::pair<K, V> type;\n};\n\n// Emit an assertion failure due to incorrect DoDefault() usage. Out-of-lined to\n// reduce code size.\nGTEST_API_ void IllegalDoDefault(const char* file, int line);\n\ntemplate <typename F, typename Tuple, size_t... Idx>\nauto ApplyImpl(F&& f, Tuple&& args, IndexSequence<Idx...>)\n    -> decltype(std::forward<F>(f)(\n        std::get<Idx>(std::forward<Tuple>(args))...)) {\n  return std::forward<F>(f)(std::get<Idx>(std::forward<Tuple>(args))...);\n}\n\n// Apply the function to a tuple of arguments.\ntemplate <typename F, typename Tuple>\nauto Apply(F&& f, Tuple&& args) -> decltype(ApplyImpl(\n    std::forward<F>(f), std::forward<Tuple>(args),\n    MakeIndexSequence<std::tuple_size<\n        typename std::remove_reference<Tuple>::type>::value>())) {\n  return ApplyImpl(std::forward<F>(f), std::forward<Tuple>(args),\n                   MakeIndexSequence<std::tuple_size<\n                       typename std::remove_reference<Tuple>::type>::value>());\n}\n\n// Template struct Function<F>, where F must be a function type, contains\n// the following typedefs:\n//\n//   Result:               the function's return type.\n//   Arg<N>:               the type of the N-th argument, where N starts with 0.\n//   ArgumentTuple:        the tuple type consisting of all parameters of F.\n//   ArgumentMatcherTuple: the tuple type consisting of Matchers for all\n//                         parameters of F.\n//   MakeResultVoid:       the function type obtained by substituting void\n//                         for the return type of F.\n//   MakeResultIgnoredValue:\n//                         the function type obtained by substituting Something\n//                         for the return type of F.\ntemplate <typename T>\nstruct Function;\n\ntemplate <typename R, typename... Args>\nstruct Function<R(Args...)> {\n  using Result = R;\n  static constexpr size_t ArgumentCount = sizeof...(Args);\n  template <size_t I>\n  using Arg = ElemFromList<I, Args...>;\n  using ArgumentTuple = std::tuple<Args...>;\n  using ArgumentMatcherTuple = std::tuple<Matcher<Args>...>;\n  using MakeResultVoid = void(Args...);\n  using MakeResultIgnoredValue = IgnoredValue(Args...);\n};\n\ntemplate <typename R, typename... Args>\nconstexpr size_t Function<R(Args...)>::ArgumentCount;\n\nbool Base64Unescape(const std::string& encoded, std::string* decoded);\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n}  // namespace internal\n}  // namespace testing\n\n#endif  // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_INTERNAL_UTILS_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/include/gmock/internal/gmock-port.h",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Low-level types and utilities for porting Google Mock to various\n// platforms.  All macros ending with _ and symbols defined in an\n// internal namespace are subject to change without notice.  Code\n// outside Google Mock MUST NOT USE THEM DIRECTLY.  Macros that don't\n// end with _ are part of Google Mock's public API and can be used by\n// code outside Google Mock.\n\n// IWYU pragma: private, include \"gmock/gmock.h\"\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_\n#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_\n\n#include <assert.h>\n#include <stdlib.h>\n#include <cstdint>\n#include <iostream>\n\n// Most of the utilities needed for porting Google Mock are also\n// required for Google Test and are defined in gtest-port.h.\n//\n// Note to maintainers: to reduce code duplication, prefer adding\n// portability utilities to Google Test's gtest-port.h instead of\n// here, as Google Mock depends on Google Test.  Only add a utility\n// here if it's truly specific to Google Mock.\n\n#include \"gmock/internal/custom/gmock-port.h\"\n#include \"gtest/internal/gtest-port.h\"\n\n#if GTEST_HAS_ABSL\n#include \"absl/flags/declare.h\"\n#include \"absl/flags/flag.h\"\n#endif\n\n// For MS Visual C++, check the compiler version. At least VS 2015 is\n// required to compile Google Mock.\n#if defined(_MSC_VER) && _MSC_VER < 1900\n#error \"At least Visual C++ 2015 (14.0) is required to compile Google Mock.\"\n#endif\n\n// Macro for referencing flags.  This is public as we want the user to\n// use this syntax to reference Google Mock flags.\n#define GMOCK_FLAG_NAME_(name) gmock_##name\n#define GMOCK_FLAG(name) FLAGS_gmock_##name\n\n// Pick a command line flags implementation.\n#if GTEST_HAS_ABSL\n\n// Macros for defining flags.\n#define GMOCK_DEFINE_bool_(name, default_val, doc) \\\n  ABSL_FLAG(bool, GMOCK_FLAG_NAME_(name), default_val, doc)\n#define GMOCK_DEFINE_int32_(name, default_val, doc) \\\n  ABSL_FLAG(int32_t, GMOCK_FLAG_NAME_(name), default_val, doc)\n#define GMOCK_DEFINE_string_(name, default_val, doc) \\\n  ABSL_FLAG(std::string, GMOCK_FLAG_NAME_(name), default_val, doc)\n\n// Macros for declaring flags.\n#define GMOCK_DECLARE_bool_(name) \\\n  ABSL_DECLARE_FLAG(bool, GMOCK_FLAG_NAME_(name))\n#define GMOCK_DECLARE_int32_(name) \\\n  ABSL_DECLARE_FLAG(int32_t, GMOCK_FLAG_NAME_(name))\n#define GMOCK_DECLARE_string_(name) \\\n  ABSL_DECLARE_FLAG(std::string, GMOCK_FLAG_NAME_(name))\n\n#define GMOCK_FLAG_GET(name) ::absl::GetFlag(GMOCK_FLAG(name))\n#define GMOCK_FLAG_SET(name, value) \\\n  (void)(::absl::SetFlag(&GMOCK_FLAG(name), value))\n\n#else  // GTEST_HAS_ABSL\n\n// Macros for defining flags.\n#define GMOCK_DEFINE_bool_(name, default_val, doc)  \\\n  namespace testing {                               \\\n  GTEST_API_ bool GMOCK_FLAG(name) = (default_val); \\\n  }                                                 \\\n  static_assert(true, \"no-op to require trailing semicolon\")\n#define GMOCK_DEFINE_int32_(name, default_val, doc)    \\\n  namespace testing {                                  \\\n  GTEST_API_ int32_t GMOCK_FLAG(name) = (default_val); \\\n  }                                                    \\\n  static_assert(true, \"no-op to require trailing semicolon\")\n#define GMOCK_DEFINE_string_(name, default_val, doc)         \\\n  namespace testing {                                        \\\n  GTEST_API_ ::std::string GMOCK_FLAG(name) = (default_val); \\\n  }                                                          \\\n  static_assert(true, \"no-op to require trailing semicolon\")\n\n// Macros for declaring flags.\n#define GMOCK_DECLARE_bool_(name)          \\\n  namespace testing {                      \\\n  GTEST_API_ extern bool GMOCK_FLAG(name); \\\n  }                                        \\\n  static_assert(true, \"no-op to require trailing semicolon\")\n#define GMOCK_DECLARE_int32_(name)            \\\n  namespace testing {                         \\\n  GTEST_API_ extern int32_t GMOCK_FLAG(name); \\\n  }                                           \\\n  static_assert(true, \"no-op to require trailing semicolon\")\n#define GMOCK_DECLARE_string_(name)                 \\\n  namespace testing {                               \\\n  GTEST_API_ extern ::std::string GMOCK_FLAG(name); \\\n  }                                                 \\\n  static_assert(true, \"no-op to require trailing semicolon\")\n\n#define GMOCK_FLAG_GET(name) ::testing::GMOCK_FLAG(name)\n#define GMOCK_FLAG_SET(name, value) (void)(::testing::GMOCK_FLAG(name) = value)\n\n#endif  // GTEST_HAS_ABSL\n\n#endif  // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PORT_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/include/gmock/internal/gmock-pp.h",
    "content": "#ifndef GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_\n#define GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_\n\n// Expands and concatenates the arguments. Constructed macros reevaluate.\n#define GMOCK_PP_CAT(_1, _2) GMOCK_PP_INTERNAL_CAT(_1, _2)\n\n// Expands and stringifies the only argument.\n#define GMOCK_PP_STRINGIZE(...) GMOCK_PP_INTERNAL_STRINGIZE(__VA_ARGS__)\n\n// Returns empty. Given a variadic number of arguments.\n#define GMOCK_PP_EMPTY(...)\n\n// Returns a comma. Given a variadic number of arguments.\n#define GMOCK_PP_COMMA(...) ,\n\n// Returns the only argument.\n#define GMOCK_PP_IDENTITY(_1) _1\n\n// Evaluates to the number of arguments after expansion.\n//\n//   #define PAIR x, y\n//\n//   GMOCK_PP_NARG() => 1\n//   GMOCK_PP_NARG(x) => 1\n//   GMOCK_PP_NARG(x, y) => 2\n//   GMOCK_PP_NARG(PAIR) => 2\n//\n// Requires: the number of arguments after expansion is at most 15.\n#define GMOCK_PP_NARG(...) \\\n  GMOCK_PP_INTERNAL_16TH(  \\\n      (__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0))\n\n// Returns 1 if the expansion of arguments has an unprotected comma. Otherwise\n// returns 0. Requires no more than 15 unprotected commas.\n#define GMOCK_PP_HAS_COMMA(...) \\\n  GMOCK_PP_INTERNAL_16TH(       \\\n      (__VA_ARGS__, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0))\n\n// Returns the first argument.\n#define GMOCK_PP_HEAD(...) GMOCK_PP_INTERNAL_HEAD((__VA_ARGS__, unusedArg))\n\n// Returns the tail. A variadic list of all arguments minus the first. Requires\n// at least one argument.\n#define GMOCK_PP_TAIL(...) GMOCK_PP_INTERNAL_TAIL((__VA_ARGS__))\n\n// Calls CAT(_Macro, NARG(__VA_ARGS__))(__VA_ARGS__)\n#define GMOCK_PP_VARIADIC_CALL(_Macro, ...) \\\n  GMOCK_PP_IDENTITY(                        \\\n      GMOCK_PP_CAT(_Macro, GMOCK_PP_NARG(__VA_ARGS__))(__VA_ARGS__))\n\n// If the arguments after expansion have no tokens, evaluates to `1`. Otherwise\n// evaluates to `0`.\n//\n// Requires: * the number of arguments after expansion is at most 15.\n//           * If the argument is a macro, it must be able to be called with one\n//             argument.\n//\n// Implementation details:\n//\n// There is one case when it generates a compile error: if the argument is macro\n// that cannot be called with one argument.\n//\n//   #define M(a, b)  // it doesn't matter what it expands to\n//\n//   // Expected: expands to `0`.\n//   // Actual: compile error.\n//   GMOCK_PP_IS_EMPTY(M)\n//\n// There are 4 cases tested:\n//\n// * __VA_ARGS__ possible expansion has no unparen'd commas. Expected 0.\n// * __VA_ARGS__ possible expansion is not enclosed in parenthesis. Expected 0.\n// * __VA_ARGS__ possible expansion is not a macro that ()-evaluates to a comma.\n//   Expected 0\n// * __VA_ARGS__ is empty, or has unparen'd commas, or is enclosed in\n//   parenthesis, or is a macro that ()-evaluates to comma. Expected 1.\n//\n// We trigger detection on '0001', i.e. on empty.\n#define GMOCK_PP_IS_EMPTY(...)                                               \\\n  GMOCK_PP_INTERNAL_IS_EMPTY(GMOCK_PP_HAS_COMMA(__VA_ARGS__),                \\\n                             GMOCK_PP_HAS_COMMA(GMOCK_PP_COMMA __VA_ARGS__), \\\n                             GMOCK_PP_HAS_COMMA(__VA_ARGS__()),              \\\n                             GMOCK_PP_HAS_COMMA(GMOCK_PP_COMMA __VA_ARGS__()))\n\n// Evaluates to _Then if _Cond is 1 and _Else if _Cond is 0.\n#define GMOCK_PP_IF(_Cond, _Then, _Else) \\\n  GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IF_, _Cond)(_Then, _Else)\n\n// Similar to GMOCK_PP_IF but takes _Then and _Else in parentheses.\n//\n// GMOCK_PP_GENERIC_IF(1, (a, b, c), (d, e, f)) => a, b, c\n// GMOCK_PP_GENERIC_IF(0, (a, b, c), (d, e, f)) => d, e, f\n//\n#define GMOCK_PP_GENERIC_IF(_Cond, _Then, _Else) \\\n  GMOCK_PP_REMOVE_PARENS(GMOCK_PP_IF(_Cond, _Then, _Else))\n\n// Evaluates to the number of arguments after expansion. Identifies 'empty' as\n// 0.\n//\n//   #define PAIR x, y\n//\n//   GMOCK_PP_NARG0() => 0\n//   GMOCK_PP_NARG0(x) => 1\n//   GMOCK_PP_NARG0(x, y) => 2\n//   GMOCK_PP_NARG0(PAIR) => 2\n//\n// Requires: * the number of arguments after expansion is at most 15.\n//           * If the argument is a macro, it must be able to be called with one\n//             argument.\n#define GMOCK_PP_NARG0(...) \\\n  GMOCK_PP_IF(GMOCK_PP_IS_EMPTY(__VA_ARGS__), 0, GMOCK_PP_NARG(__VA_ARGS__))\n\n// Expands to 1 if the first argument starts with something in parentheses,\n// otherwise to 0.\n#define GMOCK_PP_IS_BEGIN_PARENS(...)                              \\\n  GMOCK_PP_HEAD(GMOCK_PP_CAT(GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_, \\\n                             GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C __VA_ARGS__))\n\n// Expands to 1 is there is only one argument and it is enclosed in parentheses.\n#define GMOCK_PP_IS_ENCLOSED_PARENS(...)             \\\n  GMOCK_PP_IF(GMOCK_PP_IS_BEGIN_PARENS(__VA_ARGS__), \\\n              GMOCK_PP_IS_EMPTY(GMOCK_PP_EMPTY __VA_ARGS__), 0)\n\n// Remove the parens, requires GMOCK_PP_IS_ENCLOSED_PARENS(args) => 1.\n#define GMOCK_PP_REMOVE_PARENS(...) GMOCK_PP_INTERNAL_REMOVE_PARENS __VA_ARGS__\n\n// Expands to _Macro(0, _Data, e1) _Macro(1, _Data, e2) ... _Macro(K -1, _Data,\n// eK) as many of GMOCK_INTERNAL_NARG0 _Tuple.\n// Requires: * |_Macro| can be called with 3 arguments.\n//           * |_Tuple| expansion has no more than 15 elements.\n#define GMOCK_PP_FOR_EACH(_Macro, _Data, _Tuple)                        \\\n  GMOCK_PP_CAT(GMOCK_PP_INTERNAL_FOR_EACH_IMPL_, GMOCK_PP_NARG0 _Tuple) \\\n  (0, _Macro, _Data, _Tuple)\n\n// Expands to _Macro(0, _Data, ) _Macro(1, _Data, ) ... _Macro(K - 1, _Data, )\n// Empty if _K = 0.\n// Requires: * |_Macro| can be called with 3 arguments.\n//           * |_K| literal between 0 and 15\n#define GMOCK_PP_REPEAT(_Macro, _Data, _N)           \\\n  GMOCK_PP_CAT(GMOCK_PP_INTERNAL_FOR_EACH_IMPL_, _N) \\\n  (0, _Macro, _Data, GMOCK_PP_INTENRAL_EMPTY_TUPLE)\n\n// Increments the argument, requires the argument to be between 0 and 15.\n#define GMOCK_PP_INC(_i) GMOCK_PP_CAT(GMOCK_PP_INTERNAL_INC_, _i)\n\n// Returns comma if _i != 0. Requires _i to be between 0 and 15.\n#define GMOCK_PP_COMMA_IF(_i) GMOCK_PP_CAT(GMOCK_PP_INTERNAL_COMMA_IF_, _i)\n\n// Internal details follow. Do not use any of these symbols outside of this\n// file or we will break your code.\n#define GMOCK_PP_INTENRAL_EMPTY_TUPLE (, , , , , , , , , , , , , , , )\n#define GMOCK_PP_INTERNAL_CAT(_1, _2) _1##_2\n#define GMOCK_PP_INTERNAL_STRINGIZE(...) #__VA_ARGS__\n#define GMOCK_PP_INTERNAL_CAT_5(_1, _2, _3, _4, _5) _1##_2##_3##_4##_5\n#define GMOCK_PP_INTERNAL_IS_EMPTY(_1, _2, _3, _4)                             \\\n  GMOCK_PP_HAS_COMMA(GMOCK_PP_INTERNAL_CAT_5(GMOCK_PP_INTERNAL_IS_EMPTY_CASE_, \\\n                                             _1, _2, _3, _4))\n#define GMOCK_PP_INTERNAL_IS_EMPTY_CASE_0001 ,\n#define GMOCK_PP_INTERNAL_IF_1(_Then, _Else) _Then\n#define GMOCK_PP_INTERNAL_IF_0(_Then, _Else) _Else\n\n// Because of MSVC treating a token with a comma in it as a single token when\n// passed to another macro, we need to force it to evaluate it as multiple\n// tokens. We do that by using a \"IDENTITY(MACRO PARENTHESIZED_ARGS)\" macro. We\n// define one per possible macro that relies on this behavior. Note \"_Args\" must\n// be parenthesized.\n#define GMOCK_PP_INTERNAL_INTERNAL_16TH(_1, _2, _3, _4, _5, _6, _7, _8, _9, \\\n                                        _10, _11, _12, _13, _14, _15, _16,  \\\n                                        ...)                                \\\n  _16\n#define GMOCK_PP_INTERNAL_16TH(_Args) \\\n  GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_16TH _Args)\n#define GMOCK_PP_INTERNAL_INTERNAL_HEAD(_1, ...) _1\n#define GMOCK_PP_INTERNAL_HEAD(_Args) \\\n  GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_HEAD _Args)\n#define GMOCK_PP_INTERNAL_INTERNAL_TAIL(_1, ...) __VA_ARGS__\n#define GMOCK_PP_INTERNAL_TAIL(_Args) \\\n  GMOCK_PP_IDENTITY(GMOCK_PP_INTERNAL_INTERNAL_TAIL _Args)\n\n#define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C(...) 1 _\n#define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_1 1,\n#define GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_R_GMOCK_PP_INTERNAL_IBP_IS_VARIADIC_C \\\n  0,\n#define GMOCK_PP_INTERNAL_REMOVE_PARENS(...) __VA_ARGS__\n#define GMOCK_PP_INTERNAL_INC_0 1\n#define GMOCK_PP_INTERNAL_INC_1 2\n#define GMOCK_PP_INTERNAL_INC_2 3\n#define GMOCK_PP_INTERNAL_INC_3 4\n#define GMOCK_PP_INTERNAL_INC_4 5\n#define GMOCK_PP_INTERNAL_INC_5 6\n#define GMOCK_PP_INTERNAL_INC_6 7\n#define GMOCK_PP_INTERNAL_INC_7 8\n#define GMOCK_PP_INTERNAL_INC_8 9\n#define GMOCK_PP_INTERNAL_INC_9 10\n#define GMOCK_PP_INTERNAL_INC_10 11\n#define GMOCK_PP_INTERNAL_INC_11 12\n#define GMOCK_PP_INTERNAL_INC_12 13\n#define GMOCK_PP_INTERNAL_INC_13 14\n#define GMOCK_PP_INTERNAL_INC_14 15\n#define GMOCK_PP_INTERNAL_INC_15 16\n#define GMOCK_PP_INTERNAL_COMMA_IF_0\n#define GMOCK_PP_INTERNAL_COMMA_IF_1 ,\n#define GMOCK_PP_INTERNAL_COMMA_IF_2 ,\n#define GMOCK_PP_INTERNAL_COMMA_IF_3 ,\n#define GMOCK_PP_INTERNAL_COMMA_IF_4 ,\n#define GMOCK_PP_INTERNAL_COMMA_IF_5 ,\n#define GMOCK_PP_INTERNAL_COMMA_IF_6 ,\n#define GMOCK_PP_INTERNAL_COMMA_IF_7 ,\n#define GMOCK_PP_INTERNAL_COMMA_IF_8 ,\n#define GMOCK_PP_INTERNAL_COMMA_IF_9 ,\n#define GMOCK_PP_INTERNAL_COMMA_IF_10 ,\n#define GMOCK_PP_INTERNAL_COMMA_IF_11 ,\n#define GMOCK_PP_INTERNAL_COMMA_IF_12 ,\n#define GMOCK_PP_INTERNAL_COMMA_IF_13 ,\n#define GMOCK_PP_INTERNAL_COMMA_IF_14 ,\n#define GMOCK_PP_INTERNAL_COMMA_IF_15 ,\n#define GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, _element) \\\n  _Macro(_i, _Data, _element)\n#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_0(_i, _Macro, _Data, _Tuple)\n#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_1(_i, _Macro, _Data, _Tuple) \\\n  GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple)\n#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_2(_i, _Macro, _Data, _Tuple)    \\\n  GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \\\n  GMOCK_PP_INTERNAL_FOR_EACH_IMPL_1(GMOCK_PP_INC(_i), _Macro, _Data,    \\\n                                    (GMOCK_PP_TAIL _Tuple))\n#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_3(_i, _Macro, _Data, _Tuple)    \\\n  GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \\\n  GMOCK_PP_INTERNAL_FOR_EACH_IMPL_2(GMOCK_PP_INC(_i), _Macro, _Data,    \\\n                                    (GMOCK_PP_TAIL _Tuple))\n#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_4(_i, _Macro, _Data, _Tuple)    \\\n  GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \\\n  GMOCK_PP_INTERNAL_FOR_EACH_IMPL_3(GMOCK_PP_INC(_i), _Macro, _Data,    \\\n                                    (GMOCK_PP_TAIL _Tuple))\n#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_5(_i, _Macro, _Data, _Tuple)    \\\n  GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \\\n  GMOCK_PP_INTERNAL_FOR_EACH_IMPL_4(GMOCK_PP_INC(_i), _Macro, _Data,    \\\n                                    (GMOCK_PP_TAIL _Tuple))\n#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_6(_i, _Macro, _Data, _Tuple)    \\\n  GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \\\n  GMOCK_PP_INTERNAL_FOR_EACH_IMPL_5(GMOCK_PP_INC(_i), _Macro, _Data,    \\\n                                    (GMOCK_PP_TAIL _Tuple))\n#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_7(_i, _Macro, _Data, _Tuple)    \\\n  GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \\\n  GMOCK_PP_INTERNAL_FOR_EACH_IMPL_6(GMOCK_PP_INC(_i), _Macro, _Data,    \\\n                                    (GMOCK_PP_TAIL _Tuple))\n#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_8(_i, _Macro, _Data, _Tuple)    \\\n  GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \\\n  GMOCK_PP_INTERNAL_FOR_EACH_IMPL_7(GMOCK_PP_INC(_i), _Macro, _Data,    \\\n                                    (GMOCK_PP_TAIL _Tuple))\n#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_9(_i, _Macro, _Data, _Tuple)    \\\n  GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \\\n  GMOCK_PP_INTERNAL_FOR_EACH_IMPL_8(GMOCK_PP_INC(_i), _Macro, _Data,    \\\n                                    (GMOCK_PP_TAIL _Tuple))\n#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_10(_i, _Macro, _Data, _Tuple)   \\\n  GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \\\n  GMOCK_PP_INTERNAL_FOR_EACH_IMPL_9(GMOCK_PP_INC(_i), _Macro, _Data,    \\\n                                    (GMOCK_PP_TAIL _Tuple))\n#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_11(_i, _Macro, _Data, _Tuple)   \\\n  GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \\\n  GMOCK_PP_INTERNAL_FOR_EACH_IMPL_10(GMOCK_PP_INC(_i), _Macro, _Data,   \\\n                                     (GMOCK_PP_TAIL _Tuple))\n#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_12(_i, _Macro, _Data, _Tuple)   \\\n  GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \\\n  GMOCK_PP_INTERNAL_FOR_EACH_IMPL_11(GMOCK_PP_INC(_i), _Macro, _Data,   \\\n                                     (GMOCK_PP_TAIL _Tuple))\n#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_13(_i, _Macro, _Data, _Tuple)   \\\n  GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \\\n  GMOCK_PP_INTERNAL_FOR_EACH_IMPL_12(GMOCK_PP_INC(_i), _Macro, _Data,   \\\n                                     (GMOCK_PP_TAIL _Tuple))\n#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_14(_i, _Macro, _Data, _Tuple)   \\\n  GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \\\n  GMOCK_PP_INTERNAL_FOR_EACH_IMPL_13(GMOCK_PP_INC(_i), _Macro, _Data,   \\\n                                     (GMOCK_PP_TAIL _Tuple))\n#define GMOCK_PP_INTERNAL_FOR_EACH_IMPL_15(_i, _Macro, _Data, _Tuple)   \\\n  GMOCK_PP_INTERNAL_CALL_MACRO(_Macro, _i, _Data, GMOCK_PP_HEAD _Tuple) \\\n  GMOCK_PP_INTERNAL_FOR_EACH_IMPL_14(GMOCK_PP_INC(_i), _Macro, _Data,   \\\n                                     (GMOCK_PP_TAIL _Tuple))\n\n#endif  // GOOGLEMOCK_INCLUDE_GMOCK_INTERNAL_GMOCK_PP_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/src/gmock-all.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// Google C++ Mocking Framework (Google Mock)\n//\n// This file #includes all Google Mock implementation .cc files.  The\n// purpose is to allow a user to build Google Mock by compiling this\n// file alone.\n\n// This line ensures that gmock.h can be compiled on its own, even\n// when it's fused.\n#include \"gmock/gmock.h\"\n\n// The following lines pull in the real gmock *.cc files.\n#include \"src/gmock-cardinalities.cc\"\n#include \"src/gmock-internal-utils.cc\"\n#include \"src/gmock-matchers.cc\"\n#include \"src/gmock-spec-builders.cc\"\n#include \"src/gmock.cc\"\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/src/gmock-cardinalities.cc",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file implements cardinalities.\n\n#include \"gmock/gmock-cardinalities.h\"\n\n#include <limits.h>\n\n#include <ostream>  // NOLINT\n#include <sstream>\n#include <string>\n\n#include \"gmock/internal/gmock-internal-utils.h\"\n#include \"gtest/gtest.h\"\n\nnamespace testing {\n\nnamespace {\n\n// Implements the Between(m, n) cardinality.\nclass BetweenCardinalityImpl : public CardinalityInterface {\n public:\n  BetweenCardinalityImpl(int min, int max)\n      : min_(min >= 0 ? min : 0), max_(max >= min_ ? max : min_) {\n    std::stringstream ss;\n    if (min < 0) {\n      ss << \"The invocation lower bound must be >= 0, \"\n         << \"but is actually \" << min << \".\";\n      internal::Expect(false, __FILE__, __LINE__, ss.str());\n    } else if (max < 0) {\n      ss << \"The invocation upper bound must be >= 0, \"\n         << \"but is actually \" << max << \".\";\n      internal::Expect(false, __FILE__, __LINE__, ss.str());\n    } else if (min > max) {\n      ss << \"The invocation upper bound (\" << max\n         << \") must be >= the invocation lower bound (\" << min << \").\";\n      internal::Expect(false, __FILE__, __LINE__, ss.str());\n    }\n  }\n\n  // Conservative estimate on the lower/upper bound of the number of\n  // calls allowed.\n  int ConservativeLowerBound() const override { return min_; }\n  int ConservativeUpperBound() const override { return max_; }\n\n  bool IsSatisfiedByCallCount(int call_count) const override {\n    return min_ <= call_count && call_count <= max_;\n  }\n\n  bool IsSaturatedByCallCount(int call_count) const override {\n    return call_count >= max_;\n  }\n\n  void DescribeTo(::std::ostream* os) const override;\n\n private:\n  const int min_;\n  const int max_;\n\n  BetweenCardinalityImpl(const BetweenCardinalityImpl&) = delete;\n  BetweenCardinalityImpl& operator=(const BetweenCardinalityImpl&) = delete;\n};\n\n// Formats \"n times\" in a human-friendly way.\ninline std::string FormatTimes(int n) {\n  if (n == 1) {\n    return \"once\";\n  } else if (n == 2) {\n    return \"twice\";\n  } else {\n    std::stringstream ss;\n    ss << n << \" times\";\n    return ss.str();\n  }\n}\n\n// Describes the Between(m, n) cardinality in human-friendly text.\nvoid BetweenCardinalityImpl::DescribeTo(::std::ostream* os) const {\n  if (min_ == 0) {\n    if (max_ == 0) {\n      *os << \"never called\";\n    } else if (max_ == INT_MAX) {\n      *os << \"called any number of times\";\n    } else {\n      *os << \"called at most \" << FormatTimes(max_);\n    }\n  } else if (min_ == max_) {\n    *os << \"called \" << FormatTimes(min_);\n  } else if (max_ == INT_MAX) {\n    *os << \"called at least \" << FormatTimes(min_);\n  } else {\n    // 0 < min_ < max_ < INT_MAX\n    *os << \"called between \" << min_ << \" and \" << max_ << \" times\";\n  }\n}\n\n}  // Unnamed namespace\n\n// Describes the given call count to an ostream.\nvoid Cardinality::DescribeActualCallCountTo(int actual_call_count,\n                                            ::std::ostream* os) {\n  if (actual_call_count > 0) {\n    *os << \"called \" << FormatTimes(actual_call_count);\n  } else {\n    *os << \"never called\";\n  }\n}\n\n// Creates a cardinality that allows at least n calls.\nGTEST_API_ Cardinality AtLeast(int n) { return Between(n, INT_MAX); }\n\n// Creates a cardinality that allows at most n calls.\nGTEST_API_ Cardinality AtMost(int n) { return Between(0, n); }\n\n// Creates a cardinality that allows any number of calls.\nGTEST_API_ Cardinality AnyNumber() { return AtLeast(0); }\n\n// Creates a cardinality that allows between min and max calls.\nGTEST_API_ Cardinality Between(int min, int max) {\n  return Cardinality(new BetweenCardinalityImpl(min, max));\n}\n\n// Creates a cardinality that allows exactly n calls.\nGTEST_API_ Cardinality Exactly(int n) { return Between(n, n); }\n\n}  // namespace testing\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/src/gmock-internal-utils.cc",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file defines some utilities useful for implementing Google\n// Mock.  They are subject to change without notice, so please DO NOT\n// USE THEM IN USER CODE.\n\n#include \"gmock/internal/gmock-internal-utils.h\"\n\n#include <ctype.h>\n\n#include <array>\n#include <cctype>\n#include <cstdint>\n#include <cstring>\n#include <ostream>  // NOLINT\n#include <string>\n#include <vector>\n\n#include \"gmock/gmock.h\"\n#include \"gmock/internal/gmock-port.h\"\n#include \"gtest/gtest.h\"\n\nnamespace testing {\nnamespace internal {\n\n// Joins a vector of strings as if they are fields of a tuple; returns\n// the joined string.\nGTEST_API_ std::string JoinAsKeyValueTuple(\n    const std::vector<const char*>& names, const Strings& values) {\n  GTEST_CHECK_(names.size() == values.size());\n  if (values.empty()) {\n    return \"\";\n  }\n  const auto build_one = [&](const size_t i) {\n    return std::string(names[i]) + \": \" + values[i];\n  };\n  std::string result = \"(\" + build_one(0);\n  for (size_t i = 1; i < values.size(); i++) {\n    result += \", \";\n    result += build_one(i);\n  }\n  result += \")\";\n  return result;\n}\n\n// Converts an identifier name to a space-separated list of lower-case\n// words.  Each maximum substring of the form [A-Za-z][a-z]*|\\d+ is\n// treated as one word.  For example, both \"FooBar123\" and\n// \"foo_bar_123\" are converted to \"foo bar 123\".\nGTEST_API_ std::string ConvertIdentifierNameToWords(const char* id_name) {\n  std::string result;\n  char prev_char = '\\0';\n  for (const char* p = id_name; *p != '\\0'; prev_char = *(p++)) {\n    // We don't care about the current locale as the input is\n    // guaranteed to be a valid C++ identifier name.\n    const bool starts_new_word = IsUpper(*p) ||\n                                 (!IsAlpha(prev_char) && IsLower(*p)) ||\n                                 (!IsDigit(prev_char) && IsDigit(*p));\n\n    if (IsAlNum(*p)) {\n      if (starts_new_word && result != \"\") result += ' ';\n      result += ToLower(*p);\n    }\n  }\n  return result;\n}\n\n// This class reports Google Mock failures as Google Test failures.  A\n// user can define another class in a similar fashion if they intend to\n// use Google Mock with a testing framework other than Google Test.\nclass GoogleTestFailureReporter : public FailureReporterInterface {\n public:\n  void ReportFailure(FailureType type, const char* file, int line,\n                     const std::string& message) override {\n    AssertHelper(type == kFatal ? TestPartResult::kFatalFailure\n                                : TestPartResult::kNonFatalFailure,\n                 file, line, message.c_str()) = Message();\n    if (type == kFatal) {\n      posix::Abort();\n    }\n  }\n};\n\n// Returns the global failure reporter.  Will create a\n// GoogleTestFailureReporter and return it the first time called.\nGTEST_API_ FailureReporterInterface* GetFailureReporter() {\n  // Points to the global failure reporter used by Google Mock.  gcc\n  // guarantees that the following use of failure_reporter is\n  // thread-safe.  We may need to add additional synchronization to\n  // protect failure_reporter if we port Google Mock to other\n  // compilers.\n  static FailureReporterInterface* const failure_reporter =\n      new GoogleTestFailureReporter();\n  return failure_reporter;\n}\n\n// Protects global resources (stdout in particular) used by Log().\nstatic GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex);\n\n// Returns true if and only if a log with the given severity is visible\n// according to the --gmock_verbose flag.\nGTEST_API_ bool LogIsVisible(LogSeverity severity) {\n  if (GMOCK_FLAG_GET(verbose) == kInfoVerbosity) {\n    // Always show the log if --gmock_verbose=info.\n    return true;\n  } else if (GMOCK_FLAG_GET(verbose) == kErrorVerbosity) {\n    // Always hide it if --gmock_verbose=error.\n    return false;\n  } else {\n    // If --gmock_verbose is neither \"info\" nor \"error\", we treat it\n    // as \"warning\" (its default value).\n    return severity == kWarning;\n  }\n}\n\n// Prints the given message to stdout if and only if 'severity' >= the level\n// specified by the --gmock_verbose flag.  If stack_frames_to_skip >=\n// 0, also prints the stack trace excluding the top\n// stack_frames_to_skip frames.  In opt mode, any positive\n// stack_frames_to_skip is treated as 0, since we don't know which\n// function calls will be inlined by the compiler and need to be\n// conservative.\nGTEST_API_ void Log(LogSeverity severity, const std::string& message,\n                    int stack_frames_to_skip) {\n  if (!LogIsVisible(severity)) return;\n\n  // Ensures that logs from different threads don't interleave.\n  MutexLock l(&g_log_mutex);\n\n  if (severity == kWarning) {\n    // Prints a GMOCK WARNING marker to make the warnings easily searchable.\n    std::cout << \"\\nGMOCK WARNING:\";\n  }\n  // Pre-pends a new-line to message if it doesn't start with one.\n  if (message.empty() || message[0] != '\\n') {\n    std::cout << \"\\n\";\n  }\n  std::cout << message;\n  if (stack_frames_to_skip >= 0) {\n#ifdef NDEBUG\n    // In opt mode, we have to be conservative and skip no stack frame.\n    const int actual_to_skip = 0;\n#else\n    // In dbg mode, we can do what the caller tell us to do (plus one\n    // for skipping this function's stack frame).\n    const int actual_to_skip = stack_frames_to_skip + 1;\n#endif  // NDEBUG\n\n    // Appends a new-line to message if it doesn't end with one.\n    if (!message.empty() && *message.rbegin() != '\\n') {\n      std::cout << \"\\n\";\n    }\n    std::cout << \"Stack trace:\\n\"\n              << ::testing::internal::GetCurrentOsStackTraceExceptTop(\n                     ::testing::UnitTest::GetInstance(), actual_to_skip);\n  }\n  std::cout << ::std::flush;\n}\n\nGTEST_API_ WithoutMatchers GetWithoutMatchers() { return WithoutMatchers(); }\n\nGTEST_API_ void IllegalDoDefault(const char* file, int line) {\n  internal::Assert(\n      false, file, line,\n      \"You are using DoDefault() inside a composite action like \"\n      \"DoAll() or WithArgs().  This is not supported for technical \"\n      \"reasons.  Please instead spell out the default action, or \"\n      \"assign the default action to an Action variable and use \"\n      \"the variable in various places.\");\n}\n\nconstexpr char UnBase64Impl(char c, const char* const base64, char carry) {\n  return *base64 == 0   ? static_cast<char>(65)\n         : *base64 == c ? carry\n                        : UnBase64Impl(c, base64 + 1, carry + 1);\n}\n\ntemplate <size_t... I>\nconstexpr std::array<char, 256> UnBase64Impl(IndexSequence<I...>,\n                                             const char* const base64) {\n  return {{UnBase64Impl(static_cast<char>(I), base64, 0)...}};\n}\n\nconstexpr std::array<char, 256> UnBase64(const char* const base64) {\n  return UnBase64Impl(MakeIndexSequence<256>{}, base64);\n}\n\nstatic constexpr char kBase64[] =\n    \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nstatic constexpr std::array<char, 256> kUnBase64 = UnBase64(kBase64);\n\nbool Base64Unescape(const std::string& encoded, std::string* decoded) {\n  decoded->clear();\n  size_t encoded_len = encoded.size();\n  decoded->reserve(3 * (encoded_len / 4) + (encoded_len % 4));\n  int bit_pos = 0;\n  char dst = 0;\n  for (int src : encoded) {\n    if (std::isspace(src) || src == '=') {\n      continue;\n    }\n    char src_bin = kUnBase64[static_cast<size_t>(src)];\n    if (src_bin >= 64) {\n      decoded->clear();\n      return false;\n    }\n    if (bit_pos == 0) {\n      dst |= static_cast<char>(src_bin << 2);\n      bit_pos = 6;\n    } else {\n      dst |= static_cast<char>(src_bin >> (bit_pos - 2));\n      decoded->push_back(dst);\n      dst = static_cast<char>(src_bin << (10 - bit_pos));\n      bit_pos = (bit_pos + 6) % 8;\n    }\n  }\n  return true;\n}\n\n}  // namespace internal\n}  // namespace testing\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/src/gmock-matchers.cc",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file implements Matcher<const string&>, Matcher<string>, and\n// utilities for defining matchers.\n\n#include \"gmock/gmock-matchers.h\"\n\n#include <string.h>\n\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nnamespace testing {\nnamespace internal {\n\n// Returns the description for a matcher defined using the MATCHER*()\n// macro where the user-supplied description string is \"\", if\n// 'negation' is false; otherwise returns the description of the\n// negation of the matcher.  'param_values' contains a list of strings\n// that are the print-out of the matcher's parameters.\nGTEST_API_ std::string FormatMatcherDescription(\n    bool negation, const char* matcher_name,\n    const std::vector<const char*>& param_names, const Strings& param_values) {\n  std::string result = ConvertIdentifierNameToWords(matcher_name);\n  if (param_values.size() >= 1) {\n    result += \" \" + JoinAsKeyValueTuple(param_names, param_values);\n  }\n  return negation ? \"not (\" + result + \")\" : result;\n}\n\n// FindMaxBipartiteMatching and its helper class.\n//\n// Uses the well-known Ford-Fulkerson max flow method to find a maximum\n// bipartite matching. Flow is considered to be from left to right.\n// There is an implicit source node that is connected to all of the left\n// nodes, and an implicit sink node that is connected to all of the\n// right nodes. All edges have unit capacity.\n//\n// Neither the flow graph nor the residual flow graph are represented\n// explicitly. Instead, they are implied by the information in 'graph' and\n// a vector<int> called 'left_' whose elements are initialized to the\n// value kUnused. This represents the initial state of the algorithm,\n// where the flow graph is empty, and the residual flow graph has the\n// following edges:\n//   - An edge from source to each left_ node\n//   - An edge from each right_ node to sink\n//   - An edge from each left_ node to each right_ node, if the\n//     corresponding edge exists in 'graph'.\n//\n// When the TryAugment() method adds a flow, it sets left_[l] = r for some\n// nodes l and r. This induces the following changes:\n//   - The edges (source, l), (l, r), and (r, sink) are added to the\n//     flow graph.\n//   - The same three edges are removed from the residual flow graph.\n//   - The reverse edges (l, source), (r, l), and (sink, r) are added\n//     to the residual flow graph, which is a directional graph\n//     representing unused flow capacity.\n//\n// When the method augments a flow (moving left_[l] from some r1 to some\n// other r2), this can be thought of as \"undoing\" the above steps with\n// respect to r1 and \"redoing\" them with respect to r2.\n//\n// It bears repeating that the flow graph and residual flow graph are\n// never represented explicitly, but can be derived by looking at the\n// information in 'graph' and in left_.\n//\n// As an optimization, there is a second vector<int> called right_ which\n// does not provide any new information. Instead, it enables more\n// efficient queries about edges entering or leaving the right-side nodes\n// of the flow or residual flow graphs. The following invariants are\n// maintained:\n//\n// left[l] == kUnused or right[left[l]] == l\n// right[r] == kUnused or left[right[r]] == r\n//\n// . [ source ]                                        .\n// .   |||                                             .\n// .   |||                                             .\n// .   ||\\--> left[0]=1  ---\\    right[0]=-1 ----\\     .\n// .   ||                   |                    |     .\n// .   |\\---> left[1]=-1    \\--> right[1]=0  ---\\|     .\n// .   |                                        ||     .\n// .   \\----> left[2]=2  ------> right[2]=2  --\\||     .\n// .                                           |||     .\n// .         elements           matchers       vvv     .\n// .                                         [ sink ]  .\n//\n// See Also:\n//   [1] Cormen, et al (2001). \"Section 26.2: The Ford-Fulkerson method\".\n//       \"Introduction to Algorithms (Second ed.)\", pp. 651-664.\n//   [2] \"Ford-Fulkerson algorithm\", Wikipedia,\n//       'http://en.wikipedia.org/wiki/Ford%E2%80%93Fulkerson_algorithm'\nclass MaxBipartiteMatchState {\n public:\n  explicit MaxBipartiteMatchState(const MatchMatrix& graph)\n      : graph_(&graph),\n        left_(graph_->LhsSize(), kUnused),\n        right_(graph_->RhsSize(), kUnused) {}\n\n  // Returns the edges of a maximal match, each in the form {left, right}.\n  ElementMatcherPairs Compute() {\n    // 'seen' is used for path finding { 0: unseen, 1: seen }.\n    ::std::vector<char> seen;\n    // Searches the residual flow graph for a path from each left node to\n    // the sink in the residual flow graph, and if one is found, add flow\n    // to the graph. It's okay to search through the left nodes once. The\n    // edge from the implicit source node to each previously-visited left\n    // node will have flow if that left node has any path to the sink\n    // whatsoever. Subsequent augmentations can only add flow to the\n    // network, and cannot take away that previous flow unit from the source.\n    // Since the source-to-left edge can only carry one flow unit (or,\n    // each element can be matched to only one matcher), there is no need\n    // to visit the left nodes more than once looking for augmented paths.\n    // The flow is known to be possible or impossible by looking at the\n    // node once.\n    for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {\n      // Reset the path-marking vector and try to find a path from\n      // source to sink starting at the left_[ilhs] node.\n      GTEST_CHECK_(left_[ilhs] == kUnused)\n          << \"ilhs: \" << ilhs << \", left_[ilhs]: \" << left_[ilhs];\n      // 'seen' initialized to 'graph_->RhsSize()' copies of 0.\n      seen.assign(graph_->RhsSize(), 0);\n      TryAugment(ilhs, &seen);\n    }\n    ElementMatcherPairs result;\n    for (size_t ilhs = 0; ilhs < left_.size(); ++ilhs) {\n      size_t irhs = left_[ilhs];\n      if (irhs == kUnused) continue;\n      result.push_back(ElementMatcherPair(ilhs, irhs));\n    }\n    return result;\n  }\n\n private:\n  static const size_t kUnused = static_cast<size_t>(-1);\n\n  // Perform a depth-first search from left node ilhs to the sink.  If a\n  // path is found, flow is added to the network by linking the left and\n  // right vector elements corresponding each segment of the path.\n  // Returns true if a path to sink was found, which means that a unit of\n  // flow was added to the network. The 'seen' vector elements correspond\n  // to right nodes and are marked to eliminate cycles from the search.\n  //\n  // Left nodes will only be explored at most once because they\n  // are accessible from at most one right node in the residual flow\n  // graph.\n  //\n  // Note that left_[ilhs] is the only element of left_ that TryAugment will\n  // potentially transition from kUnused to another value. Any other\n  // left_ element holding kUnused before TryAugment will be holding it\n  // when TryAugment returns.\n  //\n  bool TryAugment(size_t ilhs, ::std::vector<char>* seen) {\n    for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {\n      if ((*seen)[irhs]) continue;\n      if (!graph_->HasEdge(ilhs, irhs)) continue;\n      // There's an available edge from ilhs to irhs.\n      (*seen)[irhs] = 1;\n      // Next a search is performed to determine whether\n      // this edge is a dead end or leads to the sink.\n      //\n      // right_[irhs] == kUnused means that there is residual flow from\n      // right node irhs to the sink, so we can use that to finish this\n      // flow path and return success.\n      //\n      // Otherwise there is residual flow to some ilhs. We push flow\n      // along that path and call ourselves recursively to see if this\n      // ultimately leads to sink.\n      if (right_[irhs] == kUnused || TryAugment(right_[irhs], seen)) {\n        // Add flow from left_[ilhs] to right_[irhs].\n        left_[ilhs] = irhs;\n        right_[irhs] = ilhs;\n        return true;\n      }\n    }\n    return false;\n  }\n\n  const MatchMatrix* graph_;  // not owned\n  // Each element of the left_ vector represents a left hand side node\n  // (i.e. an element) and each element of right_ is a right hand side\n  // node (i.e. a matcher). The values in the left_ vector indicate\n  // outflow from that node to a node on the right_ side. The values\n  // in the right_ indicate inflow, and specify which left_ node is\n  // feeding that right_ node, if any. For example, left_[3] == 1 means\n  // there's a flow from element #3 to matcher #1. Such a flow would also\n  // be redundantly represented in the right_ vector as right_[1] == 3.\n  // Elements of left_ and right_ are either kUnused or mutually\n  // referent. Mutually referent means that left_[right_[i]] = i and\n  // right_[left_[i]] = i.\n  ::std::vector<size_t> left_;\n  ::std::vector<size_t> right_;\n};\n\nconst size_t MaxBipartiteMatchState::kUnused;\n\nGTEST_API_ ElementMatcherPairs FindMaxBipartiteMatching(const MatchMatrix& g) {\n  return MaxBipartiteMatchState(g).Compute();\n}\n\nstatic void LogElementMatcherPairVec(const ElementMatcherPairs& pairs,\n                                     ::std::ostream* stream) {\n  typedef ElementMatcherPairs::const_iterator Iter;\n  ::std::ostream& os = *stream;\n  os << \"{\";\n  const char* sep = \"\";\n  for (Iter it = pairs.begin(); it != pairs.end(); ++it) {\n    os << sep << \"\\n  (\"\n       << \"element #\" << it->first << \", \"\n       << \"matcher #\" << it->second << \")\";\n    sep = \",\";\n  }\n  os << \"\\n}\";\n}\n\nbool MatchMatrix::NextGraph() {\n  for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {\n    for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {\n      char& b = matched_[SpaceIndex(ilhs, irhs)];\n      if (!b) {\n        b = 1;\n        return true;\n      }\n      b = 0;\n    }\n  }\n  return false;\n}\n\nvoid MatchMatrix::Randomize() {\n  for (size_t ilhs = 0; ilhs < LhsSize(); ++ilhs) {\n    for (size_t irhs = 0; irhs < RhsSize(); ++irhs) {\n      char& b = matched_[SpaceIndex(ilhs, irhs)];\n      b = static_cast<char>(rand() & 1);  // NOLINT\n    }\n  }\n}\n\nstd::string MatchMatrix::DebugString() const {\n  ::std::stringstream ss;\n  const char* sep = \"\";\n  for (size_t i = 0; i < LhsSize(); ++i) {\n    ss << sep;\n    for (size_t j = 0; j < RhsSize(); ++j) {\n      ss << HasEdge(i, j);\n    }\n    sep = \";\";\n  }\n  return ss.str();\n}\n\nvoid UnorderedElementsAreMatcherImplBase::DescribeToImpl(\n    ::std::ostream* os) const {\n  switch (match_flags()) {\n    case UnorderedMatcherRequire::ExactMatch:\n      if (matcher_describers_.empty()) {\n        *os << \"is empty\";\n        return;\n      }\n      if (matcher_describers_.size() == 1) {\n        *os << \"has \" << Elements(1) << \" and that element \";\n        matcher_describers_[0]->DescribeTo(os);\n        return;\n      }\n      *os << \"has \" << Elements(matcher_describers_.size())\n          << \" and there exists some permutation of elements such that:\\n\";\n      break;\n    case UnorderedMatcherRequire::Superset:\n      *os << \"a surjection from elements to requirements exists such that:\\n\";\n      break;\n    case UnorderedMatcherRequire::Subset:\n      *os << \"an injection from elements to requirements exists such that:\\n\";\n      break;\n  }\n\n  const char* sep = \"\";\n  for (size_t i = 0; i != matcher_describers_.size(); ++i) {\n    *os << sep;\n    if (match_flags() == UnorderedMatcherRequire::ExactMatch) {\n      *os << \" - element #\" << i << \" \";\n    } else {\n      *os << \" - an element \";\n    }\n    matcher_describers_[i]->DescribeTo(os);\n    if (match_flags() == UnorderedMatcherRequire::ExactMatch) {\n      sep = \", and\\n\";\n    } else {\n      sep = \"\\n\";\n    }\n  }\n}\n\nvoid UnorderedElementsAreMatcherImplBase::DescribeNegationToImpl(\n    ::std::ostream* os) const {\n  switch (match_flags()) {\n    case UnorderedMatcherRequire::ExactMatch:\n      if (matcher_describers_.empty()) {\n        *os << \"isn't empty\";\n        return;\n      }\n      if (matcher_describers_.size() == 1) {\n        *os << \"doesn't have \" << Elements(1) << \", or has \" << Elements(1)\n            << \" that \";\n        matcher_describers_[0]->DescribeNegationTo(os);\n        return;\n      }\n      *os << \"doesn't have \" << Elements(matcher_describers_.size())\n          << \", or there exists no permutation of elements such that:\\n\";\n      break;\n    case UnorderedMatcherRequire::Superset:\n      *os << \"no surjection from elements to requirements exists such that:\\n\";\n      break;\n    case UnorderedMatcherRequire::Subset:\n      *os << \"no injection from elements to requirements exists such that:\\n\";\n      break;\n  }\n  const char* sep = \"\";\n  for (size_t i = 0; i != matcher_describers_.size(); ++i) {\n    *os << sep;\n    if (match_flags() == UnorderedMatcherRequire::ExactMatch) {\n      *os << \" - element #\" << i << \" \";\n    } else {\n      *os << \" - an element \";\n    }\n    matcher_describers_[i]->DescribeTo(os);\n    if (match_flags() == UnorderedMatcherRequire::ExactMatch) {\n      sep = \", and\\n\";\n    } else {\n      sep = \"\\n\";\n    }\n  }\n}\n\n// Checks that all matchers match at least one element, and that all\n// elements match at least one matcher. This enables faster matching\n// and better error reporting.\n// Returns false, writing an explanation to 'listener', if and only\n// if the success criteria are not met.\nbool UnorderedElementsAreMatcherImplBase::VerifyMatchMatrix(\n    const ::std::vector<std::string>& element_printouts,\n    const MatchMatrix& matrix, MatchResultListener* listener) const {\n  bool result = true;\n  ::std::vector<char> element_matched(matrix.LhsSize(), 0);\n  ::std::vector<char> matcher_matched(matrix.RhsSize(), 0);\n\n  for (size_t ilhs = 0; ilhs < matrix.LhsSize(); ilhs++) {\n    for (size_t irhs = 0; irhs < matrix.RhsSize(); irhs++) {\n      char matched = matrix.HasEdge(ilhs, irhs);\n      element_matched[ilhs] |= matched;\n      matcher_matched[irhs] |= matched;\n    }\n  }\n\n  if (match_flags() & UnorderedMatcherRequire::Superset) {\n    const char* sep =\n        \"where the following matchers don't match any elements:\\n\";\n    for (size_t mi = 0; mi < matcher_matched.size(); ++mi) {\n      if (matcher_matched[mi]) continue;\n      result = false;\n      if (listener->IsInterested()) {\n        *listener << sep << \"matcher #\" << mi << \": \";\n        matcher_describers_[mi]->DescribeTo(listener->stream());\n        sep = \",\\n\";\n      }\n    }\n  }\n\n  if (match_flags() & UnorderedMatcherRequire::Subset) {\n    const char* sep =\n        \"where the following elements don't match any matchers:\\n\";\n    const char* outer_sep = \"\";\n    if (!result) {\n      outer_sep = \"\\nand \";\n    }\n    for (size_t ei = 0; ei < element_matched.size(); ++ei) {\n      if (element_matched[ei]) continue;\n      result = false;\n      if (listener->IsInterested()) {\n        *listener << outer_sep << sep << \"element #\" << ei << \": \"\n                  << element_printouts[ei];\n        sep = \",\\n\";\n        outer_sep = \"\";\n      }\n    }\n  }\n  return result;\n}\n\nbool UnorderedElementsAreMatcherImplBase::FindPairing(\n    const MatchMatrix& matrix, MatchResultListener* listener) const {\n  ElementMatcherPairs matches = FindMaxBipartiteMatching(matrix);\n\n  size_t max_flow = matches.size();\n  if ((match_flags() & UnorderedMatcherRequire::Superset) &&\n      max_flow < matrix.RhsSize()) {\n    if (listener->IsInterested()) {\n      *listener << \"where no permutation of the elements can satisfy all \"\n                   \"matchers, and the closest match is \"\n                << max_flow << \" of \" << matrix.RhsSize()\n                << \" matchers with the pairings:\\n\";\n      LogElementMatcherPairVec(matches, listener->stream());\n    }\n    return false;\n  }\n  if ((match_flags() & UnorderedMatcherRequire::Subset) &&\n      max_flow < matrix.LhsSize()) {\n    if (listener->IsInterested()) {\n      *listener\n          << \"where not all elements can be matched, and the closest match is \"\n          << max_flow << \" of \" << matrix.RhsSize()\n          << \" matchers with the pairings:\\n\";\n      LogElementMatcherPairVec(matches, listener->stream());\n    }\n    return false;\n  }\n\n  if (matches.size() > 1) {\n    if (listener->IsInterested()) {\n      const char* sep = \"where:\\n\";\n      for (size_t mi = 0; mi < matches.size(); ++mi) {\n        *listener << sep << \" - element #\" << matches[mi].first\n                  << \" is matched by matcher #\" << matches[mi].second;\n        sep = \",\\n\";\n      }\n    }\n  }\n  return true;\n}\n\n}  // namespace internal\n}  // namespace testing\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/src/gmock-spec-builders.cc",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file implements the spec builder syntax (ON_CALL and\n// EXPECT_CALL).\n\n#include \"gmock/gmock-spec-builders.h\"\n\n#include <stdlib.h>\n\n#include <iostream>  // NOLINT\n#include <map>\n#include <memory>\n#include <set>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n#include \"gtest/internal/gtest-port.h\"\n\n#if GTEST_OS_CYGWIN || GTEST_OS_LINUX || GTEST_OS_MAC\n#include <unistd.h>  // NOLINT\n#endif\n\n// Silence C4800 (C4800: 'int *const ': forcing value\n// to bool 'true' or 'false') for MSVC 15\n#ifdef _MSC_VER\n#if _MSC_VER == 1900\n#pragma warning(push)\n#pragma warning(disable : 4800)\n#endif\n#endif\n\nnamespace testing {\nnamespace internal {\n\n// Protects the mock object registry (in class Mock), all function\n// mockers, and all expectations.\nGTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_gmock_mutex);\n\n// Logs a message including file and line number information.\nGTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,\n                                const char* file, int line,\n                                const std::string& message) {\n  ::std::ostringstream s;\n  s << internal::FormatFileLocation(file, line) << \" \" << message\n    << ::std::endl;\n  Log(severity, s.str(), 0);\n}\n\n// Constructs an ExpectationBase object.\nExpectationBase::ExpectationBase(const char* a_file, int a_line,\n                                 const std::string& a_source_text)\n    : file_(a_file),\n      line_(a_line),\n      source_text_(a_source_text),\n      cardinality_specified_(false),\n      cardinality_(Exactly(1)),\n      call_count_(0),\n      retired_(false),\n      extra_matcher_specified_(false),\n      repeated_action_specified_(false),\n      retires_on_saturation_(false),\n      last_clause_(kNone),\n      action_count_checked_(false) {}\n\n// Destructs an ExpectationBase object.\nExpectationBase::~ExpectationBase() {}\n\n// Explicitly specifies the cardinality of this expectation.  Used by\n// the subclasses to implement the .Times() clause.\nvoid ExpectationBase::SpecifyCardinality(const Cardinality& a_cardinality) {\n  cardinality_specified_ = true;\n  cardinality_ = a_cardinality;\n}\n\n// Retires all pre-requisites of this expectation.\nvoid ExpectationBase::RetireAllPreRequisites()\n    GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n  if (is_retired()) {\n    // We can take this short-cut as we never retire an expectation\n    // until we have retired all its pre-requisites.\n    return;\n  }\n\n  ::std::vector<ExpectationBase*> expectations(1, this);\n  while (!expectations.empty()) {\n    ExpectationBase* exp = expectations.back();\n    expectations.pop_back();\n\n    for (ExpectationSet::const_iterator it =\n             exp->immediate_prerequisites_.begin();\n         it != exp->immediate_prerequisites_.end(); ++it) {\n      ExpectationBase* next = it->expectation_base().get();\n      if (!next->is_retired()) {\n        next->Retire();\n        expectations.push_back(next);\n      }\n    }\n  }\n}\n\n// Returns true if and only if all pre-requisites of this expectation\n// have been satisfied.\nbool ExpectationBase::AllPrerequisitesAreSatisfied() const\n    GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n  g_gmock_mutex.AssertHeld();\n  ::std::vector<const ExpectationBase*> expectations(1, this);\n  while (!expectations.empty()) {\n    const ExpectationBase* exp = expectations.back();\n    expectations.pop_back();\n\n    for (ExpectationSet::const_iterator it =\n             exp->immediate_prerequisites_.begin();\n         it != exp->immediate_prerequisites_.end(); ++it) {\n      const ExpectationBase* next = it->expectation_base().get();\n      if (!next->IsSatisfied()) return false;\n      expectations.push_back(next);\n    }\n  }\n  return true;\n}\n\n// Adds unsatisfied pre-requisites of this expectation to 'result'.\nvoid ExpectationBase::FindUnsatisfiedPrerequisites(ExpectationSet* result) const\n    GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n  g_gmock_mutex.AssertHeld();\n  ::std::vector<const ExpectationBase*> expectations(1, this);\n  while (!expectations.empty()) {\n    const ExpectationBase* exp = expectations.back();\n    expectations.pop_back();\n\n    for (ExpectationSet::const_iterator it =\n             exp->immediate_prerequisites_.begin();\n         it != exp->immediate_prerequisites_.end(); ++it) {\n      const ExpectationBase* next = it->expectation_base().get();\n\n      if (next->IsSatisfied()) {\n        // If *it is satisfied and has a call count of 0, some of its\n        // pre-requisites may not be satisfied yet.\n        if (next->call_count_ == 0) {\n          expectations.push_back(next);\n        }\n      } else {\n        // Now that we know next is unsatisfied, we are not so interested\n        // in whether its pre-requisites are satisfied.  Therefore we\n        // don't iterate into it here.\n        *result += *it;\n      }\n    }\n  }\n}\n\n// Describes how many times a function call matching this\n// expectation has occurred.\nvoid ExpectationBase::DescribeCallCountTo(::std::ostream* os) const\n    GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n  g_gmock_mutex.AssertHeld();\n\n  // Describes how many times the function is expected to be called.\n  *os << \"         Expected: to be \";\n  cardinality().DescribeTo(os);\n  *os << \"\\n           Actual: \";\n  Cardinality::DescribeActualCallCountTo(call_count(), os);\n\n  // Describes the state of the expectation (e.g. is it satisfied?\n  // is it active?).\n  *os << \" - \"\n      << (IsOverSaturated() ? \"over-saturated\"\n          : IsSaturated()   ? \"saturated\"\n          : IsSatisfied()   ? \"satisfied\"\n                            : \"unsatisfied\")\n      << \" and \" << (is_retired() ? \"retired\" : \"active\");\n}\n\n// Checks the action count (i.e. the number of WillOnce() and\n// WillRepeatedly() clauses) against the cardinality if this hasn't\n// been done before.  Prints a warning if there are too many or too\n// few actions.\nvoid ExpectationBase::CheckActionCountIfNotDone() const\n    GTEST_LOCK_EXCLUDED_(mutex_) {\n  bool should_check = false;\n  {\n    MutexLock l(&mutex_);\n    if (!action_count_checked_) {\n      action_count_checked_ = true;\n      should_check = true;\n    }\n  }\n\n  if (should_check) {\n    if (!cardinality_specified_) {\n      // The cardinality was inferred - no need to check the action\n      // count against it.\n      return;\n    }\n\n    // The cardinality was explicitly specified.\n    const int action_count = static_cast<int>(untyped_actions_.size());\n    const int upper_bound = cardinality().ConservativeUpperBound();\n    const int lower_bound = cardinality().ConservativeLowerBound();\n    bool too_many;  // True if there are too many actions, or false\n    // if there are too few.\n    if (action_count > upper_bound ||\n        (action_count == upper_bound && repeated_action_specified_)) {\n      too_many = true;\n    } else if (0 < action_count && action_count < lower_bound &&\n               !repeated_action_specified_) {\n      too_many = false;\n    } else {\n      return;\n    }\n\n    ::std::stringstream ss;\n    DescribeLocationTo(&ss);\n    ss << \"Too \" << (too_many ? \"many\" : \"few\") << \" actions specified in \"\n       << source_text() << \"...\\n\"\n       << \"Expected to be \";\n    cardinality().DescribeTo(&ss);\n    ss << \", but has \" << (too_many ? \"\" : \"only \") << action_count\n       << \" WillOnce()\" << (action_count == 1 ? \"\" : \"s\");\n    if (repeated_action_specified_) {\n      ss << \" and a WillRepeatedly()\";\n    }\n    ss << \".\";\n    Log(kWarning, ss.str(), -1);  // -1 means \"don't print stack trace\".\n  }\n}\n\n// Implements the .Times() clause.\nvoid ExpectationBase::UntypedTimes(const Cardinality& a_cardinality) {\n  if (last_clause_ == kTimes) {\n    ExpectSpecProperty(false,\n                       \".Times() cannot appear \"\n                       \"more than once in an EXPECT_CALL().\");\n  } else {\n    ExpectSpecProperty(\n        last_clause_ < kTimes,\n        \".Times() may only appear *before* .InSequence(), .WillOnce(), \"\n        \".WillRepeatedly(), or .RetiresOnSaturation(), not after.\");\n  }\n  last_clause_ = kTimes;\n\n  SpecifyCardinality(a_cardinality);\n}\n\n// Points to the implicit sequence introduced by a living InSequence\n// object (if any) in the current thread or NULL.\nGTEST_API_ ThreadLocal<Sequence*> g_gmock_implicit_sequence;\n\n// Reports an uninteresting call (whose description is in msg) in the\n// manner specified by 'reaction'.\nvoid ReportUninterestingCall(CallReaction reaction, const std::string& msg) {\n  // Include a stack trace only if --gmock_verbose=info is specified.\n  const int stack_frames_to_skip =\n      GMOCK_FLAG_GET(verbose) == kInfoVerbosity ? 3 : -1;\n  switch (reaction) {\n    case kAllow:\n      Log(kInfo, msg, stack_frames_to_skip);\n      break;\n    case kWarn:\n      Log(kWarning,\n          msg +\n              \"\\nNOTE: You can safely ignore the above warning unless this \"\n              \"call should not happen.  Do not suppress it by blindly adding \"\n              \"an EXPECT_CALL() if you don't mean to enforce the call.  \"\n              \"See \"\n              \"https://github.com/google/googletest/blob/master/docs/\"\n              \"gmock_cook_book.md#\"\n              \"knowing-when-to-expect for details.\\n\",\n          stack_frames_to_skip);\n      break;\n    default:  // FAIL\n      Expect(false, nullptr, -1, msg);\n  }\n}\n\nUntypedFunctionMockerBase::UntypedFunctionMockerBase()\n    : mock_obj_(nullptr), name_(\"\") {}\n\nUntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}\n\n// Sets the mock object this mock method belongs to, and registers\n// this information in the global mock registry.  Will be called\n// whenever an EXPECT_CALL() or ON_CALL() is executed on this mock\n// method.\nvoid UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)\n    GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {\n  {\n    MutexLock l(&g_gmock_mutex);\n    mock_obj_ = mock_obj;\n  }\n  Mock::Register(mock_obj, this);\n}\n\n// Sets the mock object this mock method belongs to, and sets the name\n// of the mock function.  Will be called upon each invocation of this\n// mock function.\nvoid UntypedFunctionMockerBase::SetOwnerAndName(const void* mock_obj,\n                                                const char* name)\n    GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {\n  // We protect name_ under g_gmock_mutex in case this mock function\n  // is called from two threads concurrently.\n  MutexLock l(&g_gmock_mutex);\n  mock_obj_ = mock_obj;\n  name_ = name;\n}\n\n// Returns the name of the function being mocked.  Must be called\n// after RegisterOwner() or SetOwnerAndName() has been called.\nconst void* UntypedFunctionMockerBase::MockObject() const\n    GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {\n  const void* mock_obj;\n  {\n    // We protect mock_obj_ under g_gmock_mutex in case this mock\n    // function is called from two threads concurrently.\n    MutexLock l(&g_gmock_mutex);\n    Assert(mock_obj_ != nullptr, __FILE__, __LINE__,\n           \"MockObject() must not be called before RegisterOwner() or \"\n           \"SetOwnerAndName() has been called.\");\n    mock_obj = mock_obj_;\n  }\n  return mock_obj;\n}\n\n// Returns the name of this mock method.  Must be called after\n// SetOwnerAndName() has been called.\nconst char* UntypedFunctionMockerBase::Name() const\n    GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {\n  const char* name;\n  {\n    // We protect name_ under g_gmock_mutex in case this mock\n    // function is called from two threads concurrently.\n    MutexLock l(&g_gmock_mutex);\n    Assert(name_ != nullptr, __FILE__, __LINE__,\n           \"Name() must not be called before SetOwnerAndName() has \"\n           \"been called.\");\n    name = name_;\n  }\n  return name;\n}\n\n// Returns an Expectation object that references and co-owns exp,\n// which must be an expectation on this mock function.\nExpectation UntypedFunctionMockerBase::GetHandleOf(ExpectationBase* exp) {\n  // See the definition of untyped_expectations_ for why access to it\n  // is unprotected here.\n  for (UntypedExpectations::const_iterator it = untyped_expectations_.begin();\n       it != untyped_expectations_.end(); ++it) {\n    if (it->get() == exp) {\n      return Expectation(*it);\n    }\n  }\n\n  Assert(false, __FILE__, __LINE__, \"Cannot find expectation.\");\n  return Expectation();\n  // The above statement is just to make the code compile, and will\n  // never be executed.\n}\n\n// Verifies that all expectations on this mock function have been\n// satisfied.  Reports one or more Google Test non-fatal failures\n// and returns false if not.\nbool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()\n    GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {\n  g_gmock_mutex.AssertHeld();\n  bool expectations_met = true;\n  for (UntypedExpectations::const_iterator it = untyped_expectations_.begin();\n       it != untyped_expectations_.end(); ++it) {\n    ExpectationBase* const untyped_expectation = it->get();\n    if (untyped_expectation->IsOverSaturated()) {\n      // There was an upper-bound violation.  Since the error was\n      // already reported when it occurred, there is no need to do\n      // anything here.\n      expectations_met = false;\n    } else if (!untyped_expectation->IsSatisfied()) {\n      expectations_met = false;\n      ::std::stringstream ss;\n      ss << \"Actual function call count doesn't match \"\n         << untyped_expectation->source_text() << \"...\\n\";\n      // No need to show the source file location of the expectation\n      // in the description, as the Expect() call that follows already\n      // takes care of it.\n      untyped_expectation->MaybeDescribeExtraMatcherTo(&ss);\n      untyped_expectation->DescribeCallCountTo(&ss);\n      Expect(false, untyped_expectation->file(), untyped_expectation->line(),\n             ss.str());\n    }\n  }\n\n  // Deleting our expectations may trigger other mock objects to be deleted, for\n  // example if an action contains a reference counted smart pointer to that\n  // mock object, and that is the last reference. So if we delete our\n  // expectations within the context of the global mutex we may deadlock when\n  // this method is called again. Instead, make a copy of the set of\n  // expectations to delete, clear our set within the mutex, and then clear the\n  // copied set outside of it.\n  UntypedExpectations expectations_to_delete;\n  untyped_expectations_.swap(expectations_to_delete);\n\n  g_gmock_mutex.Unlock();\n  expectations_to_delete.clear();\n  g_gmock_mutex.Lock();\n\n  return expectations_met;\n}\n\nCallReaction intToCallReaction(int mock_behavior) {\n  if (mock_behavior >= kAllow && mock_behavior <= kFail) {\n    return static_cast<internal::CallReaction>(mock_behavior);\n  }\n  return kWarn;\n}\n\n}  // namespace internal\n\n// Class Mock.\n\nnamespace {\n\ntypedef std::set<internal::UntypedFunctionMockerBase*> FunctionMockers;\n\n// The current state of a mock object.  Such information is needed for\n// detecting leaked mock objects and explicitly verifying a mock's\n// expectations.\nstruct MockObjectState {\n  MockObjectState()\n      : first_used_file(nullptr), first_used_line(-1), leakable(false) {}\n\n  // Where in the source file an ON_CALL or EXPECT_CALL is first\n  // invoked on this mock object.\n  const char* first_used_file;\n  int first_used_line;\n  ::std::string first_used_test_suite;\n  ::std::string first_used_test;\n  bool leakable;  // true if and only if it's OK to leak the object.\n  FunctionMockers function_mockers;  // All registered methods of the object.\n};\n\n// A global registry holding the state of all mock objects that are\n// alive.  A mock object is added to this registry the first time\n// Mock::AllowLeak(), ON_CALL(), or EXPECT_CALL() is called on it.  It\n// is removed from the registry in the mock object's destructor.\nclass MockObjectRegistry {\n public:\n  // Maps a mock object (identified by its address) to its state.\n  typedef std::map<const void*, MockObjectState> StateMap;\n\n  // This destructor will be called when a program exits, after all\n  // tests in it have been run.  By then, there should be no mock\n  // object alive.  Therefore we report any living object as test\n  // failure, unless the user explicitly asked us to ignore it.\n  ~MockObjectRegistry() {\n    if (!GMOCK_FLAG_GET(catch_leaked_mocks)) return;\n\n    int leaked_count = 0;\n    for (StateMap::const_iterator it = states_.begin(); it != states_.end();\n         ++it) {\n      if (it->second.leakable)  // The user said it's fine to leak this object.\n        continue;\n\n      // FIXME: Print the type of the leaked object.\n      // This can help the user identify the leaked object.\n      std::cout << \"\\n\";\n      const MockObjectState& state = it->second;\n      std::cout << internal::FormatFileLocation(state.first_used_file,\n                                                state.first_used_line);\n      std::cout << \" ERROR: this mock object\";\n      if (state.first_used_test != \"\") {\n        std::cout << \" (used in test \" << state.first_used_test_suite << \".\"\n                  << state.first_used_test << \")\";\n      }\n      std::cout << \" should be deleted but never is. Its address is @\"\n                << it->first << \".\";\n      leaked_count++;\n    }\n    if (leaked_count > 0) {\n      std::cout << \"\\nERROR: \" << leaked_count << \" leaked mock \"\n                << (leaked_count == 1 ? \"object\" : \"objects\")\n                << \" found at program exit. Expectations on a mock object are \"\n                   \"verified when the object is destructed. Leaking a mock \"\n                   \"means that its expectations aren't verified, which is \"\n                   \"usually a test bug. If you really intend to leak a mock, \"\n                   \"you can suppress this error using \"\n                   \"testing::Mock::AllowLeak(mock_object), or you may use a \"\n                   \"fake or stub instead of a mock.\\n\";\n      std::cout.flush();\n      ::std::cerr.flush();\n      // RUN_ALL_TESTS() has already returned when this destructor is\n      // called.  Therefore we cannot use the normal Google Test\n      // failure reporting mechanism.\n      _exit(1);  // We cannot call exit() as it is not reentrant and\n                 // may already have been called.\n    }\n  }\n\n  StateMap& states() { return states_; }\n\n private:\n  StateMap states_;\n};\n\n// Protected by g_gmock_mutex.\nMockObjectRegistry g_mock_object_registry;\n\n// Maps a mock object to the reaction Google Mock should have when an\n// uninteresting method is called.  Protected by g_gmock_mutex.\nstd::unordered_map<uintptr_t, internal::CallReaction>&\nUninterestingCallReactionMap() {\n  static auto* map = new std::unordered_map<uintptr_t, internal::CallReaction>;\n  return *map;\n}\n\n// Sets the reaction Google Mock should have when an uninteresting\n// method of the given mock object is called.\nvoid SetReactionOnUninterestingCalls(uintptr_t mock_obj,\n                                     internal::CallReaction reaction)\n    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n  internal::MutexLock l(&internal::g_gmock_mutex);\n  UninterestingCallReactionMap()[mock_obj] = reaction;\n}\n\n}  // namespace\n\n// Tells Google Mock to allow uninteresting calls on the given mock\n// object.\nvoid Mock::AllowUninterestingCalls(uintptr_t mock_obj)\n    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n  SetReactionOnUninterestingCalls(mock_obj, internal::kAllow);\n}\n\n// Tells Google Mock to warn the user about uninteresting calls on the\n// given mock object.\nvoid Mock::WarnUninterestingCalls(uintptr_t mock_obj)\n    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n  SetReactionOnUninterestingCalls(mock_obj, internal::kWarn);\n}\n\n// Tells Google Mock to fail uninteresting calls on the given mock\n// object.\nvoid Mock::FailUninterestingCalls(uintptr_t mock_obj)\n    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n  SetReactionOnUninterestingCalls(mock_obj, internal::kFail);\n}\n\n// Tells Google Mock the given mock object is being destroyed and its\n// entry in the call-reaction table should be removed.\nvoid Mock::UnregisterCallReaction(uintptr_t mock_obj)\n    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n  internal::MutexLock l(&internal::g_gmock_mutex);\n  UninterestingCallReactionMap().erase(static_cast<uintptr_t>(mock_obj));\n}\n\n// Returns the reaction Google Mock will have on uninteresting calls\n// made on the given mock object.\ninternal::CallReaction Mock::GetReactionOnUninterestingCalls(\n    const void* mock_obj) GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n  internal::MutexLock l(&internal::g_gmock_mutex);\n  return (UninterestingCallReactionMap().count(\n              reinterpret_cast<uintptr_t>(mock_obj)) == 0)\n             ? internal::intToCallReaction(\n                   GMOCK_FLAG_GET(default_mock_behavior))\n             : UninterestingCallReactionMap()[reinterpret_cast<uintptr_t>(\n                   mock_obj)];\n}\n\n// Tells Google Mock to ignore mock_obj when checking for leaked mock\n// objects.\nvoid Mock::AllowLeak(const void* mock_obj)\n    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n  internal::MutexLock l(&internal::g_gmock_mutex);\n  g_mock_object_registry.states()[mock_obj].leakable = true;\n}\n\n// Verifies and clears all expectations on the given mock object.  If\n// the expectations aren't satisfied, generates one or more Google\n// Test non-fatal failures and returns false.\nbool Mock::VerifyAndClearExpectations(void* mock_obj)\n    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n  internal::MutexLock l(&internal::g_gmock_mutex);\n  return VerifyAndClearExpectationsLocked(mock_obj);\n}\n\n// Verifies all expectations on the given mock object and clears its\n// default actions and expectations.  Returns true if and only if the\n// verification was successful.\nbool Mock::VerifyAndClear(void* mock_obj)\n    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n  internal::MutexLock l(&internal::g_gmock_mutex);\n  ClearDefaultActionsLocked(mock_obj);\n  return VerifyAndClearExpectationsLocked(mock_obj);\n}\n\n// Verifies and clears all expectations on the given mock object.  If\n// the expectations aren't satisfied, generates one or more Google\n// Test non-fatal failures and returns false.\nbool Mock::VerifyAndClearExpectationsLocked(void* mock_obj)\n    GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {\n  internal::g_gmock_mutex.AssertHeld();\n  if (g_mock_object_registry.states().count(mock_obj) == 0) {\n    // No EXPECT_CALL() was set on the given mock object.\n    return true;\n  }\n\n  // Verifies and clears the expectations on each mock method in the\n  // given mock object.\n  bool expectations_met = true;\n  FunctionMockers& mockers =\n      g_mock_object_registry.states()[mock_obj].function_mockers;\n  for (FunctionMockers::const_iterator it = mockers.begin();\n       it != mockers.end(); ++it) {\n    if (!(*it)->VerifyAndClearExpectationsLocked()) {\n      expectations_met = false;\n    }\n  }\n\n  // We don't clear the content of mockers, as they may still be\n  // needed by ClearDefaultActionsLocked().\n  return expectations_met;\n}\n\nbool Mock::IsNaggy(void* mock_obj)\n    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n  return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kWarn;\n}\nbool Mock::IsNice(void* mock_obj)\n    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n  return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kAllow;\n}\nbool Mock::IsStrict(void* mock_obj)\n    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n  return Mock::GetReactionOnUninterestingCalls(mock_obj) == internal::kFail;\n}\n\n// Registers a mock object and a mock method it owns.\nvoid Mock::Register(const void* mock_obj,\n                    internal::UntypedFunctionMockerBase* mocker)\n    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n  internal::MutexLock l(&internal::g_gmock_mutex);\n  g_mock_object_registry.states()[mock_obj].function_mockers.insert(mocker);\n}\n\n// Tells Google Mock where in the source code mock_obj is used in an\n// ON_CALL or EXPECT_CALL.  In case mock_obj is leaked, this\n// information helps the user identify which object it is.\nvoid Mock::RegisterUseByOnCallOrExpectCall(const void* mock_obj,\n                                           const char* file, int line)\n    GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex) {\n  internal::MutexLock l(&internal::g_gmock_mutex);\n  MockObjectState& state = g_mock_object_registry.states()[mock_obj];\n  if (state.first_used_file == nullptr) {\n    state.first_used_file = file;\n    state.first_used_line = line;\n    const TestInfo* const test_info =\n        UnitTest::GetInstance()->current_test_info();\n    if (test_info != nullptr) {\n      state.first_used_test_suite = test_info->test_suite_name();\n      state.first_used_test = test_info->name();\n    }\n  }\n}\n\n// Unregisters a mock method; removes the owning mock object from the\n// registry when the last mock method associated with it has been\n// unregistered.  This is called only in the destructor of\n// FunctionMockerBase.\nvoid Mock::UnregisterLocked(internal::UntypedFunctionMockerBase* mocker)\n    GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {\n  internal::g_gmock_mutex.AssertHeld();\n  for (MockObjectRegistry::StateMap::iterator it =\n           g_mock_object_registry.states().begin();\n       it != g_mock_object_registry.states().end(); ++it) {\n    FunctionMockers& mockers = it->second.function_mockers;\n    if (mockers.erase(mocker) > 0) {\n      // mocker was in mockers and has been just removed.\n      if (mockers.empty()) {\n        g_mock_object_registry.states().erase(it);\n      }\n      return;\n    }\n  }\n}\n\n// Clears all ON_CALL()s set on the given mock object.\nvoid Mock::ClearDefaultActionsLocked(void* mock_obj)\n    GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {\n  internal::g_gmock_mutex.AssertHeld();\n\n  if (g_mock_object_registry.states().count(mock_obj) == 0) {\n    // No ON_CALL() was set on the given mock object.\n    return;\n  }\n\n  // Clears the default actions for each mock method in the given mock\n  // object.\n  FunctionMockers& mockers =\n      g_mock_object_registry.states()[mock_obj].function_mockers;\n  for (FunctionMockers::const_iterator it = mockers.begin();\n       it != mockers.end(); ++it) {\n    (*it)->ClearDefaultActionsLocked();\n  }\n\n  // We don't clear the content of mockers, as they may still be\n  // needed by VerifyAndClearExpectationsLocked().\n}\n\nExpectation::Expectation() {}\n\nExpectation::Expectation(\n    const std::shared_ptr<internal::ExpectationBase>& an_expectation_base)\n    : expectation_base_(an_expectation_base) {}\n\nExpectation::~Expectation() {}\n\n// Adds an expectation to a sequence.\nvoid Sequence::AddExpectation(const Expectation& expectation) const {\n  if (*last_expectation_ != expectation) {\n    if (last_expectation_->expectation_base() != nullptr) {\n      expectation.expectation_base()->immediate_prerequisites_ +=\n          *last_expectation_;\n    }\n    *last_expectation_ = expectation;\n  }\n}\n\n// Creates the implicit sequence if there isn't one.\nInSequence::InSequence() {\n  if (internal::g_gmock_implicit_sequence.get() == nullptr) {\n    internal::g_gmock_implicit_sequence.set(new Sequence);\n    sequence_created_ = true;\n  } else {\n    sequence_created_ = false;\n  }\n}\n\n// Deletes the implicit sequence if it was created by the constructor\n// of this object.\nInSequence::~InSequence() {\n  if (sequence_created_) {\n    delete internal::g_gmock_implicit_sequence.get();\n    internal::g_gmock_implicit_sequence.set(nullptr);\n  }\n}\n\n}  // namespace testing\n\n#ifdef _MSC_VER\n#if _MSC_VER == 1900\n#pragma warning(pop)\n#endif\n#endif\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/src/gmock.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"gmock/gmock.h\"\n\n#include \"gmock/internal/gmock-port.h\"\n\nGMOCK_DEFINE_bool_(catch_leaked_mocks, true,\n                   \"true if and only if Google Mock should report leaked \"\n                   \"mock objects as failures.\");\n\nGMOCK_DEFINE_string_(verbose, testing::internal::kWarningVerbosity,\n                     \"Controls how verbose Google Mock's output is.\"\n                     \"  Valid values:\\n\"\n                     \"  info    - prints all messages.\\n\"\n                     \"  warning - prints warnings and errors.\\n\"\n                     \"  error   - prints errors only.\");\n\nGMOCK_DEFINE_int32_(default_mock_behavior, 1,\n                    \"Controls the default behavior of mocks.\"\n                    \"  Valid values:\\n\"\n                    \"  0 - by default, mocks act as NiceMocks.\\n\"\n                    \"  1 - by default, mocks act as NaggyMocks.\\n\"\n                    \"  2 - by default, mocks act as StrictMocks.\");\n\nnamespace testing {\nnamespace internal {\n\n// Parses a string as a command line flag.  The string should have the\n// format \"--gmock_flag=value\".  When def_optional is true, the\n// \"=value\" part can be omitted.\n//\n// Returns the value of the flag, or NULL if the parsing failed.\nstatic const char* ParseGoogleMockFlagValue(const char* str,\n                                            const char* flag_name,\n                                            bool def_optional) {\n  // str and flag must not be NULL.\n  if (str == nullptr || flag_name == nullptr) return nullptr;\n\n  // The flag must start with \"--gmock_\".\n  const std::string flag_name_str = std::string(\"--gmock_\") + flag_name;\n  const size_t flag_name_len = flag_name_str.length();\n  if (strncmp(str, flag_name_str.c_str(), flag_name_len) != 0) return nullptr;\n\n  // Skips the flag name.\n  const char* flag_end = str + flag_name_len;\n\n  // When def_optional is true, it's OK to not have a \"=value\" part.\n  if (def_optional && (flag_end[0] == '\\0')) {\n    return flag_end;\n  }\n\n  // If def_optional is true and there are more characters after the\n  // flag name, or if def_optional is false, there must be a '=' after\n  // the flag name.\n  if (flag_end[0] != '=') return nullptr;\n\n  // Returns the string after \"=\".\n  return flag_end + 1;\n}\n\n// Parses a string for a Google Mock bool flag, in the form of\n// \"--gmock_flag=value\".\n//\n// On success, stores the value of the flag in *value, and returns\n// true.  On failure, returns false without changing *value.\nstatic bool ParseGoogleMockFlag(const char* str, const char* flag_name,\n                                bool* value) {\n  // Gets the value of the flag as a string.\n  const char* const value_str = ParseGoogleMockFlagValue(str, flag_name, true);\n\n  // Aborts if the parsing failed.\n  if (value_str == nullptr) return false;\n\n  // Converts the string value to a bool.\n  *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');\n  return true;\n}\n\n// Parses a string for a Google Mock string flag, in the form of\n// \"--gmock_flag=value\".\n//\n// On success, stores the value of the flag in *value, and returns\n// true.  On failure, returns false without changing *value.\ntemplate <typename String>\nstatic bool ParseGoogleMockFlag(const char* str, const char* flag_name,\n                                String* value) {\n  // Gets the value of the flag as a string.\n  const char* const value_str = ParseGoogleMockFlagValue(str, flag_name, false);\n\n  // Aborts if the parsing failed.\n  if (value_str == nullptr) return false;\n\n  // Sets *value to the value of the flag.\n  *value = value_str;\n  return true;\n}\n\nstatic bool ParseGoogleMockFlag(const char* str, const char* flag_name,\n                                int32_t* value) {\n  // Gets the value of the flag as a string.\n  const char* const value_str = ParseGoogleMockFlagValue(str, flag_name, true);\n\n  // Aborts if the parsing failed.\n  if (value_str == nullptr) return false;\n\n  // Sets *value to the value of the flag.\n  return ParseInt32(Message() << \"The value of flag --\" << flag_name, value_str,\n                    value);\n}\n\n// The internal implementation of InitGoogleMock().\n//\n// The type parameter CharType can be instantiated to either char or\n// wchar_t.\ntemplate <typename CharType>\nvoid InitGoogleMockImpl(int* argc, CharType** argv) {\n  // Makes sure Google Test is initialized.  InitGoogleTest() is\n  // idempotent, so it's fine if the user has already called it.\n  InitGoogleTest(argc, argv);\n  if (*argc <= 0) return;\n\n  for (int i = 1; i != *argc; i++) {\n    const std::string arg_string = StreamableToString(argv[i]);\n    const char* const arg = arg_string.c_str();\n\n    // Do we see a Google Mock flag?\n    bool found_gmock_flag = false;\n\n#define GMOCK_INTERNAL_PARSE_FLAG(flag_name)            \\\n  if (!found_gmock_flag) {                              \\\n    auto value = GMOCK_FLAG_GET(flag_name);             \\\n    if (ParseGoogleMockFlag(arg, #flag_name, &value)) { \\\n      GMOCK_FLAG_SET(flag_name, value);                 \\\n      found_gmock_flag = true;                          \\\n    }                                                   \\\n  }\n\n    GMOCK_INTERNAL_PARSE_FLAG(catch_leaked_mocks)\n    GMOCK_INTERNAL_PARSE_FLAG(verbose)\n    GMOCK_INTERNAL_PARSE_FLAG(default_mock_behavior)\n\n    if (found_gmock_flag) {\n      // Yes.  Shift the remainder of the argv list left by one.  Note\n      // that argv has (*argc + 1) elements, the last one always being\n      // NULL.  The following loop moves the trailing NULL element as\n      // well.\n      for (int j = i; j != *argc; j++) {\n        argv[j] = argv[j + 1];\n      }\n\n      // Decrements the argument count.\n      (*argc)--;\n\n      // We also need to decrement the iterator as we just removed\n      // an element.\n      i--;\n    }\n  }\n}\n\n}  // namespace internal\n\n// Initializes Google Mock.  This must be called before running the\n// tests.  In particular, it parses a command line for the flags that\n// Google Mock recognizes.  Whenever a Google Mock flag is seen, it is\n// removed from argv, and *argc is decremented.\n//\n// No value is returned.  Instead, the Google Mock flag variables are\n// updated.\n//\n// Since Google Test is needed for Google Mock to work, this function\n// also initializes Google Test and parses its flags, if that hasn't\n// been done.\nGTEST_API_ void InitGoogleMock(int* argc, char** argv) {\n  internal::InitGoogleMockImpl(argc, argv);\n}\n\n// This overloaded version can be used in Windows programs compiled in\n// UNICODE mode.\nGTEST_API_ void InitGoogleMock(int* argc, wchar_t** argv) {\n  internal::InitGoogleMockImpl(argc, argv);\n}\n\n// This overloaded version can be used on Arduino/embedded platforms where\n// there is no argc/argv.\nGTEST_API_ void InitGoogleMock() {\n  // Since Arduino doesn't have a command line, fake out the argc/argv arguments\n  int argc = 1;\n  const auto arg0 = \"dummy\";\n  char* argv0 = const_cast<char*>(arg0);\n  char** argv = &argv0;\n\n  internal::InitGoogleMockImpl(&argc, argv);\n}\n\n}  // namespace testing\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/src/gmock_main.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include <iostream>\n\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n\n#if GTEST_OS_ESP8266 || GTEST_OS_ESP32\n#if GTEST_OS_ESP8266\nextern \"C\" {\n#endif\nvoid setup() {\n  // Since Google Mock depends on Google Test, InitGoogleMock() is\n  // also responsible for initializing Google Test.  Therefore there's\n  // no need for calling testing::InitGoogleTest() separately.\n  testing::InitGoogleMock();\n}\nvoid loop() { RUN_ALL_TESTS(); }\n#if GTEST_OS_ESP8266\n}\n#endif\n\n#else\n\n// MS C++ compiler/linker has a bug on Windows (not on Windows CE), which\n// causes a link error when _tmain is defined in a static library and UNICODE\n// is enabled. For this reason instead of _tmain, main function is used on\n// Windows. See the following link to track the current status of this bug:\n// https://web.archive.org/web/20170912203238/connect.microsoft.com/VisualStudio/feedback/details/394464/wmain-link-error-in-the-static-library\n// // NOLINT\n#if GTEST_OS_WINDOWS_MOBILE\n#include <tchar.h>  // NOLINT\n\nGTEST_API_ int _tmain(int argc, TCHAR** argv) {\n#else\nGTEST_API_ int main(int argc, char** argv) {\n#endif  // GTEST_OS_WINDOWS_MOBILE\n  std::cout << \"Running main() from gmock_main.cc\\n\";\n  // Since Google Mock depends on Google Test, InitGoogleMock() is\n  // also responsible for initializing Google Test.  Therefore there's\n  // no need for calling testing::InitGoogleTest() separately.\n  testing::InitGoogleMock(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n#endif\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/BUILD.bazel",
    "content": "# Copyright 2017 Google Inc.\n# All Rights Reserved.\n#\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n#   Bazel Build for Google C++ Testing Framework(Google Test)-googlemock\n\nload(\"@rules_python//python:defs.bzl\", \"py_library\", \"py_test\")\n\nlicenses([\"notice\"])\n\n# Tests for GMock itself\ncc_test(\n    name = \"gmock_all_test\",\n    size = \"small\",\n    srcs = glob(include = [\"gmock-*.cc\"]) + [\"gmock-matchers_test.h\"],\n    linkopts = select({\n        \"//:qnx\": [],\n        \"//:windows\": [],\n        \"//conditions:default\": [\"-pthread\"],\n    }),\n    deps = [\"//:gtest\"],\n)\n\n# Python tests\npy_library(\n    name = \"gmock_test_utils\",\n    testonly = 1,\n    srcs = [\"gmock_test_utils.py\"],\n    deps = [\n        \"//googletest/test:gtest_test_utils\",\n    ],\n)\n\ncc_binary(\n    name = \"gmock_leak_test_\",\n    testonly = 1,\n    srcs = [\"gmock_leak_test_.cc\"],\n    deps = [\"//:gtest_main\"],\n)\n\npy_test(\n    name = \"gmock_leak_test\",\n    size = \"medium\",\n    srcs = [\"gmock_leak_test.py\"],\n    data = [\n        \":gmock_leak_test_\",\n        \":gmock_test_utils\",\n    ],\n    tags = [\n        \"no_test_msvc2015\",\n        \"no_test_msvc2017\",\n    ],\n)\n\ncc_test(\n    name = \"gmock_link_test\",\n    size = \"small\",\n    srcs = [\n        \"gmock_link2_test.cc\",\n        \"gmock_link_test.cc\",\n        \"gmock_link_test.h\",\n    ],\n    deps = [\"//:gtest_main\"],\n)\n\ncc_binary(\n    name = \"gmock_output_test_\",\n    srcs = [\"gmock_output_test_.cc\"],\n    deps = [\"//:gtest\"],\n)\n\npy_test(\n    name = \"gmock_output_test\",\n    size = \"medium\",\n    srcs = [\"gmock_output_test.py\"],\n    data = [\n        \":gmock_output_test_\",\n        \":gmock_output_test_golden.txt\",\n    ],\n    tags = [\n        \"no_test_msvc2015\",\n        \"no_test_msvc2017\",\n    ],\n    deps = [\":gmock_test_utils\"],\n)\n\ncc_test(\n    name = \"gmock_test\",\n    size = \"small\",\n    srcs = [\"gmock_test.cc\"],\n    deps = [\"//:gtest_main\"],\n)\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock-actions_test.cc",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file tests the built-in actions.\n\n// Silence C4100 (unreferenced formal parameter) and C4503 (decorated name\n// length exceeded) for MSVC.\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 4100)\n#pragma warning(disable : 4503)\n#if _MSC_VER == 1900\n// and silence C4800 (C4800: 'int *const ': forcing value\n// to bool 'true' or 'false') for MSVC 15\n#pragma warning(disable : 4800)\n#endif\n#endif\n\n#include \"gmock/gmock-actions.h\"\n\n#include <algorithm>\n#include <functional>\n#include <iterator>\n#include <memory>\n#include <string>\n#include <type_traits>\n#include <vector>\n\n#include \"gmock/gmock.h\"\n#include \"gmock/internal/gmock-port.h\"\n#include \"gtest/gtest-spi.h\"\n#include \"gtest/gtest.h\"\n\nnamespace testing {\nnamespace {\n\nusing ::testing::internal::BuiltInDefaultValue;\n\nTEST(TypeTraits, Negation) {\n  // Direct use with std types.\n  static_assert(std::is_base_of<std::false_type,\n                                internal::negation<std::true_type>>::value,\n                \"\");\n\n  static_assert(std::is_base_of<std::true_type,\n                                internal::negation<std::false_type>>::value,\n                \"\");\n\n  // With other types that fit the requirement of a value member that is\n  // convertible to bool.\n  static_assert(std::is_base_of<\n                    std::true_type,\n                    internal::negation<std::integral_constant<int, 0>>>::value,\n                \"\");\n\n  static_assert(std::is_base_of<\n                    std::false_type,\n                    internal::negation<std::integral_constant<int, 1>>>::value,\n                \"\");\n\n  static_assert(std::is_base_of<\n                    std::false_type,\n                    internal::negation<std::integral_constant<int, -1>>>::value,\n                \"\");\n}\n\n// Weird false/true types that aren't actually bool constants (but should still\n// be legal according to [meta.logical] because `bool(T::value)` is valid), are\n// distinct from std::false_type and std::true_type, and are distinct from other\n// instantiations of the same template.\n//\n// These let us check finicky details mandated by the standard like\n// \"std::conjunction should evaluate to a type that inherits from the first\n// false-y input\".\ntemplate <int>\nstruct MyFalse : std::integral_constant<int, 0> {};\n\ntemplate <int>\nstruct MyTrue : std::integral_constant<int, -1> {};\n\nTEST(TypeTraits, Conjunction) {\n  // Base case: always true.\n  static_assert(std::is_base_of<std::true_type, internal::conjunction<>>::value,\n                \"\");\n\n  // One predicate: inherits from that predicate, regardless of value.\n  static_assert(\n      std::is_base_of<MyFalse<0>, internal::conjunction<MyFalse<0>>>::value,\n      \"\");\n\n  static_assert(\n      std::is_base_of<MyTrue<0>, internal::conjunction<MyTrue<0>>>::value, \"\");\n\n  // Multiple predicates, with at least one false: inherits from that one.\n  static_assert(\n      std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>,\n                                                        MyTrue<2>>>::value,\n      \"\");\n\n  static_assert(\n      std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>,\n                                                        MyFalse<2>>>::value,\n      \"\");\n\n  // Short circuiting: in the case above, additional predicates need not even\n  // define a value member.\n  struct Empty {};\n  static_assert(\n      std::is_base_of<MyFalse<1>, internal::conjunction<MyTrue<0>, MyFalse<1>,\n                                                        Empty>>::value,\n      \"\");\n\n  // All predicates true: inherits from the last.\n  static_assert(\n      std::is_base_of<MyTrue<2>, internal::conjunction<MyTrue<0>, MyTrue<1>,\n                                                       MyTrue<2>>>::value,\n      \"\");\n}\n\nTEST(TypeTraits, Disjunction) {\n  // Base case: always false.\n  static_assert(\n      std::is_base_of<std::false_type, internal::disjunction<>>::value, \"\");\n\n  // One predicate: inherits from that predicate, regardless of value.\n  static_assert(\n      std::is_base_of<MyFalse<0>, internal::disjunction<MyFalse<0>>>::value,\n      \"\");\n\n  static_assert(\n      std::is_base_of<MyTrue<0>, internal::disjunction<MyTrue<0>>>::value, \"\");\n\n  // Multiple predicates, with at least one true: inherits from that one.\n  static_assert(\n      std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>,\n                                                       MyFalse<2>>>::value,\n      \"\");\n\n  static_assert(\n      std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>,\n                                                       MyTrue<2>>>::value,\n      \"\");\n\n  // Short circuiting: in the case above, additional predicates need not even\n  // define a value member.\n  struct Empty {};\n  static_assert(\n      std::is_base_of<MyTrue<1>, internal::disjunction<MyFalse<0>, MyTrue<1>,\n                                                       Empty>>::value,\n      \"\");\n\n  // All predicates false: inherits from the last.\n  static_assert(\n      std::is_base_of<MyFalse<2>, internal::disjunction<MyFalse<0>, MyFalse<1>,\n                                                        MyFalse<2>>>::value,\n      \"\");\n}\n\nTEST(TypeTraits, IsInvocableRV) {\n  struct C {\n    int operator()() const { return 0; }\n    void operator()(int) & {}\n    std::string operator()(int) && { return \"\"; };\n  };\n\n  // The first overload is callable for const and non-const rvalues and lvalues.\n  // It can be used to obtain an int, cv void, or anything int is convertible\n  // to.\n  static_assert(internal::is_callable_r<int, C>::value, \"\");\n  static_assert(internal::is_callable_r<int, C&>::value, \"\");\n  static_assert(internal::is_callable_r<int, const C>::value, \"\");\n  static_assert(internal::is_callable_r<int, const C&>::value, \"\");\n\n  static_assert(internal::is_callable_r<void, C>::value, \"\");\n  static_assert(internal::is_callable_r<const volatile void, C>::value, \"\");\n  static_assert(internal::is_callable_r<char, C>::value, \"\");\n\n  // It's possible to provide an int. If it's given to an lvalue, the result is\n  // void. Otherwise it is std::string (which is also treated as allowed for a\n  // void result type).\n  static_assert(internal::is_callable_r<void, C&, int>::value, \"\");\n  static_assert(!internal::is_callable_r<int, C&, int>::value, \"\");\n  static_assert(!internal::is_callable_r<std::string, C&, int>::value, \"\");\n  static_assert(!internal::is_callable_r<void, const C&, int>::value, \"\");\n\n  static_assert(internal::is_callable_r<std::string, C, int>::value, \"\");\n  static_assert(internal::is_callable_r<void, C, int>::value, \"\");\n  static_assert(!internal::is_callable_r<int, C, int>::value, \"\");\n\n  // It's not possible to provide other arguments.\n  static_assert(!internal::is_callable_r<void, C, std::string>::value, \"\");\n  static_assert(!internal::is_callable_r<void, C, int, int>::value, \"\");\n\n  // In C++17 and above, where it's guaranteed that functions can return\n  // non-moveable objects, everything should work fine for non-moveable rsult\n  // types too.\n#if defined(__cplusplus) && __cplusplus >= 201703L\n  {\n    struct NonMoveable {\n      NonMoveable() = default;\n      NonMoveable(NonMoveable&&) = delete;\n    };\n\n    static_assert(!std::is_move_constructible_v<NonMoveable>);\n\n    struct Callable {\n      NonMoveable operator()() { return NonMoveable(); }\n    };\n\n    static_assert(internal::is_callable_r<NonMoveable, Callable>::value);\n    static_assert(internal::is_callable_r<void, Callable>::value);\n    static_assert(\n        internal::is_callable_r<const volatile void, Callable>::value);\n\n    static_assert(!internal::is_callable_r<int, Callable>::value);\n    static_assert(!internal::is_callable_r<NonMoveable, Callable, int>::value);\n  }\n#endif  // C++17 and above\n\n  // Nothing should choke when we try to call other arguments besides directly\n  // callable objects, but they should not show up as callable.\n  static_assert(!internal::is_callable_r<void, int>::value, \"\");\n  static_assert(!internal::is_callable_r<void, void (C::*)()>::value, \"\");\n  static_assert(!internal::is_callable_r<void, void (C::*)(), C*>::value, \"\");\n}\n\n// Tests that BuiltInDefaultValue<T*>::Get() returns NULL.\nTEST(BuiltInDefaultValueTest, IsNullForPointerTypes) {\n  EXPECT_TRUE(BuiltInDefaultValue<int*>::Get() == nullptr);\n  EXPECT_TRUE(BuiltInDefaultValue<const char*>::Get() == nullptr);\n  EXPECT_TRUE(BuiltInDefaultValue<void*>::Get() == nullptr);\n}\n\n// Tests that BuiltInDefaultValue<T*>::Exists() return true.\nTEST(BuiltInDefaultValueTest, ExistsForPointerTypes) {\n  EXPECT_TRUE(BuiltInDefaultValue<int*>::Exists());\n  EXPECT_TRUE(BuiltInDefaultValue<const char*>::Exists());\n  EXPECT_TRUE(BuiltInDefaultValue<void*>::Exists());\n}\n\n// Tests that BuiltInDefaultValue<T>::Get() returns 0 when T is a\n// built-in numeric type.\nTEST(BuiltInDefaultValueTest, IsZeroForNumericTypes) {\n  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned char>::Get());\n  EXPECT_EQ(0, BuiltInDefaultValue<signed char>::Get());\n  EXPECT_EQ(0, BuiltInDefaultValue<char>::Get());\n#if GMOCK_WCHAR_T_IS_NATIVE_\n#if !defined(__WCHAR_UNSIGNED__)\n  EXPECT_EQ(0, BuiltInDefaultValue<wchar_t>::Get());\n#else\n  EXPECT_EQ(0U, BuiltInDefaultValue<wchar_t>::Get());\n#endif\n#endif\n  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned short>::Get());  // NOLINT\n  EXPECT_EQ(0, BuiltInDefaultValue<signed short>::Get());     // NOLINT\n  EXPECT_EQ(0, BuiltInDefaultValue<short>::Get());            // NOLINT\n  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned int>::Get());\n  EXPECT_EQ(0, BuiltInDefaultValue<signed int>::Get());\n  EXPECT_EQ(0, BuiltInDefaultValue<int>::Get());\n  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long>::Get());       // NOLINT\n  EXPECT_EQ(0, BuiltInDefaultValue<signed long>::Get());          // NOLINT\n  EXPECT_EQ(0, BuiltInDefaultValue<long>::Get());                 // NOLINT\n  EXPECT_EQ(0U, BuiltInDefaultValue<unsigned long long>::Get());  // NOLINT\n  EXPECT_EQ(0, BuiltInDefaultValue<signed long long>::Get());     // NOLINT\n  EXPECT_EQ(0, BuiltInDefaultValue<long long>::Get());            // NOLINT\n  EXPECT_EQ(0, BuiltInDefaultValue<float>::Get());\n  EXPECT_EQ(0, BuiltInDefaultValue<double>::Get());\n}\n\n// Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a\n// built-in numeric type.\nTEST(BuiltInDefaultValueTest, ExistsForNumericTypes) {\n  EXPECT_TRUE(BuiltInDefaultValue<unsigned char>::Exists());\n  EXPECT_TRUE(BuiltInDefaultValue<signed char>::Exists());\n  EXPECT_TRUE(BuiltInDefaultValue<char>::Exists());\n#if GMOCK_WCHAR_T_IS_NATIVE_\n  EXPECT_TRUE(BuiltInDefaultValue<wchar_t>::Exists());\n#endif\n  EXPECT_TRUE(BuiltInDefaultValue<unsigned short>::Exists());  // NOLINT\n  EXPECT_TRUE(BuiltInDefaultValue<signed short>::Exists());    // NOLINT\n  EXPECT_TRUE(BuiltInDefaultValue<short>::Exists());           // NOLINT\n  EXPECT_TRUE(BuiltInDefaultValue<unsigned int>::Exists());\n  EXPECT_TRUE(BuiltInDefaultValue<signed int>::Exists());\n  EXPECT_TRUE(BuiltInDefaultValue<int>::Exists());\n  EXPECT_TRUE(BuiltInDefaultValue<unsigned long>::Exists());       // NOLINT\n  EXPECT_TRUE(BuiltInDefaultValue<signed long>::Exists());         // NOLINT\n  EXPECT_TRUE(BuiltInDefaultValue<long>::Exists());                // NOLINT\n  EXPECT_TRUE(BuiltInDefaultValue<unsigned long long>::Exists());  // NOLINT\n  EXPECT_TRUE(BuiltInDefaultValue<signed long long>::Exists());    // NOLINT\n  EXPECT_TRUE(BuiltInDefaultValue<long long>::Exists());           // NOLINT\n  EXPECT_TRUE(BuiltInDefaultValue<float>::Exists());\n  EXPECT_TRUE(BuiltInDefaultValue<double>::Exists());\n}\n\n// Tests that BuiltInDefaultValue<bool>::Get() returns false.\nTEST(BuiltInDefaultValueTest, IsFalseForBool) {\n  EXPECT_FALSE(BuiltInDefaultValue<bool>::Get());\n}\n\n// Tests that BuiltInDefaultValue<bool>::Exists() returns true.\nTEST(BuiltInDefaultValueTest, BoolExists) {\n  EXPECT_TRUE(BuiltInDefaultValue<bool>::Exists());\n}\n\n// Tests that BuiltInDefaultValue<T>::Get() returns \"\" when T is a\n// string type.\nTEST(BuiltInDefaultValueTest, IsEmptyStringForString) {\n  EXPECT_EQ(\"\", BuiltInDefaultValue<::std::string>::Get());\n}\n\n// Tests that BuiltInDefaultValue<T>::Exists() returns true when T is a\n// string type.\nTEST(BuiltInDefaultValueTest, ExistsForString) {\n  EXPECT_TRUE(BuiltInDefaultValue<::std::string>::Exists());\n}\n\n// Tests that BuiltInDefaultValue<const T>::Get() returns the same\n// value as BuiltInDefaultValue<T>::Get() does.\nTEST(BuiltInDefaultValueTest, WorksForConstTypes) {\n  EXPECT_EQ(\"\", BuiltInDefaultValue<const std::string>::Get());\n  EXPECT_EQ(0, BuiltInDefaultValue<const int>::Get());\n  EXPECT_TRUE(BuiltInDefaultValue<char* const>::Get() == nullptr);\n  EXPECT_FALSE(BuiltInDefaultValue<const bool>::Get());\n}\n\n// A type that's default constructible.\nclass MyDefaultConstructible {\n public:\n  MyDefaultConstructible() : value_(42) {}\n\n  int value() const { return value_; }\n\n private:\n  int value_;\n};\n\n// A type that's not default constructible.\nclass MyNonDefaultConstructible {\n public:\n  // Does not have a default ctor.\n  explicit MyNonDefaultConstructible(int a_value) : value_(a_value) {}\n\n  int value() const { return value_; }\n\n private:\n  int value_;\n};\n\nTEST(BuiltInDefaultValueTest, ExistsForDefaultConstructibleType) {\n  EXPECT_TRUE(BuiltInDefaultValue<MyDefaultConstructible>::Exists());\n}\n\nTEST(BuiltInDefaultValueTest, IsDefaultConstructedForDefaultConstructibleType) {\n  EXPECT_EQ(42, BuiltInDefaultValue<MyDefaultConstructible>::Get().value());\n}\n\nTEST(BuiltInDefaultValueTest, DoesNotExistForNonDefaultConstructibleType) {\n  EXPECT_FALSE(BuiltInDefaultValue<MyNonDefaultConstructible>::Exists());\n}\n\n// Tests that BuiltInDefaultValue<T&>::Get() aborts the program.\nTEST(BuiltInDefaultValueDeathTest, IsUndefinedForReferences) {\n  EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<int&>::Get(); }, \"\");\n  EXPECT_DEATH_IF_SUPPORTED({ BuiltInDefaultValue<const char&>::Get(); }, \"\");\n}\n\nTEST(BuiltInDefaultValueDeathTest, IsUndefinedForNonDefaultConstructibleType) {\n  EXPECT_DEATH_IF_SUPPORTED(\n      { BuiltInDefaultValue<MyNonDefaultConstructible>::Get(); }, \"\");\n}\n\n// Tests that DefaultValue<T>::IsSet() is false initially.\nTEST(DefaultValueTest, IsInitiallyUnset) {\n  EXPECT_FALSE(DefaultValue<int>::IsSet());\n  EXPECT_FALSE(DefaultValue<MyDefaultConstructible>::IsSet());\n  EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());\n}\n\n// Tests that DefaultValue<T> can be set and then unset.\nTEST(DefaultValueTest, CanBeSetAndUnset) {\n  EXPECT_TRUE(DefaultValue<int>::Exists());\n  EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());\n\n  DefaultValue<int>::Set(1);\n  DefaultValue<const MyNonDefaultConstructible>::Set(\n      MyNonDefaultConstructible(42));\n\n  EXPECT_EQ(1, DefaultValue<int>::Get());\n  EXPECT_EQ(42, DefaultValue<const MyNonDefaultConstructible>::Get().value());\n\n  EXPECT_TRUE(DefaultValue<int>::Exists());\n  EXPECT_TRUE(DefaultValue<const MyNonDefaultConstructible>::Exists());\n\n  DefaultValue<int>::Clear();\n  DefaultValue<const MyNonDefaultConstructible>::Clear();\n\n  EXPECT_FALSE(DefaultValue<int>::IsSet());\n  EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::IsSet());\n\n  EXPECT_TRUE(DefaultValue<int>::Exists());\n  EXPECT_FALSE(DefaultValue<const MyNonDefaultConstructible>::Exists());\n}\n\n// Tests that DefaultValue<T>::Get() returns the\n// BuiltInDefaultValue<T>::Get() when DefaultValue<T>::IsSet() is\n// false.\nTEST(DefaultValueDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {\n  EXPECT_FALSE(DefaultValue<int>::IsSet());\n  EXPECT_TRUE(DefaultValue<int>::Exists());\n  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::IsSet());\n  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible>::Exists());\n\n  EXPECT_EQ(0, DefaultValue<int>::Get());\n\n  EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); },\n                            \"\");\n}\n\nTEST(DefaultValueTest, GetWorksForMoveOnlyIfSet) {\n  EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());\n  EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Get() == nullptr);\n  DefaultValue<std::unique_ptr<int>>::SetFactory(\n      [] { return std::unique_ptr<int>(new int(42)); });\n  EXPECT_TRUE(DefaultValue<std::unique_ptr<int>>::Exists());\n  std::unique_ptr<int> i = DefaultValue<std::unique_ptr<int>>::Get();\n  EXPECT_EQ(42, *i);\n}\n\n// Tests that DefaultValue<void>::Get() returns void.\nTEST(DefaultValueTest, GetWorksForVoid) { return DefaultValue<void>::Get(); }\n\n// Tests using DefaultValue with a reference type.\n\n// Tests that DefaultValue<T&>::IsSet() is false initially.\nTEST(DefaultValueOfReferenceTest, IsInitiallyUnset) {\n  EXPECT_FALSE(DefaultValue<int&>::IsSet());\n  EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::IsSet());\n  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());\n}\n\n// Tests that DefaultValue<T&>::Exists is false initiallly.\nTEST(DefaultValueOfReferenceTest, IsInitiallyNotExisting) {\n  EXPECT_FALSE(DefaultValue<int&>::Exists());\n  EXPECT_FALSE(DefaultValue<MyDefaultConstructible&>::Exists());\n  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());\n}\n\n// Tests that DefaultValue<T&> can be set and then unset.\nTEST(DefaultValueOfReferenceTest, CanBeSetAndUnset) {\n  int n = 1;\n  DefaultValue<const int&>::Set(n);\n  MyNonDefaultConstructible x(42);\n  DefaultValue<MyNonDefaultConstructible&>::Set(x);\n\n  EXPECT_TRUE(DefaultValue<const int&>::Exists());\n  EXPECT_TRUE(DefaultValue<MyNonDefaultConstructible&>::Exists());\n\n  EXPECT_EQ(&n, &(DefaultValue<const int&>::Get()));\n  EXPECT_EQ(&x, &(DefaultValue<MyNonDefaultConstructible&>::Get()));\n\n  DefaultValue<const int&>::Clear();\n  DefaultValue<MyNonDefaultConstructible&>::Clear();\n\n  EXPECT_FALSE(DefaultValue<const int&>::Exists());\n  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::Exists());\n\n  EXPECT_FALSE(DefaultValue<const int&>::IsSet());\n  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());\n}\n\n// Tests that DefaultValue<T&>::Get() returns the\n// BuiltInDefaultValue<T&>::Get() when DefaultValue<T&>::IsSet() is\n// false.\nTEST(DefaultValueOfReferenceDeathTest, GetReturnsBuiltInDefaultValueWhenUnset) {\n  EXPECT_FALSE(DefaultValue<int&>::IsSet());\n  EXPECT_FALSE(DefaultValue<MyNonDefaultConstructible&>::IsSet());\n\n  EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<int&>::Get(); }, \"\");\n  EXPECT_DEATH_IF_SUPPORTED({ DefaultValue<MyNonDefaultConstructible>::Get(); },\n                            \"\");\n}\n\n// Tests that ActionInterface can be implemented by defining the\n// Perform method.\n\ntypedef int MyGlobalFunction(bool, int);\n\nclass MyActionImpl : public ActionInterface<MyGlobalFunction> {\n public:\n  int Perform(const std::tuple<bool, int>& args) override {\n    return std::get<0>(args) ? std::get<1>(args) : 0;\n  }\n};\n\nTEST(ActionInterfaceTest, CanBeImplementedByDefiningPerform) {\n  MyActionImpl my_action_impl;\n  (void)my_action_impl;\n}\n\nTEST(ActionInterfaceTest, MakeAction) {\n  Action<MyGlobalFunction> action = MakeAction(new MyActionImpl);\n\n  // When exercising the Perform() method of Action<F>, we must pass\n  // it a tuple whose size and type are compatible with F's argument\n  // types.  For example, if F is int(), then Perform() takes a\n  // 0-tuple; if F is void(bool, int), then Perform() takes a\n  // std::tuple<bool, int>, and so on.\n  EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5)));\n}\n\n// Tests that Action<F> can be constructed from a pointer to\n// ActionInterface<F>.\nTEST(ActionTest, CanBeConstructedFromActionInterface) {\n  Action<MyGlobalFunction> action(new MyActionImpl);\n}\n\n// Tests that Action<F> delegates actual work to ActionInterface<F>.\nTEST(ActionTest, DelegatesWorkToActionInterface) {\n  const Action<MyGlobalFunction> action(new MyActionImpl);\n\n  EXPECT_EQ(5, action.Perform(std::make_tuple(true, 5)));\n  EXPECT_EQ(0, action.Perform(std::make_tuple(false, 1)));\n}\n\n// Tests that Action<F> can be copied.\nTEST(ActionTest, IsCopyable) {\n  Action<MyGlobalFunction> a1(new MyActionImpl);\n  Action<MyGlobalFunction> a2(a1);  // Tests the copy constructor.\n\n  // a1 should continue to work after being copied from.\n  EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));\n  EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1)));\n\n  // a2 should work like the action it was copied from.\n  EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5)));\n  EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1)));\n\n  a2 = a1;  // Tests the assignment operator.\n\n  // a1 should continue to work after being copied from.\n  EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));\n  EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 1)));\n\n  // a2 should work like the action it was copied from.\n  EXPECT_EQ(5, a2.Perform(std::make_tuple(true, 5)));\n  EXPECT_EQ(0, a2.Perform(std::make_tuple(false, 1)));\n}\n\n// Tests that an Action<From> object can be converted to a\n// compatible Action<To> object.\n\nclass IsNotZero : public ActionInterface<bool(int)> {  // NOLINT\n public:\n  bool Perform(const std::tuple<int>& arg) override {\n    return std::get<0>(arg) != 0;\n  }\n};\n\nTEST(ActionTest, CanBeConvertedToOtherActionType) {\n  const Action<bool(int)> a1(new IsNotZero);           // NOLINT\n  const Action<int(char)> a2 = Action<int(char)>(a1);  // NOLINT\n  EXPECT_EQ(1, a2.Perform(std::make_tuple('a')));\n  EXPECT_EQ(0, a2.Perform(std::make_tuple('\\0')));\n}\n\n// The following two classes are for testing MakePolymorphicAction().\n\n// Implements a polymorphic action that returns the second of the\n// arguments it receives.\nclass ReturnSecondArgumentAction {\n public:\n  // We want to verify that MakePolymorphicAction() can work with a\n  // polymorphic action whose Perform() method template is either\n  // const or not.  This lets us verify the non-const case.\n  template <typename Result, typename ArgumentTuple>\n  Result Perform(const ArgumentTuple& args) {\n    return std::get<1>(args);\n  }\n};\n\n// Implements a polymorphic action that can be used in a nullary\n// function to return 0.\nclass ReturnZeroFromNullaryFunctionAction {\n public:\n  // For testing that MakePolymorphicAction() works when the\n  // implementation class' Perform() method template takes only one\n  // template parameter.\n  //\n  // We want to verify that MakePolymorphicAction() can work with a\n  // polymorphic action whose Perform() method template is either\n  // const or not.  This lets us verify the const case.\n  template <typename Result>\n  Result Perform(const std::tuple<>&) const {\n    return 0;\n  }\n};\n\n// These functions verify that MakePolymorphicAction() returns a\n// PolymorphicAction<T> where T is the argument's type.\n\nPolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() {\n  return MakePolymorphicAction(ReturnSecondArgumentAction());\n}\n\nPolymorphicAction<ReturnZeroFromNullaryFunctionAction>\nReturnZeroFromNullaryFunction() {\n  return MakePolymorphicAction(ReturnZeroFromNullaryFunctionAction());\n}\n\n// Tests that MakePolymorphicAction() turns a polymorphic action\n// implementation class into a polymorphic action.\nTEST(MakePolymorphicActionTest, ConstructsActionFromImpl) {\n  Action<int(bool, int, double)> a1 = ReturnSecondArgument();  // NOLINT\n  EXPECT_EQ(5, a1.Perform(std::make_tuple(false, 5, 2.0)));\n}\n\n// Tests that MakePolymorphicAction() works when the implementation\n// class' Perform() method template has only one template parameter.\nTEST(MakePolymorphicActionTest, WorksWhenPerformHasOneTemplateParameter) {\n  Action<int()> a1 = ReturnZeroFromNullaryFunction();\n  EXPECT_EQ(0, a1.Perform(std::make_tuple()));\n\n  Action<void*()> a2 = ReturnZeroFromNullaryFunction();\n  EXPECT_TRUE(a2.Perform(std::make_tuple()) == nullptr);\n}\n\n// Tests that Return() works as an action for void-returning\n// functions.\nTEST(ReturnTest, WorksForVoid) {\n  const Action<void(int)> ret = Return();  // NOLINT\n  return ret.Perform(std::make_tuple(1));\n}\n\n// Tests that Return(v) returns v.\nTEST(ReturnTest, ReturnsGivenValue) {\n  Action<int()> ret = Return(1);  // NOLINT\n  EXPECT_EQ(1, ret.Perform(std::make_tuple()));\n\n  ret = Return(-5);\n  EXPECT_EQ(-5, ret.Perform(std::make_tuple()));\n}\n\n// Tests that Return(\"string literal\") works.\nTEST(ReturnTest, AcceptsStringLiteral) {\n  Action<const char*()> a1 = Return(\"Hello\");\n  EXPECT_STREQ(\"Hello\", a1.Perform(std::make_tuple()));\n\n  Action<std::string()> a2 = Return(\"world\");\n  EXPECT_EQ(\"world\", a2.Perform(std::make_tuple()));\n}\n\n// Return(x) should work fine when the mock function's return type is a\n// reference-like wrapper for decltype(x), as when x is a std::string and the\n// mock function returns std::string_view.\nTEST(ReturnTest, SupportsReferenceLikeReturnType) {\n  // A reference wrapper for std::vector<int>, implicitly convertible from it.\n  struct Result {\n    const std::vector<int>* v;\n    Result(const std::vector<int>& v) : v(&v) {}  // NOLINT\n  };\n\n  // Set up an action for a mock function that returns the reference wrapper\n  // type, initializing it with an actual vector.\n  //\n  // The returned wrapper should be initialized with a copy of that vector\n  // that's embedded within the action itself (which should stay alive as long\n  // as the mock object is alive), rather than e.g. a reference to the temporary\n  // we feed to Return. This should work fine both for WillOnce and\n  // WillRepeatedly.\n  MockFunction<Result()> mock;\n  EXPECT_CALL(mock, Call)\n      .WillOnce(Return(std::vector<int>{17, 19, 23}))\n      .WillRepeatedly(Return(std::vector<int>{29, 31, 37}));\n\n  EXPECT_THAT(mock.AsStdFunction()(),\n              Field(&Result::v, Pointee(ElementsAre(17, 19, 23))));\n\n  EXPECT_THAT(mock.AsStdFunction()(),\n              Field(&Result::v, Pointee(ElementsAre(29, 31, 37))));\n}\n\nTEST(ReturnTest, PrefersConversionOperator) {\n  // Define types In and Out such that:\n  //\n  //  *  In is implicitly convertible to Out.\n  //  *  Out also has an explicit constructor from In.\n  //\n  struct In;\n  struct Out {\n    int x;\n\n    explicit Out(const int x) : x(x) {}\n    explicit Out(const In&) : x(0) {}\n  };\n\n  struct In {\n    operator Out() const { return Out{19}; }  // NOLINT\n  };\n\n  // Assumption check: the C++ language rules are such that a function that\n  // returns Out which uses In a return statement will use the implicit\n  // conversion path rather than the explicit constructor.\n  EXPECT_THAT([]() -> Out { return In(); }(), Field(&Out::x, 19));\n\n  // Return should work the same way: if the mock function's return type is Out\n  // and we feed Return an In value, then the Out should be created through the\n  // implicit conversion path rather than the explicit constructor.\n  MockFunction<Out()> mock;\n  EXPECT_CALL(mock, Call).WillOnce(Return(In()));\n  EXPECT_THAT(mock.AsStdFunction()(), Field(&Out::x, 19));\n}\n\n// It should be possible to use Return(R) with a mock function result type U\n// that is convertible from const R& but *not* R (such as\n// std::reference_wrapper). This should work for both WillOnce and\n// WillRepeatedly.\nTEST(ReturnTest, ConversionRequiresConstLvalueReference) {\n  using R = int;\n  using U = std::reference_wrapper<const int>;\n\n  static_assert(std::is_convertible<const R&, U>::value, \"\");\n  static_assert(!std::is_convertible<R, U>::value, \"\");\n\n  MockFunction<U()> mock;\n  EXPECT_CALL(mock, Call).WillOnce(Return(17)).WillRepeatedly(Return(19));\n\n  EXPECT_EQ(17, mock.AsStdFunction()());\n  EXPECT_EQ(19, mock.AsStdFunction()());\n}\n\n// Return(x) should not be usable with a mock function result type that's\n// implicitly convertible from decltype(x) but requires a non-const lvalue\n// reference to the input. It doesn't make sense for the conversion operator to\n// modify the input.\nTEST(ReturnTest, ConversionRequiresMutableLvalueReference) {\n  // Set up a type that is implicitly convertible from std::string&, but not\n  // std::string&& or `const std::string&`.\n  //\n  // Avoid asserting about conversion from std::string on MSVC, which seems to\n  // implement std::is_convertible incorrectly in this case.\n  struct S {\n    S(std::string&) {}  // NOLINT\n  };\n\n  static_assert(std::is_convertible<std::string&, S>::value, \"\");\n#ifndef _MSC_VER\n  static_assert(!std::is_convertible<std::string&&, S>::value, \"\");\n#endif\n  static_assert(!std::is_convertible<const std::string&, S>::value, \"\");\n\n  // It shouldn't be possible to use the result of Return(std::string) in a\n  // context where an S is needed.\n  //\n  // Here too we disable the assertion for MSVC, since its incorrect\n  // implementation of is_convertible causes our SFINAE to be wrong.\n  using RA = decltype(Return(std::string()));\n\n  static_assert(!std::is_convertible<RA, Action<S()>>::value, \"\");\n#ifndef _MSC_VER\n  static_assert(!std::is_convertible<RA, OnceAction<S()>>::value, \"\");\n#endif\n}\n\nTEST(ReturnTest, MoveOnlyResultType) {\n  // Return should support move-only result types when used with WillOnce.\n  {\n    MockFunction<std::unique_ptr<int>()> mock;\n    EXPECT_CALL(mock, Call)\n        // NOLINTNEXTLINE\n        .WillOnce(Return(std::unique_ptr<int>(new int(17))));\n\n    EXPECT_THAT(mock.AsStdFunction()(), Pointee(17));\n  }\n\n  // The result of Return should not be convertible to Action (so it can't be\n  // used with WillRepeatedly).\n  static_assert(!std::is_convertible<decltype(Return(std::unique_ptr<int>())),\n                                     Action<std::unique_ptr<int>()>>::value,\n                \"\");\n}\n\n// Tests that Return(v) is covaraint.\n\nstruct Base {\n  bool operator==(const Base&) { return true; }\n};\n\nstruct Derived : public Base {\n  bool operator==(const Derived&) { return true; }\n};\n\nTEST(ReturnTest, IsCovariant) {\n  Base base;\n  Derived derived;\n  Action<Base*()> ret = Return(&base);\n  EXPECT_EQ(&base, ret.Perform(std::make_tuple()));\n\n  ret = Return(&derived);\n  EXPECT_EQ(&derived, ret.Perform(std::make_tuple()));\n}\n\n// Tests that the type of the value passed into Return is converted into T\n// when the action is cast to Action<T(...)> rather than when the action is\n// performed. See comments on testing::internal::ReturnAction in\n// gmock-actions.h for more information.\nclass FromType {\n public:\n  explicit FromType(bool* is_converted) : converted_(is_converted) {}\n  bool* converted() const { return converted_; }\n\n private:\n  bool* const converted_;\n};\n\nclass ToType {\n public:\n  // Must allow implicit conversion due to use in ImplicitCast_<T>.\n  ToType(const FromType& x) { *x.converted() = true; }  // NOLINT\n};\n\nTEST(ReturnTest, ConvertsArgumentWhenConverted) {\n  bool converted = false;\n  FromType x(&converted);\n  Action<ToType()> action(Return(x));\n  EXPECT_TRUE(converted) << \"Return must convert its argument in its own \"\n                         << \"conversion operator.\";\n  converted = false;\n  action.Perform(std::tuple<>());\n  EXPECT_FALSE(converted) << \"Action must NOT convert its argument \"\n                          << \"when performed.\";\n}\n\n// Tests that ReturnNull() returns NULL in a pointer-returning function.\nTEST(ReturnNullTest, WorksInPointerReturningFunction) {\n  const Action<int*()> a1 = ReturnNull();\n  EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr);\n\n  const Action<const char*(bool)> a2 = ReturnNull();  // NOLINT\n  EXPECT_TRUE(a2.Perform(std::make_tuple(true)) == nullptr);\n}\n\n// Tests that ReturnNull() returns NULL for shared_ptr and unique_ptr returning\n// functions.\nTEST(ReturnNullTest, WorksInSmartPointerReturningFunction) {\n  const Action<std::unique_ptr<const int>()> a1 = ReturnNull();\n  EXPECT_TRUE(a1.Perform(std::make_tuple()) == nullptr);\n\n  const Action<std::shared_ptr<int>(std::string)> a2 = ReturnNull();\n  EXPECT_TRUE(a2.Perform(std::make_tuple(\"foo\")) == nullptr);\n}\n\n// Tests that ReturnRef(v) works for reference types.\nTEST(ReturnRefTest, WorksForReference) {\n  const int n = 0;\n  const Action<const int&(bool)> ret = ReturnRef(n);  // NOLINT\n\n  EXPECT_EQ(&n, &ret.Perform(std::make_tuple(true)));\n}\n\n// Tests that ReturnRef(v) is covariant.\nTEST(ReturnRefTest, IsCovariant) {\n  Base base;\n  Derived derived;\n  Action<Base&()> a = ReturnRef(base);\n  EXPECT_EQ(&base, &a.Perform(std::make_tuple()));\n\n  a = ReturnRef(derived);\n  EXPECT_EQ(&derived, &a.Perform(std::make_tuple()));\n}\n\ntemplate <typename T, typename = decltype(ReturnRef(std::declval<T&&>()))>\nbool CanCallReturnRef(T&&) {\n  return true;\n}\nbool CanCallReturnRef(Unused) { return false; }\n\n// Tests that ReturnRef(v) is working with non-temporaries (T&)\nTEST(ReturnRefTest, WorksForNonTemporary) {\n  int scalar_value = 123;\n  EXPECT_TRUE(CanCallReturnRef(scalar_value));\n\n  std::string non_scalar_value(\"ABC\");\n  EXPECT_TRUE(CanCallReturnRef(non_scalar_value));\n\n  const int const_scalar_value{321};\n  EXPECT_TRUE(CanCallReturnRef(const_scalar_value));\n\n  const std::string const_non_scalar_value(\"CBA\");\n  EXPECT_TRUE(CanCallReturnRef(const_non_scalar_value));\n}\n\n// Tests that ReturnRef(v) is not working with temporaries (T&&)\nTEST(ReturnRefTest, DoesNotWorkForTemporary) {\n  auto scalar_value = []() -> int { return 123; };\n  EXPECT_FALSE(CanCallReturnRef(scalar_value()));\n\n  auto non_scalar_value = []() -> std::string { return \"ABC\"; };\n  EXPECT_FALSE(CanCallReturnRef(non_scalar_value()));\n\n  // cannot use here callable returning \"const scalar type\",\n  // because such const for scalar return type is ignored\n  EXPECT_FALSE(CanCallReturnRef(static_cast<const int>(321)));\n\n  auto const_non_scalar_value = []() -> const std::string { return \"CBA\"; };\n  EXPECT_FALSE(CanCallReturnRef(const_non_scalar_value()));\n}\n\n// Tests that ReturnRefOfCopy(v) works for reference types.\nTEST(ReturnRefOfCopyTest, WorksForReference) {\n  int n = 42;\n  const Action<const int&()> ret = ReturnRefOfCopy(n);\n\n  EXPECT_NE(&n, &ret.Perform(std::make_tuple()));\n  EXPECT_EQ(42, ret.Perform(std::make_tuple()));\n\n  n = 43;\n  EXPECT_NE(&n, &ret.Perform(std::make_tuple()));\n  EXPECT_EQ(42, ret.Perform(std::make_tuple()));\n}\n\n// Tests that ReturnRefOfCopy(v) is covariant.\nTEST(ReturnRefOfCopyTest, IsCovariant) {\n  Base base;\n  Derived derived;\n  Action<Base&()> a = ReturnRefOfCopy(base);\n  EXPECT_NE(&base, &a.Perform(std::make_tuple()));\n\n  a = ReturnRefOfCopy(derived);\n  EXPECT_NE(&derived, &a.Perform(std::make_tuple()));\n}\n\n// Tests that ReturnRoundRobin(v) works with initializer lists\nTEST(ReturnRoundRobinTest, WorksForInitList) {\n  Action<int()> ret = ReturnRoundRobin({1, 2, 3});\n\n  EXPECT_EQ(1, ret.Perform(std::make_tuple()));\n  EXPECT_EQ(2, ret.Perform(std::make_tuple()));\n  EXPECT_EQ(3, ret.Perform(std::make_tuple()));\n  EXPECT_EQ(1, ret.Perform(std::make_tuple()));\n  EXPECT_EQ(2, ret.Perform(std::make_tuple()));\n  EXPECT_EQ(3, ret.Perform(std::make_tuple()));\n}\n\n// Tests that ReturnRoundRobin(v) works with vectors\nTEST(ReturnRoundRobinTest, WorksForVector) {\n  std::vector<double> v = {4.4, 5.5, 6.6};\n  Action<double()> ret = ReturnRoundRobin(v);\n\n  EXPECT_EQ(4.4, ret.Perform(std::make_tuple()));\n  EXPECT_EQ(5.5, ret.Perform(std::make_tuple()));\n  EXPECT_EQ(6.6, ret.Perform(std::make_tuple()));\n  EXPECT_EQ(4.4, ret.Perform(std::make_tuple()));\n  EXPECT_EQ(5.5, ret.Perform(std::make_tuple()));\n  EXPECT_EQ(6.6, ret.Perform(std::make_tuple()));\n}\n\n// Tests that DoDefault() does the default action for the mock method.\n\nclass MockClass {\n public:\n  MockClass() {}\n\n  MOCK_METHOD1(IntFunc, int(bool flag));  // NOLINT\n  MOCK_METHOD0(Foo, MyNonDefaultConstructible());\n  MOCK_METHOD0(MakeUnique, std::unique_ptr<int>());\n  MOCK_METHOD0(MakeUniqueBase, std::unique_ptr<Base>());\n  MOCK_METHOD0(MakeVectorUnique, std::vector<std::unique_ptr<int>>());\n  MOCK_METHOD1(TakeUnique, int(std::unique_ptr<int>));\n  MOCK_METHOD2(TakeUnique,\n               int(const std::unique_ptr<int>&, std::unique_ptr<int>));\n\n private:\n  MockClass(const MockClass&) = delete;\n  MockClass& operator=(const MockClass&) = delete;\n};\n\n// Tests that DoDefault() returns the built-in default value for the\n// return type by default.\nTEST(DoDefaultTest, ReturnsBuiltInDefaultValueByDefault) {\n  MockClass mock;\n  EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());\n  EXPECT_EQ(0, mock.IntFunc(true));\n}\n\n// Tests that DoDefault() throws (when exceptions are enabled) or aborts\n// the process when there is no built-in default value for the return type.\nTEST(DoDefaultDeathTest, DiesForUnknowType) {\n  MockClass mock;\n  EXPECT_CALL(mock, Foo()).WillRepeatedly(DoDefault());\n#if GTEST_HAS_EXCEPTIONS\n  EXPECT_ANY_THROW(mock.Foo());\n#else\n  EXPECT_DEATH_IF_SUPPORTED({ mock.Foo(); }, \"\");\n#endif\n}\n\n// Tests that using DoDefault() inside a composite action leads to a\n// run-time error.\n\nvoid VoidFunc(bool /* flag */) {}\n\nTEST(DoDefaultDeathTest, DiesIfUsedInCompositeAction) {\n  MockClass mock;\n  EXPECT_CALL(mock, IntFunc(_))\n      .WillRepeatedly(DoAll(Invoke(VoidFunc), DoDefault()));\n\n  // Ideally we should verify the error message as well.  Sadly,\n  // EXPECT_DEATH() can only capture stderr, while Google Mock's\n  // errors are printed on stdout.  Therefore we have to settle for\n  // not verifying the message.\n  EXPECT_DEATH_IF_SUPPORTED({ mock.IntFunc(true); }, \"\");\n}\n\n// Tests that DoDefault() returns the default value set by\n// DefaultValue<T>::Set() when it's not overridden by an ON_CALL().\nTEST(DoDefaultTest, ReturnsUserSpecifiedPerTypeDefaultValueWhenThereIsOne) {\n  DefaultValue<int>::Set(1);\n  MockClass mock;\n  EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());\n  EXPECT_EQ(1, mock.IntFunc(false));\n  DefaultValue<int>::Clear();\n}\n\n// Tests that DoDefault() does the action specified by ON_CALL().\nTEST(DoDefaultTest, DoesWhatOnCallSpecifies) {\n  MockClass mock;\n  ON_CALL(mock, IntFunc(_)).WillByDefault(Return(2));\n  EXPECT_CALL(mock, IntFunc(_)).WillOnce(DoDefault());\n  EXPECT_EQ(2, mock.IntFunc(false));\n}\n\n// Tests that using DoDefault() in ON_CALL() leads to a run-time failure.\nTEST(DoDefaultTest, CannotBeUsedInOnCall) {\n  MockClass mock;\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        ON_CALL(mock, IntFunc(_)).WillByDefault(DoDefault());\n      },\n      \"DoDefault() cannot be used in ON_CALL()\");\n}\n\n// Tests that SetArgPointee<N>(v) sets the variable pointed to by\n// the N-th (0-based) argument to v.\nTEST(SetArgPointeeTest, SetsTheNthPointee) {\n  typedef void MyFunction(bool, int*, char*);\n  Action<MyFunction> a = SetArgPointee<1>(2);\n\n  int n = 0;\n  char ch = '\\0';\n  a.Perform(std::make_tuple(true, &n, &ch));\n  EXPECT_EQ(2, n);\n  EXPECT_EQ('\\0', ch);\n\n  a = SetArgPointee<2>('a');\n  n = 0;\n  ch = '\\0';\n  a.Perform(std::make_tuple(true, &n, &ch));\n  EXPECT_EQ(0, n);\n  EXPECT_EQ('a', ch);\n}\n\n// Tests that SetArgPointee<N>() accepts a string literal.\nTEST(SetArgPointeeTest, AcceptsStringLiteral) {\n  typedef void MyFunction(std::string*, const char**);\n  Action<MyFunction> a = SetArgPointee<0>(\"hi\");\n  std::string str;\n  const char* ptr = nullptr;\n  a.Perform(std::make_tuple(&str, &ptr));\n  EXPECT_EQ(\"hi\", str);\n  EXPECT_TRUE(ptr == nullptr);\n\n  a = SetArgPointee<1>(\"world\");\n  str = \"\";\n  a.Perform(std::make_tuple(&str, &ptr));\n  EXPECT_EQ(\"\", str);\n  EXPECT_STREQ(\"world\", ptr);\n}\n\nTEST(SetArgPointeeTest, AcceptsWideStringLiteral) {\n  typedef void MyFunction(const wchar_t**);\n  Action<MyFunction> a = SetArgPointee<0>(L\"world\");\n  const wchar_t* ptr = nullptr;\n  a.Perform(std::make_tuple(&ptr));\n  EXPECT_STREQ(L\"world\", ptr);\n\n#if GTEST_HAS_STD_WSTRING\n\n  typedef void MyStringFunction(std::wstring*);\n  Action<MyStringFunction> a2 = SetArgPointee<0>(L\"world\");\n  std::wstring str = L\"\";\n  a2.Perform(std::make_tuple(&str));\n  EXPECT_EQ(L\"world\", str);\n\n#endif\n}\n\n// Tests that SetArgPointee<N>() accepts a char pointer.\nTEST(SetArgPointeeTest, AcceptsCharPointer) {\n  typedef void MyFunction(bool, std::string*, const char**);\n  const char* const hi = \"hi\";\n  Action<MyFunction> a = SetArgPointee<1>(hi);\n  std::string str;\n  const char* ptr = nullptr;\n  a.Perform(std::make_tuple(true, &str, &ptr));\n  EXPECT_EQ(\"hi\", str);\n  EXPECT_TRUE(ptr == nullptr);\n\n  char world_array[] = \"world\";\n  char* const world = world_array;\n  a = SetArgPointee<2>(world);\n  str = \"\";\n  a.Perform(std::make_tuple(true, &str, &ptr));\n  EXPECT_EQ(\"\", str);\n  EXPECT_EQ(world, ptr);\n}\n\nTEST(SetArgPointeeTest, AcceptsWideCharPointer) {\n  typedef void MyFunction(bool, const wchar_t**);\n  const wchar_t* const hi = L\"hi\";\n  Action<MyFunction> a = SetArgPointee<1>(hi);\n  const wchar_t* ptr = nullptr;\n  a.Perform(std::make_tuple(true, &ptr));\n  EXPECT_EQ(hi, ptr);\n\n#if GTEST_HAS_STD_WSTRING\n\n  typedef void MyStringFunction(bool, std::wstring*);\n  wchar_t world_array[] = L\"world\";\n  wchar_t* const world = world_array;\n  Action<MyStringFunction> a2 = SetArgPointee<1>(world);\n  std::wstring str;\n  a2.Perform(std::make_tuple(true, &str));\n  EXPECT_EQ(world_array, str);\n#endif\n}\n\n// Tests that SetArgumentPointee<N>(v) sets the variable pointed to by\n// the N-th (0-based) argument to v.\nTEST(SetArgumentPointeeTest, SetsTheNthPointee) {\n  typedef void MyFunction(bool, int*, char*);\n  Action<MyFunction> a = SetArgumentPointee<1>(2);\n\n  int n = 0;\n  char ch = '\\0';\n  a.Perform(std::make_tuple(true, &n, &ch));\n  EXPECT_EQ(2, n);\n  EXPECT_EQ('\\0', ch);\n\n  a = SetArgumentPointee<2>('a');\n  n = 0;\n  ch = '\\0';\n  a.Perform(std::make_tuple(true, &n, &ch));\n  EXPECT_EQ(0, n);\n  EXPECT_EQ('a', ch);\n}\n\n// Sample functions and functors for testing Invoke() and etc.\nint Nullary() { return 1; }\n\nclass NullaryFunctor {\n public:\n  int operator()() { return 2; }\n};\n\nbool g_done = false;\nvoid VoidNullary() { g_done = true; }\n\nclass VoidNullaryFunctor {\n public:\n  void operator()() { g_done = true; }\n};\n\nshort Short(short n) { return n; }  // NOLINT\nchar Char(char ch) { return ch; }\n\nconst char* CharPtr(const char* s) { return s; }\n\nbool Unary(int x) { return x < 0; }\n\nconst char* Binary(const char* input, short n) { return input + n; }  // NOLINT\n\nvoid VoidBinary(int, char) { g_done = true; }\n\nint Ternary(int x, char y, short z) { return x + y + z; }  // NOLINT\n\nint SumOf4(int a, int b, int c, int d) { return a + b + c + d; }\n\nclass Foo {\n public:\n  Foo() : value_(123) {}\n\n  int Nullary() const { return value_; }\n\n private:\n  int value_;\n};\n\n// Tests InvokeWithoutArgs(function).\nTEST(InvokeWithoutArgsTest, Function) {\n  // As an action that takes one argument.\n  Action<int(int)> a = InvokeWithoutArgs(Nullary);  // NOLINT\n  EXPECT_EQ(1, a.Perform(std::make_tuple(2)));\n\n  // As an action that takes two arguments.\n  Action<int(int, double)> a2 = InvokeWithoutArgs(Nullary);  // NOLINT\n  EXPECT_EQ(1, a2.Perform(std::make_tuple(2, 3.5)));\n\n  // As an action that returns void.\n  Action<void(int)> a3 = InvokeWithoutArgs(VoidNullary);  // NOLINT\n  g_done = false;\n  a3.Perform(std::make_tuple(1));\n  EXPECT_TRUE(g_done);\n}\n\n// Tests InvokeWithoutArgs(functor).\nTEST(InvokeWithoutArgsTest, Functor) {\n  // As an action that takes no argument.\n  Action<int()> a = InvokeWithoutArgs(NullaryFunctor());  // NOLINT\n  EXPECT_EQ(2, a.Perform(std::make_tuple()));\n\n  // As an action that takes three arguments.\n  Action<int(int, double, char)> a2 =  // NOLINT\n      InvokeWithoutArgs(NullaryFunctor());\n  EXPECT_EQ(2, a2.Perform(std::make_tuple(3, 3.5, 'a')));\n\n  // As an action that returns void.\n  Action<void()> a3 = InvokeWithoutArgs(VoidNullaryFunctor());\n  g_done = false;\n  a3.Perform(std::make_tuple());\n  EXPECT_TRUE(g_done);\n}\n\n// Tests InvokeWithoutArgs(obj_ptr, method).\nTEST(InvokeWithoutArgsTest, Method) {\n  Foo foo;\n  Action<int(bool, char)> a =  // NOLINT\n      InvokeWithoutArgs(&foo, &Foo::Nullary);\n  EXPECT_EQ(123, a.Perform(std::make_tuple(true, 'a')));\n}\n\n// Tests using IgnoreResult() on a polymorphic action.\nTEST(IgnoreResultTest, PolymorphicAction) {\n  Action<void(int)> a = IgnoreResult(Return(5));  // NOLINT\n  a.Perform(std::make_tuple(1));\n}\n\n// Tests using IgnoreResult() on a monomorphic action.\n\nint ReturnOne() {\n  g_done = true;\n  return 1;\n}\n\nTEST(IgnoreResultTest, MonomorphicAction) {\n  g_done = false;\n  Action<void()> a = IgnoreResult(Invoke(ReturnOne));\n  a.Perform(std::make_tuple());\n  EXPECT_TRUE(g_done);\n}\n\n// Tests using IgnoreResult() on an action that returns a class type.\n\nMyNonDefaultConstructible ReturnMyNonDefaultConstructible(double /* x */) {\n  g_done = true;\n  return MyNonDefaultConstructible(42);\n}\n\nTEST(IgnoreResultTest, ActionReturningClass) {\n  g_done = false;\n  Action<void(int)> a =\n      IgnoreResult(Invoke(ReturnMyNonDefaultConstructible));  // NOLINT\n  a.Perform(std::make_tuple(2));\n  EXPECT_TRUE(g_done);\n}\n\nTEST(AssignTest, Int) {\n  int x = 0;\n  Action<void(int)> a = Assign(&x, 5);\n  a.Perform(std::make_tuple(0));\n  EXPECT_EQ(5, x);\n}\n\nTEST(AssignTest, String) {\n  ::std::string x;\n  Action<void(void)> a = Assign(&x, \"Hello, world\");\n  a.Perform(std::make_tuple());\n  EXPECT_EQ(\"Hello, world\", x);\n}\n\nTEST(AssignTest, CompatibleTypes) {\n  double x = 0;\n  Action<void(int)> a = Assign(&x, 5);\n  a.Perform(std::make_tuple(0));\n  EXPECT_DOUBLE_EQ(5, x);\n}\n\n// DoAll should support &&-qualified actions when used with WillOnce.\nTEST(DoAll, SupportsRefQualifiedActions) {\n  struct InitialAction {\n    void operator()(const int arg) && { EXPECT_EQ(17, arg); }\n  };\n\n  struct FinalAction {\n    int operator()() && { return 19; }\n  };\n\n  MockFunction<int(int)> mock;\n  EXPECT_CALL(mock, Call).WillOnce(DoAll(InitialAction{}, FinalAction{}));\n  EXPECT_EQ(19, mock.AsStdFunction()(17));\n}\n\n// DoAll should never provide rvalue references to the initial actions. If the\n// mock action itself accepts an rvalue reference or a non-scalar object by\n// value then the final action should receive an rvalue reference, but initial\n// actions should receive only lvalue references.\nTEST(DoAll, ProvidesLvalueReferencesToInitialActions) {\n  struct Obj {};\n\n  // Mock action accepts by value: the initial action should be fed a const\n  // lvalue reference, and the final action an rvalue reference.\n  {\n    struct InitialAction {\n      void operator()(Obj&) const { FAIL() << \"Unexpected call\"; }\n      void operator()(const Obj&) const {}\n      void operator()(Obj&&) const { FAIL() << \"Unexpected call\"; }\n      void operator()(const Obj&&) const { FAIL() << \"Unexpected call\"; }\n    };\n\n    MockFunction<void(Obj)> mock;\n    EXPECT_CALL(mock, Call)\n        .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}))\n        .WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}));\n\n    mock.AsStdFunction()(Obj{});\n    mock.AsStdFunction()(Obj{});\n  }\n\n  // Mock action accepts by const lvalue reference: both actions should receive\n  // a const lvalue reference.\n  {\n    struct InitialAction {\n      void operator()(Obj&) const { FAIL() << \"Unexpected call\"; }\n      void operator()(const Obj&) const {}\n      void operator()(Obj&&) const { FAIL() << \"Unexpected call\"; }\n      void operator()(const Obj&&) const { FAIL() << \"Unexpected call\"; }\n    };\n\n    MockFunction<void(const Obj&)> mock;\n    EXPECT_CALL(mock, Call)\n        .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](const Obj&) {}))\n        .WillRepeatedly(\n            DoAll(InitialAction{}, InitialAction{}, [](const Obj&) {}));\n\n    mock.AsStdFunction()(Obj{});\n    mock.AsStdFunction()(Obj{});\n  }\n\n  // Mock action accepts by non-const lvalue reference: both actions should get\n  // a non-const lvalue reference if they want them.\n  {\n    struct InitialAction {\n      void operator()(Obj&) const {}\n      void operator()(Obj&&) const { FAIL() << \"Unexpected call\"; }\n    };\n\n    MockFunction<void(Obj&)> mock;\n    EXPECT_CALL(mock, Call)\n        .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {}))\n        .WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {}));\n\n    Obj obj;\n    mock.AsStdFunction()(obj);\n    mock.AsStdFunction()(obj);\n  }\n\n  // Mock action accepts by rvalue reference: the initial actions should receive\n  // a non-const lvalue reference if it wants it, and the final action an rvalue\n  // reference.\n  {\n    struct InitialAction {\n      void operator()(Obj&) const {}\n      void operator()(Obj&&) const { FAIL() << \"Unexpected call\"; }\n    };\n\n    MockFunction<void(Obj &&)> mock;\n    EXPECT_CALL(mock, Call)\n        .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}))\n        .WillRepeatedly(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}));\n\n    mock.AsStdFunction()(Obj{});\n    mock.AsStdFunction()(Obj{});\n  }\n\n  // &&-qualified initial actions should also be allowed with WillOnce.\n  {\n    struct InitialAction {\n      void operator()(Obj&) && {}\n    };\n\n    MockFunction<void(Obj&)> mock;\n    EXPECT_CALL(mock, Call)\n        .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&) {}));\n\n    Obj obj;\n    mock.AsStdFunction()(obj);\n  }\n\n  {\n    struct InitialAction {\n      void operator()(Obj&) && {}\n    };\n\n    MockFunction<void(Obj &&)> mock;\n    EXPECT_CALL(mock, Call)\n        .WillOnce(DoAll(InitialAction{}, InitialAction{}, [](Obj&&) {}));\n\n    mock.AsStdFunction()(Obj{});\n  }\n}\n\n// DoAll should support being used with type-erased Action objects, both through\n// WillOnce and WillRepeatedly.\nTEST(DoAll, SupportsTypeErasedActions) {\n  // With only type-erased actions.\n  const Action<void()> initial_action = [] {};\n  const Action<int()> final_action = [] { return 17; };\n\n  MockFunction<int()> mock;\n  EXPECT_CALL(mock, Call)\n      .WillOnce(DoAll(initial_action, initial_action, final_action))\n      .WillRepeatedly(DoAll(initial_action, initial_action, final_action));\n\n  EXPECT_EQ(17, mock.AsStdFunction()());\n\n  // With &&-qualified and move-only final action.\n  {\n    struct FinalAction {\n      FinalAction() = default;\n      FinalAction(FinalAction&&) = default;\n\n      int operator()() && { return 17; }\n    };\n\n    EXPECT_CALL(mock, Call)\n        .WillOnce(DoAll(initial_action, initial_action, FinalAction{}));\n\n    EXPECT_EQ(17, mock.AsStdFunction()());\n  }\n}\n\n// Tests using WithArgs and with an action that takes 1 argument.\nTEST(WithArgsTest, OneArg) {\n  Action<bool(double x, int n)> a = WithArgs<1>(Invoke(Unary));  // NOLINT\n  EXPECT_TRUE(a.Perform(std::make_tuple(1.5, -1)));\n  EXPECT_FALSE(a.Perform(std::make_tuple(1.5, 1)));\n}\n\n// Tests using WithArgs with an action that takes 2 arguments.\nTEST(WithArgsTest, TwoArgs) {\n  Action<const char*(const char* s, double x, short n)> a =  // NOLINT\n      WithArgs<0, 2>(Invoke(Binary));\n  const char s[] = \"Hello\";\n  EXPECT_EQ(s + 2, a.Perform(std::make_tuple(CharPtr(s), 0.5, Short(2))));\n}\n\nstruct ConcatAll {\n  std::string operator()() const { return {}; }\n  template <typename... I>\n  std::string operator()(const char* a, I... i) const {\n    return a + ConcatAll()(i...);\n  }\n};\n\n// Tests using WithArgs with an action that takes 10 arguments.\nTEST(WithArgsTest, TenArgs) {\n  Action<std::string(const char*, const char*, const char*, const char*)> a =\n      WithArgs<0, 1, 2, 3, 2, 1, 0, 1, 2, 3>(Invoke(ConcatAll{}));\n  EXPECT_EQ(\"0123210123\",\n            a.Perform(std::make_tuple(CharPtr(\"0\"), CharPtr(\"1\"), CharPtr(\"2\"),\n                                      CharPtr(\"3\"))));\n}\n\n// Tests using WithArgs with an action that is not Invoke().\nclass SubtractAction : public ActionInterface<int(int, int)> {\n public:\n  int Perform(const std::tuple<int, int>& args) override {\n    return std::get<0>(args) - std::get<1>(args);\n  }\n};\n\nTEST(WithArgsTest, NonInvokeAction) {\n  Action<int(const std::string&, int, int)> a =\n      WithArgs<2, 1>(MakeAction(new SubtractAction));\n  std::tuple<std::string, int, int> dummy =\n      std::make_tuple(std::string(\"hi\"), 2, 10);\n  EXPECT_EQ(8, a.Perform(dummy));\n}\n\n// Tests using WithArgs to pass all original arguments in the original order.\nTEST(WithArgsTest, Identity) {\n  Action<int(int x, char y, short z)> a =  // NOLINT\n      WithArgs<0, 1, 2>(Invoke(Ternary));\n  EXPECT_EQ(123, a.Perform(std::make_tuple(100, Char(20), Short(3))));\n}\n\n// Tests using WithArgs with repeated arguments.\nTEST(WithArgsTest, RepeatedArguments) {\n  Action<int(bool, int m, int n)> a =  // NOLINT\n      WithArgs<1, 1, 1, 1>(Invoke(SumOf4));\n  EXPECT_EQ(4, a.Perform(std::make_tuple(false, 1, 10)));\n}\n\n// Tests using WithArgs with reversed argument order.\nTEST(WithArgsTest, ReversedArgumentOrder) {\n  Action<const char*(short n, const char* input)> a =  // NOLINT\n      WithArgs<1, 0>(Invoke(Binary));\n  const char s[] = \"Hello\";\n  EXPECT_EQ(s + 2, a.Perform(std::make_tuple(Short(2), CharPtr(s))));\n}\n\n// Tests using WithArgs with compatible, but not identical, argument types.\nTEST(WithArgsTest, ArgsOfCompatibleTypes) {\n  Action<long(short x, char y, double z, char c)> a =  // NOLINT\n      WithArgs<0, 1, 3>(Invoke(Ternary));\n  EXPECT_EQ(123,\n            a.Perform(std::make_tuple(Short(100), Char(20), 5.6, Char(3))));\n}\n\n// Tests using WithArgs with an action that returns void.\nTEST(WithArgsTest, VoidAction) {\n  Action<void(double x, char c, int n)> a = WithArgs<2, 1>(Invoke(VoidBinary));\n  g_done = false;\n  a.Perform(std::make_tuple(1.5, 'a', 3));\n  EXPECT_TRUE(g_done);\n}\n\nTEST(WithArgsTest, ReturnReference) {\n  Action<int&(int&, void*)> aa = WithArgs<0>([](int& a) -> int& { return a; });\n  int i = 0;\n  const int& res = aa.Perform(std::forward_as_tuple(i, nullptr));\n  EXPECT_EQ(&i, &res);\n}\n\nTEST(WithArgsTest, InnerActionWithConversion) {\n  Action<Derived*()> inner = [] { return nullptr; };\n\n  MockFunction<Base*(double)> mock;\n  EXPECT_CALL(mock, Call)\n      .WillOnce(WithoutArgs(inner))\n      .WillRepeatedly(WithoutArgs(inner));\n\n  EXPECT_EQ(nullptr, mock.AsStdFunction()(1.1));\n  EXPECT_EQ(nullptr, mock.AsStdFunction()(1.1));\n}\n\n// It should be possible to use an &&-qualified inner action as long as the\n// whole shebang is used as an rvalue with WillOnce.\nTEST(WithArgsTest, RefQualifiedInnerAction) {\n  struct SomeAction {\n    int operator()(const int arg) && {\n      EXPECT_EQ(17, arg);\n      return 19;\n    }\n  };\n\n  MockFunction<int(int, int)> mock;\n  EXPECT_CALL(mock, Call).WillOnce(WithArg<1>(SomeAction{}));\n  EXPECT_EQ(19, mock.AsStdFunction()(0, 17));\n}\n\n#if !GTEST_OS_WINDOWS_MOBILE\n\nclass SetErrnoAndReturnTest : public testing::Test {\n protected:\n  void SetUp() override { errno = 0; }\n  void TearDown() override { errno = 0; }\n};\n\nTEST_F(SetErrnoAndReturnTest, Int) {\n  Action<int(void)> a = SetErrnoAndReturn(ENOTTY, -5);\n  EXPECT_EQ(-5, a.Perform(std::make_tuple()));\n  EXPECT_EQ(ENOTTY, errno);\n}\n\nTEST_F(SetErrnoAndReturnTest, Ptr) {\n  int x;\n  Action<int*(void)> a = SetErrnoAndReturn(ENOTTY, &x);\n  EXPECT_EQ(&x, a.Perform(std::make_tuple()));\n  EXPECT_EQ(ENOTTY, errno);\n}\n\nTEST_F(SetErrnoAndReturnTest, CompatibleTypes) {\n  Action<double()> a = SetErrnoAndReturn(EINVAL, 5);\n  EXPECT_DOUBLE_EQ(5.0, a.Perform(std::make_tuple()));\n  EXPECT_EQ(EINVAL, errno);\n}\n\n#endif  // !GTEST_OS_WINDOWS_MOBILE\n\n// Tests ByRef().\n\n// Tests that the result of ByRef() is copyable.\nTEST(ByRefTest, IsCopyable) {\n  const std::string s1 = \"Hi\";\n  const std::string s2 = \"Hello\";\n\n  auto ref_wrapper = ByRef(s1);\n  const std::string& r1 = ref_wrapper;\n  EXPECT_EQ(&s1, &r1);\n\n  // Assigns a new value to ref_wrapper.\n  ref_wrapper = ByRef(s2);\n  const std::string& r2 = ref_wrapper;\n  EXPECT_EQ(&s2, &r2);\n\n  auto ref_wrapper1 = ByRef(s1);\n  // Copies ref_wrapper1 to ref_wrapper.\n  ref_wrapper = ref_wrapper1;\n  const std::string& r3 = ref_wrapper;\n  EXPECT_EQ(&s1, &r3);\n}\n\n// Tests using ByRef() on a const value.\nTEST(ByRefTest, ConstValue) {\n  const int n = 0;\n  // int& ref = ByRef(n);  // This shouldn't compile - we have a\n  // negative compilation test to catch it.\n  const int& const_ref = ByRef(n);\n  EXPECT_EQ(&n, &const_ref);\n}\n\n// Tests using ByRef() on a non-const value.\nTEST(ByRefTest, NonConstValue) {\n  int n = 0;\n\n  // ByRef(n) can be used as either an int&,\n  int& ref = ByRef(n);\n  EXPECT_EQ(&n, &ref);\n\n  // or a const int&.\n  const int& const_ref = ByRef(n);\n  EXPECT_EQ(&n, &const_ref);\n}\n\n// Tests explicitly specifying the type when using ByRef().\nTEST(ByRefTest, ExplicitType) {\n  int n = 0;\n  const int& r1 = ByRef<const int>(n);\n  EXPECT_EQ(&n, &r1);\n\n  // ByRef<char>(n);  // This shouldn't compile - we have a negative\n  // compilation test to catch it.\n\n  Derived d;\n  Derived& r2 = ByRef<Derived>(d);\n  EXPECT_EQ(&d, &r2);\n\n  const Derived& r3 = ByRef<const Derived>(d);\n  EXPECT_EQ(&d, &r3);\n\n  Base& r4 = ByRef<Base>(d);\n  EXPECT_EQ(&d, &r4);\n\n  const Base& r5 = ByRef<const Base>(d);\n  EXPECT_EQ(&d, &r5);\n\n  // The following shouldn't compile - we have a negative compilation\n  // test for it.\n  //\n  // Base b;\n  // ByRef<Derived>(b);\n}\n\n// Tests that Google Mock prints expression ByRef(x) as a reference to x.\nTEST(ByRefTest, PrintsCorrectly) {\n  int n = 42;\n  ::std::stringstream expected, actual;\n  testing::internal::UniversalPrinter<const int&>::Print(n, &expected);\n  testing::internal::UniversalPrint(ByRef(n), &actual);\n  EXPECT_EQ(expected.str(), actual.str());\n}\n\nstruct UnaryConstructorClass {\n  explicit UnaryConstructorClass(int v) : value(v) {}\n  int value;\n};\n\n// Tests using ReturnNew() with a unary constructor.\nTEST(ReturnNewTest, Unary) {\n  Action<UnaryConstructorClass*()> a = ReturnNew<UnaryConstructorClass>(4000);\n  UnaryConstructorClass* c = a.Perform(std::make_tuple());\n  EXPECT_EQ(4000, c->value);\n  delete c;\n}\n\nTEST(ReturnNewTest, UnaryWorksWhenMockMethodHasArgs) {\n  Action<UnaryConstructorClass*(bool, int)> a =\n      ReturnNew<UnaryConstructorClass>(4000);\n  UnaryConstructorClass* c = a.Perform(std::make_tuple(false, 5));\n  EXPECT_EQ(4000, c->value);\n  delete c;\n}\n\nTEST(ReturnNewTest, UnaryWorksWhenMockMethodReturnsPointerToConst) {\n  Action<const UnaryConstructorClass*()> a =\n      ReturnNew<UnaryConstructorClass>(4000);\n  const UnaryConstructorClass* c = a.Perform(std::make_tuple());\n  EXPECT_EQ(4000, c->value);\n  delete c;\n}\n\nclass TenArgConstructorClass {\n public:\n  TenArgConstructorClass(int a1, int a2, int a3, int a4, int a5, int a6, int a7,\n                         int a8, int a9, int a10)\n      : value_(a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) {}\n  int value_;\n};\n\n// Tests using ReturnNew() with a 10-argument constructor.\nTEST(ReturnNewTest, ConstructorThatTakes10Arguments) {\n  Action<TenArgConstructorClass*()> a = ReturnNew<TenArgConstructorClass>(\n      1000000000, 200000000, 30000000, 4000000, 500000, 60000, 7000, 800, 90,\n      0);\n  TenArgConstructorClass* c = a.Perform(std::make_tuple());\n  EXPECT_EQ(1234567890, c->value_);\n  delete c;\n}\n\nstd::unique_ptr<int> UniquePtrSource() {\n  return std::unique_ptr<int>(new int(19));\n}\n\nstd::vector<std::unique_ptr<int>> VectorUniquePtrSource() {\n  std::vector<std::unique_ptr<int>> out;\n  out.emplace_back(new int(7));\n  return out;\n}\n\nTEST(MockMethodTest, CanReturnMoveOnlyValue_Return) {\n  MockClass mock;\n  std::unique_ptr<int> i(new int(19));\n  EXPECT_CALL(mock, MakeUnique()).WillOnce(Return(ByMove(std::move(i))));\n  EXPECT_CALL(mock, MakeVectorUnique())\n      .WillOnce(Return(ByMove(VectorUniquePtrSource())));\n  Derived* d = new Derived;\n  EXPECT_CALL(mock, MakeUniqueBase())\n      .WillOnce(Return(ByMove(std::unique_ptr<Derived>(d))));\n\n  std::unique_ptr<int> result1 = mock.MakeUnique();\n  EXPECT_EQ(19, *result1);\n\n  std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();\n  EXPECT_EQ(1u, vresult.size());\n  EXPECT_NE(nullptr, vresult[0]);\n  EXPECT_EQ(7, *vresult[0]);\n\n  std::unique_ptr<Base> result2 = mock.MakeUniqueBase();\n  EXPECT_EQ(d, result2.get());\n}\n\nTEST(MockMethodTest, CanReturnMoveOnlyValue_DoAllReturn) {\n  testing::MockFunction<void()> mock_function;\n  MockClass mock;\n  std::unique_ptr<int> i(new int(19));\n  EXPECT_CALL(mock_function, Call());\n  EXPECT_CALL(mock, MakeUnique())\n      .WillOnce(DoAll(InvokeWithoutArgs(&mock_function,\n                                        &testing::MockFunction<void()>::Call),\n                      Return(ByMove(std::move(i)))));\n\n  std::unique_ptr<int> result1 = mock.MakeUnique();\n  EXPECT_EQ(19, *result1);\n}\n\nTEST(MockMethodTest, CanReturnMoveOnlyValue_Invoke) {\n  MockClass mock;\n\n  // Check default value\n  DefaultValue<std::unique_ptr<int>>::SetFactory(\n      [] { return std::unique_ptr<int>(new int(42)); });\n  EXPECT_EQ(42, *mock.MakeUnique());\n\n  EXPECT_CALL(mock, MakeUnique()).WillRepeatedly(Invoke(UniquePtrSource));\n  EXPECT_CALL(mock, MakeVectorUnique())\n      .WillRepeatedly(Invoke(VectorUniquePtrSource));\n  std::unique_ptr<int> result1 = mock.MakeUnique();\n  EXPECT_EQ(19, *result1);\n  std::unique_ptr<int> result2 = mock.MakeUnique();\n  EXPECT_EQ(19, *result2);\n  EXPECT_NE(result1, result2);\n\n  std::vector<std::unique_ptr<int>> vresult = mock.MakeVectorUnique();\n  EXPECT_EQ(1u, vresult.size());\n  EXPECT_NE(nullptr, vresult[0]);\n  EXPECT_EQ(7, *vresult[0]);\n}\n\nTEST(MockMethodTest, CanTakeMoveOnlyValue) {\n  MockClass mock;\n  auto make = [](int i) { return std::unique_ptr<int>(new int(i)); };\n\n  EXPECT_CALL(mock, TakeUnique(_)).WillRepeatedly([](std::unique_ptr<int> i) {\n    return *i;\n  });\n  // DoAll() does not compile, since it would move from its arguments twice.\n  // EXPECT_CALL(mock, TakeUnique(_, _))\n  //     .WillRepeatedly(DoAll(Invoke([](std::unique_ptr<int> j) {}),\n  //     Return(1)));\n  EXPECT_CALL(mock, TakeUnique(testing::Pointee(7)))\n      .WillOnce(Return(-7))\n      .RetiresOnSaturation();\n  EXPECT_CALL(mock, TakeUnique(testing::IsNull()))\n      .WillOnce(Return(-1))\n      .RetiresOnSaturation();\n\n  EXPECT_EQ(5, mock.TakeUnique(make(5)));\n  EXPECT_EQ(-7, mock.TakeUnique(make(7)));\n  EXPECT_EQ(7, mock.TakeUnique(make(7)));\n  EXPECT_EQ(7, mock.TakeUnique(make(7)));\n  EXPECT_EQ(-1, mock.TakeUnique({}));\n\n  // Some arguments are moved, some passed by reference.\n  auto lvalue = make(6);\n  EXPECT_CALL(mock, TakeUnique(_, _))\n      .WillOnce([](const std::unique_ptr<int>& i, std::unique_ptr<int> j) {\n        return *i * *j;\n      });\n  EXPECT_EQ(42, mock.TakeUnique(lvalue, make(7)));\n\n  // The unique_ptr can be saved by the action.\n  std::unique_ptr<int> saved;\n  EXPECT_CALL(mock, TakeUnique(_)).WillOnce([&saved](std::unique_ptr<int> i) {\n    saved = std::move(i);\n    return 0;\n  });\n  EXPECT_EQ(0, mock.TakeUnique(make(42)));\n  EXPECT_EQ(42, *saved);\n}\n\n// It should be possible to use callables with an &&-qualified call operator\n// with WillOnce, since they will be called only once. This allows actions to\n// contain and manipulate move-only types.\nTEST(MockMethodTest, ActionHasRvalueRefQualifiedCallOperator) {\n  struct Return17 {\n    int operator()() && { return 17; }\n  };\n\n  // Action is directly compatible with mocked function type.\n  {\n    MockFunction<int()> mock;\n    EXPECT_CALL(mock, Call).WillOnce(Return17());\n\n    EXPECT_EQ(17, mock.AsStdFunction()());\n  }\n\n  // Action doesn't want mocked function arguments.\n  {\n    MockFunction<int(int)> mock;\n    EXPECT_CALL(mock, Call).WillOnce(Return17());\n\n    EXPECT_EQ(17, mock.AsStdFunction()(0));\n  }\n}\n\n// Edge case: if an action has both a const-qualified and an &&-qualified call\n// operator, there should be no \"ambiguous call\" errors. The &&-qualified\n// operator should be used by WillOnce (since it doesn't need to retain the\n// action beyond one call), and the const-qualified one by WillRepeatedly.\nTEST(MockMethodTest, ActionHasMultipleCallOperators) {\n  struct ReturnInt {\n    int operator()() && { return 17; }\n    int operator()() const& { return 19; }\n  };\n\n  // Directly compatible with mocked function type.\n  {\n    MockFunction<int()> mock;\n    EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt());\n\n    EXPECT_EQ(17, mock.AsStdFunction()());\n    EXPECT_EQ(19, mock.AsStdFunction()());\n    EXPECT_EQ(19, mock.AsStdFunction()());\n  }\n\n  // Ignores function arguments.\n  {\n    MockFunction<int(int)> mock;\n    EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt());\n\n    EXPECT_EQ(17, mock.AsStdFunction()(0));\n    EXPECT_EQ(19, mock.AsStdFunction()(0));\n    EXPECT_EQ(19, mock.AsStdFunction()(0));\n  }\n}\n\n// WillOnce should have no problem coping with a move-only action, whether it is\n// &&-qualified or not.\nTEST(MockMethodTest, MoveOnlyAction) {\n  // &&-qualified\n  {\n    struct Return17 {\n      Return17() = default;\n      Return17(Return17&&) = default;\n\n      Return17(const Return17&) = delete;\n      Return17 operator=(const Return17&) = delete;\n\n      int operator()() && { return 17; }\n    };\n\n    MockFunction<int()> mock;\n    EXPECT_CALL(mock, Call).WillOnce(Return17());\n    EXPECT_EQ(17, mock.AsStdFunction()());\n  }\n\n  // Not &&-qualified\n  {\n    struct Return17 {\n      Return17() = default;\n      Return17(Return17&&) = default;\n\n      Return17(const Return17&) = delete;\n      Return17 operator=(const Return17&) = delete;\n\n      int operator()() const { return 17; }\n    };\n\n    MockFunction<int()> mock;\n    EXPECT_CALL(mock, Call).WillOnce(Return17());\n    EXPECT_EQ(17, mock.AsStdFunction()());\n  }\n}\n\n// It should be possible to use an action that returns a value with a mock\n// function that doesn't, both through WillOnce and WillRepeatedly.\nTEST(MockMethodTest, ActionReturnsIgnoredValue) {\n  struct ReturnInt {\n    int operator()() const { return 0; }\n  };\n\n  MockFunction<void()> mock;\n  EXPECT_CALL(mock, Call).WillOnce(ReturnInt()).WillRepeatedly(ReturnInt());\n\n  mock.AsStdFunction()();\n  mock.AsStdFunction()();\n}\n\n// Despite the fanciness around move-only actions and so on, it should still be\n// possible to hand an lvalue reference to a copyable action to WillOnce.\nTEST(MockMethodTest, WillOnceCanAcceptLvalueReference) {\n  MockFunction<int()> mock;\n\n  const auto action = [] { return 17; };\n  EXPECT_CALL(mock, Call).WillOnce(action);\n\n  EXPECT_EQ(17, mock.AsStdFunction()());\n}\n\n// A callable that doesn't use SFINAE to restrict its call operator's overload\n// set, but is still picky about which arguments it will accept.\nstruct StaticAssertSingleArgument {\n  template <typename... Args>\n  static constexpr bool CheckArgs() {\n    static_assert(sizeof...(Args) == 1, \"\");\n    return true;\n  }\n\n  template <typename... Args, bool = CheckArgs<Args...>()>\n  int operator()(Args...) const {\n    return 17;\n  }\n};\n\n// WillOnce and WillRepeatedly should both work fine with naïve implementations\n// of actions that don't use SFINAE to limit the overload set for their call\n// operator. If they are compatible with the actual mocked signature, we\n// shouldn't probe them with no arguments and trip a static_assert.\nTEST(MockMethodTest, ActionSwallowsAllArguments) {\n  MockFunction<int(int)> mock;\n  EXPECT_CALL(mock, Call)\n      .WillOnce(StaticAssertSingleArgument{})\n      .WillRepeatedly(StaticAssertSingleArgument{});\n\n  EXPECT_EQ(17, mock.AsStdFunction()(0));\n  EXPECT_EQ(17, mock.AsStdFunction()(0));\n}\n\nstruct ActionWithTemplatedConversionOperators {\n  template <typename... Args>\n  operator OnceAction<int(Args...)>() && {  // NOLINT\n    return [] { return 17; };\n  }\n\n  template <typename... Args>\n  operator Action<int(Args...)>() const {  // NOLINT\n    return [] { return 19; };\n  }\n};\n\n// It should be fine to hand both WillOnce and WillRepeatedly a function that\n// defines templated conversion operators to OnceAction and Action. WillOnce\n// should prefer the OnceAction version.\nTEST(MockMethodTest, ActionHasTemplatedConversionOperators) {\n  MockFunction<int()> mock;\n  EXPECT_CALL(mock, Call)\n      .WillOnce(ActionWithTemplatedConversionOperators{})\n      .WillRepeatedly(ActionWithTemplatedConversionOperators{});\n\n  EXPECT_EQ(17, mock.AsStdFunction()());\n  EXPECT_EQ(19, mock.AsStdFunction()());\n}\n\n// Tests for std::function based action.\n\nint Add(int val, int& ref, int* ptr) {  // NOLINT\n  int result = val + ref + *ptr;\n  ref = 42;\n  *ptr = 43;\n  return result;\n}\n\nint Deref(std::unique_ptr<int> ptr) { return *ptr; }\n\nstruct Double {\n  template <typename T>\n  T operator()(T t) {\n    return 2 * t;\n  }\n};\n\nstd::unique_ptr<int> UniqueInt(int i) {\n  return std::unique_ptr<int>(new int(i));\n}\n\nTEST(FunctorActionTest, ActionFromFunction) {\n  Action<int(int, int&, int*)> a = &Add;\n  int x = 1, y = 2, z = 3;\n  EXPECT_EQ(6, a.Perform(std::forward_as_tuple(x, y, &z)));\n  EXPECT_EQ(42, y);\n  EXPECT_EQ(43, z);\n\n  Action<int(std::unique_ptr<int>)> a1 = &Deref;\n  EXPECT_EQ(7, a1.Perform(std::make_tuple(UniqueInt(7))));\n}\n\nTEST(FunctorActionTest, ActionFromLambda) {\n  Action<int(bool, int)> a1 = [](bool b, int i) { return b ? i : 0; };\n  EXPECT_EQ(5, a1.Perform(std::make_tuple(true, 5)));\n  EXPECT_EQ(0, a1.Perform(std::make_tuple(false, 5)));\n\n  std::unique_ptr<int> saved;\n  Action<void(std::unique_ptr<int>)> a2 = [&saved](std::unique_ptr<int> p) {\n    saved = std::move(p);\n  };\n  a2.Perform(std::make_tuple(UniqueInt(5)));\n  EXPECT_EQ(5, *saved);\n}\n\nTEST(FunctorActionTest, PolymorphicFunctor) {\n  Action<int(int)> ai = Double();\n  EXPECT_EQ(2, ai.Perform(std::make_tuple(1)));\n  Action<double(double)> ad = Double();  // Double? Double double!\n  EXPECT_EQ(3.0, ad.Perform(std::make_tuple(1.5)));\n}\n\nTEST(FunctorActionTest, TypeConversion) {\n  // Numeric promotions are allowed.\n  const Action<bool(int)> a1 = [](int i) { return i > 1; };\n  const Action<int(bool)> a2 = Action<int(bool)>(a1);\n  EXPECT_EQ(1, a1.Perform(std::make_tuple(42)));\n  EXPECT_EQ(0, a2.Perform(std::make_tuple(42)));\n\n  // Implicit constructors are allowed.\n  const Action<bool(std::string)> s1 = [](std::string s) { return !s.empty(); };\n  const Action<int(const char*)> s2 = Action<int(const char*)>(s1);\n  EXPECT_EQ(0, s2.Perform(std::make_tuple(\"\")));\n  EXPECT_EQ(1, s2.Perform(std::make_tuple(\"hello\")));\n\n  // Also between the lambda and the action itself.\n  const Action<bool(std::string)> x1 = [](Unused) { return 42; };\n  const Action<bool(std::string)> x2 = [] { return 42; };\n  EXPECT_TRUE(x1.Perform(std::make_tuple(\"hello\")));\n  EXPECT_TRUE(x2.Perform(std::make_tuple(\"hello\")));\n\n  // Ensure decay occurs where required.\n  std::function<int()> f = [] { return 7; };\n  Action<int(int)> d = f;\n  f = nullptr;\n  EXPECT_EQ(7, d.Perform(std::make_tuple(1)));\n\n  // Ensure creation of an empty action succeeds.\n  Action<void(int)>(nullptr);\n}\n\nTEST(FunctorActionTest, UnusedArguments) {\n  // Verify that users can ignore uninteresting arguments.\n  Action<int(int, double y, double z)> a = [](int i, Unused, Unused) {\n    return 2 * i;\n  };\n  std::tuple<int, double, double> dummy = std::make_tuple(3, 7.3, 9.44);\n  EXPECT_EQ(6, a.Perform(dummy));\n}\n\n// Test that basic built-in actions work with move-only arguments.\nTEST(MoveOnlyArgumentsTest, ReturningActions) {\n  Action<int(std::unique_ptr<int>)> a = Return(1);\n  EXPECT_EQ(1, a.Perform(std::make_tuple(nullptr)));\n\n  a = testing::WithoutArgs([]() { return 7; });\n  EXPECT_EQ(7, a.Perform(std::make_tuple(nullptr)));\n\n  Action<void(std::unique_ptr<int>, int*)> a2 = testing::SetArgPointee<1>(3);\n  int x = 0;\n  a2.Perform(std::make_tuple(nullptr, &x));\n  EXPECT_EQ(x, 3);\n}\n\nACTION(ReturnArity) { return std::tuple_size<args_type>::value; }\n\nTEST(ActionMacro, LargeArity) {\n  EXPECT_EQ(\n      1, testing::Action<int(int)>(ReturnArity()).Perform(std::make_tuple(0)));\n  EXPECT_EQ(\n      10,\n      testing::Action<int(int, int, int, int, int, int, int, int, int, int)>(\n          ReturnArity())\n          .Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)));\n  EXPECT_EQ(\n      20,\n      testing::Action<int(int, int, int, int, int, int, int, int, int, int, int,\n                          int, int, int, int, int, int, int, int, int)>(\n          ReturnArity())\n          .Perform(std::make_tuple(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,\n                                   14, 15, 16, 17, 18, 19)));\n}\n\n}  // namespace\n}  // namespace testing\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock-cardinalities_test.cc",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file tests the built-in cardinalities.\n\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest-spi.h\"\n#include \"gtest/gtest.h\"\n\nnamespace {\n\nusing std::stringstream;\nusing testing::AnyNumber;\nusing testing::AtLeast;\nusing testing::AtMost;\nusing testing::Between;\nusing testing::Cardinality;\nusing testing::CardinalityInterface;\nusing testing::Exactly;\nusing testing::IsSubstring;\nusing testing::MakeCardinality;\n\nclass MockFoo {\n public:\n  MockFoo() {}\n  MOCK_METHOD0(Bar, int());  // NOLINT\n\n private:\n  MockFoo(const MockFoo&) = delete;\n  MockFoo& operator=(const MockFoo&) = delete;\n};\n\n// Tests that Cardinality objects can be default constructed.\nTEST(CardinalityTest, IsDefaultConstructable) { Cardinality c; }\n\n// Tests that Cardinality objects are copyable.\nTEST(CardinalityTest, IsCopyable) {\n  // Tests the copy constructor.\n  Cardinality c = Exactly(1);\n  EXPECT_FALSE(c.IsSatisfiedByCallCount(0));\n  EXPECT_TRUE(c.IsSatisfiedByCallCount(1));\n  EXPECT_TRUE(c.IsSaturatedByCallCount(1));\n\n  // Tests the assignment operator.\n  c = Exactly(2);\n  EXPECT_FALSE(c.IsSatisfiedByCallCount(1));\n  EXPECT_TRUE(c.IsSatisfiedByCallCount(2));\n  EXPECT_TRUE(c.IsSaturatedByCallCount(2));\n}\n\nTEST(CardinalityTest, IsOverSaturatedByCallCountWorks) {\n  const Cardinality c = AtMost(5);\n  EXPECT_FALSE(c.IsOverSaturatedByCallCount(4));\n  EXPECT_FALSE(c.IsOverSaturatedByCallCount(5));\n  EXPECT_TRUE(c.IsOverSaturatedByCallCount(6));\n}\n\n// Tests that Cardinality::DescribeActualCallCountTo() creates the\n// correct description.\nTEST(CardinalityTest, CanDescribeActualCallCount) {\n  stringstream ss0;\n  Cardinality::DescribeActualCallCountTo(0, &ss0);\n  EXPECT_EQ(\"never called\", ss0.str());\n\n  stringstream ss1;\n  Cardinality::DescribeActualCallCountTo(1, &ss1);\n  EXPECT_EQ(\"called once\", ss1.str());\n\n  stringstream ss2;\n  Cardinality::DescribeActualCallCountTo(2, &ss2);\n  EXPECT_EQ(\"called twice\", ss2.str());\n\n  stringstream ss3;\n  Cardinality::DescribeActualCallCountTo(3, &ss3);\n  EXPECT_EQ(\"called 3 times\", ss3.str());\n}\n\n// Tests AnyNumber()\nTEST(AnyNumber, Works) {\n  const Cardinality c = AnyNumber();\n  EXPECT_TRUE(c.IsSatisfiedByCallCount(0));\n  EXPECT_FALSE(c.IsSaturatedByCallCount(0));\n\n  EXPECT_TRUE(c.IsSatisfiedByCallCount(1));\n  EXPECT_FALSE(c.IsSaturatedByCallCount(1));\n\n  EXPECT_TRUE(c.IsSatisfiedByCallCount(9));\n  EXPECT_FALSE(c.IsSaturatedByCallCount(9));\n\n  stringstream ss;\n  c.DescribeTo(&ss);\n  EXPECT_PRED_FORMAT2(IsSubstring, \"called any number of times\", ss.str());\n}\n\nTEST(AnyNumberTest, HasCorrectBounds) {\n  const Cardinality c = AnyNumber();\n  EXPECT_EQ(0, c.ConservativeLowerBound());\n  EXPECT_EQ(INT_MAX, c.ConservativeUpperBound());\n}\n\n// Tests AtLeast(n).\n\nTEST(AtLeastTest, OnNegativeNumber) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        AtLeast(-1);\n      },\n      \"The invocation lower bound must be >= 0\");\n}\n\nTEST(AtLeastTest, OnZero) {\n  const Cardinality c = AtLeast(0);\n  EXPECT_TRUE(c.IsSatisfiedByCallCount(0));\n  EXPECT_FALSE(c.IsSaturatedByCallCount(0));\n\n  EXPECT_TRUE(c.IsSatisfiedByCallCount(1));\n  EXPECT_FALSE(c.IsSaturatedByCallCount(1));\n\n  stringstream ss;\n  c.DescribeTo(&ss);\n  EXPECT_PRED_FORMAT2(IsSubstring, \"any number of times\", ss.str());\n}\n\nTEST(AtLeastTest, OnPositiveNumber) {\n  const Cardinality c = AtLeast(2);\n  EXPECT_FALSE(c.IsSatisfiedByCallCount(0));\n  EXPECT_FALSE(c.IsSaturatedByCallCount(0));\n\n  EXPECT_FALSE(c.IsSatisfiedByCallCount(1));\n  EXPECT_FALSE(c.IsSaturatedByCallCount(1));\n\n  EXPECT_TRUE(c.IsSatisfiedByCallCount(2));\n  EXPECT_FALSE(c.IsSaturatedByCallCount(2));\n\n  stringstream ss1;\n  AtLeast(1).DescribeTo(&ss1);\n  EXPECT_PRED_FORMAT2(IsSubstring, \"at least once\", ss1.str());\n\n  stringstream ss2;\n  c.DescribeTo(&ss2);\n  EXPECT_PRED_FORMAT2(IsSubstring, \"at least twice\", ss2.str());\n\n  stringstream ss3;\n  AtLeast(3).DescribeTo(&ss3);\n  EXPECT_PRED_FORMAT2(IsSubstring, \"at least 3 times\", ss3.str());\n}\n\nTEST(AtLeastTest, HasCorrectBounds) {\n  const Cardinality c = AtLeast(2);\n  EXPECT_EQ(2, c.ConservativeLowerBound());\n  EXPECT_EQ(INT_MAX, c.ConservativeUpperBound());\n}\n\n// Tests AtMost(n).\n\nTEST(AtMostTest, OnNegativeNumber) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        AtMost(-1);\n      },\n      \"The invocation upper bound must be >= 0\");\n}\n\nTEST(AtMostTest, OnZero) {\n  const Cardinality c = AtMost(0);\n  EXPECT_TRUE(c.IsSatisfiedByCallCount(0));\n  EXPECT_TRUE(c.IsSaturatedByCallCount(0));\n\n  EXPECT_FALSE(c.IsSatisfiedByCallCount(1));\n  EXPECT_TRUE(c.IsSaturatedByCallCount(1));\n\n  stringstream ss;\n  c.DescribeTo(&ss);\n  EXPECT_PRED_FORMAT2(IsSubstring, \"never called\", ss.str());\n}\n\nTEST(AtMostTest, OnPositiveNumber) {\n  const Cardinality c = AtMost(2);\n  EXPECT_TRUE(c.IsSatisfiedByCallCount(0));\n  EXPECT_FALSE(c.IsSaturatedByCallCount(0));\n\n  EXPECT_TRUE(c.IsSatisfiedByCallCount(1));\n  EXPECT_FALSE(c.IsSaturatedByCallCount(1));\n\n  EXPECT_TRUE(c.IsSatisfiedByCallCount(2));\n  EXPECT_TRUE(c.IsSaturatedByCallCount(2));\n\n  stringstream ss1;\n  AtMost(1).DescribeTo(&ss1);\n  EXPECT_PRED_FORMAT2(IsSubstring, \"called at most once\", ss1.str());\n\n  stringstream ss2;\n  c.DescribeTo(&ss2);\n  EXPECT_PRED_FORMAT2(IsSubstring, \"called at most twice\", ss2.str());\n\n  stringstream ss3;\n  AtMost(3).DescribeTo(&ss3);\n  EXPECT_PRED_FORMAT2(IsSubstring, \"called at most 3 times\", ss3.str());\n}\n\nTEST(AtMostTest, HasCorrectBounds) {\n  const Cardinality c = AtMost(2);\n  EXPECT_EQ(0, c.ConservativeLowerBound());\n  EXPECT_EQ(2, c.ConservativeUpperBound());\n}\n\n// Tests Between(m, n).\n\nTEST(BetweenTest, OnNegativeStart) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        Between(-1, 2);\n      },\n      \"The invocation lower bound must be >= 0, but is actually -1\");\n}\n\nTEST(BetweenTest, OnNegativeEnd) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        Between(1, -2);\n      },\n      \"The invocation upper bound must be >= 0, but is actually -2\");\n}\n\nTEST(BetweenTest, OnStartBiggerThanEnd) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        Between(2, 1);\n      },\n      \"The invocation upper bound (1) must be >= \"\n      \"the invocation lower bound (2)\");\n}\n\nTEST(BetweenTest, OnZeroStartAndZeroEnd) {\n  const Cardinality c = Between(0, 0);\n\n  EXPECT_TRUE(c.IsSatisfiedByCallCount(0));\n  EXPECT_TRUE(c.IsSaturatedByCallCount(0));\n\n  EXPECT_FALSE(c.IsSatisfiedByCallCount(1));\n  EXPECT_TRUE(c.IsSaturatedByCallCount(1));\n\n  stringstream ss;\n  c.DescribeTo(&ss);\n  EXPECT_PRED_FORMAT2(IsSubstring, \"never called\", ss.str());\n}\n\nTEST(BetweenTest, OnZeroStartAndNonZeroEnd) {\n  const Cardinality c = Between(0, 2);\n\n  EXPECT_TRUE(c.IsSatisfiedByCallCount(0));\n  EXPECT_FALSE(c.IsSaturatedByCallCount(0));\n\n  EXPECT_TRUE(c.IsSatisfiedByCallCount(2));\n  EXPECT_TRUE(c.IsSaturatedByCallCount(2));\n\n  EXPECT_FALSE(c.IsSatisfiedByCallCount(4));\n  EXPECT_TRUE(c.IsSaturatedByCallCount(4));\n\n  stringstream ss;\n  c.DescribeTo(&ss);\n  EXPECT_PRED_FORMAT2(IsSubstring, \"called at most twice\", ss.str());\n}\n\nTEST(BetweenTest, OnSameStartAndEnd) {\n  const Cardinality c = Between(3, 3);\n\n  EXPECT_FALSE(c.IsSatisfiedByCallCount(2));\n  EXPECT_FALSE(c.IsSaturatedByCallCount(2));\n\n  EXPECT_TRUE(c.IsSatisfiedByCallCount(3));\n  EXPECT_TRUE(c.IsSaturatedByCallCount(3));\n\n  EXPECT_FALSE(c.IsSatisfiedByCallCount(4));\n  EXPECT_TRUE(c.IsSaturatedByCallCount(4));\n\n  stringstream ss;\n  c.DescribeTo(&ss);\n  EXPECT_PRED_FORMAT2(IsSubstring, \"called 3 times\", ss.str());\n}\n\nTEST(BetweenTest, OnDifferentStartAndEnd) {\n  const Cardinality c = Between(3, 5);\n\n  EXPECT_FALSE(c.IsSatisfiedByCallCount(2));\n  EXPECT_FALSE(c.IsSaturatedByCallCount(2));\n\n  EXPECT_TRUE(c.IsSatisfiedByCallCount(3));\n  EXPECT_FALSE(c.IsSaturatedByCallCount(3));\n\n  EXPECT_TRUE(c.IsSatisfiedByCallCount(5));\n  EXPECT_TRUE(c.IsSaturatedByCallCount(5));\n\n  EXPECT_FALSE(c.IsSatisfiedByCallCount(6));\n  EXPECT_TRUE(c.IsSaturatedByCallCount(6));\n\n  stringstream ss;\n  c.DescribeTo(&ss);\n  EXPECT_PRED_FORMAT2(IsSubstring, \"called between 3 and 5 times\", ss.str());\n}\n\nTEST(BetweenTest, HasCorrectBounds) {\n  const Cardinality c = Between(3, 5);\n  EXPECT_EQ(3, c.ConservativeLowerBound());\n  EXPECT_EQ(5, c.ConservativeUpperBound());\n}\n\n// Tests Exactly(n).\n\nTEST(ExactlyTest, OnNegativeNumber) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        Exactly(-1);\n      },\n      \"The invocation lower bound must be >= 0\");\n}\n\nTEST(ExactlyTest, OnZero) {\n  const Cardinality c = Exactly(0);\n  EXPECT_TRUE(c.IsSatisfiedByCallCount(0));\n  EXPECT_TRUE(c.IsSaturatedByCallCount(0));\n\n  EXPECT_FALSE(c.IsSatisfiedByCallCount(1));\n  EXPECT_TRUE(c.IsSaturatedByCallCount(1));\n\n  stringstream ss;\n  c.DescribeTo(&ss);\n  EXPECT_PRED_FORMAT2(IsSubstring, \"never called\", ss.str());\n}\n\nTEST(ExactlyTest, OnPositiveNumber) {\n  const Cardinality c = Exactly(2);\n  EXPECT_FALSE(c.IsSatisfiedByCallCount(0));\n  EXPECT_FALSE(c.IsSaturatedByCallCount(0));\n\n  EXPECT_TRUE(c.IsSatisfiedByCallCount(2));\n  EXPECT_TRUE(c.IsSaturatedByCallCount(2));\n\n  stringstream ss1;\n  Exactly(1).DescribeTo(&ss1);\n  EXPECT_PRED_FORMAT2(IsSubstring, \"called once\", ss1.str());\n\n  stringstream ss2;\n  c.DescribeTo(&ss2);\n  EXPECT_PRED_FORMAT2(IsSubstring, \"called twice\", ss2.str());\n\n  stringstream ss3;\n  Exactly(3).DescribeTo(&ss3);\n  EXPECT_PRED_FORMAT2(IsSubstring, \"called 3 times\", ss3.str());\n}\n\nTEST(ExactlyTest, HasCorrectBounds) {\n  const Cardinality c = Exactly(3);\n  EXPECT_EQ(3, c.ConservativeLowerBound());\n  EXPECT_EQ(3, c.ConservativeUpperBound());\n}\n\n// Tests that a user can make their own cardinality by implementing\n// CardinalityInterface and calling MakeCardinality().\n\nclass EvenCardinality : public CardinalityInterface {\n public:\n  // Returns true if and only if call_count calls will satisfy this\n  // cardinality.\n  bool IsSatisfiedByCallCount(int call_count) const override {\n    return (call_count % 2 == 0);\n  }\n\n  // Returns true if and only if call_count calls will saturate this\n  // cardinality.\n  bool IsSaturatedByCallCount(int /* call_count */) const override {\n    return false;\n  }\n\n  // Describes self to an ostream.\n  void DescribeTo(::std::ostream* ss) const override {\n    *ss << \"called even number of times\";\n  }\n};\n\nTEST(MakeCardinalityTest, ConstructsCardinalityFromInterface) {\n  const Cardinality c = MakeCardinality(new EvenCardinality);\n\n  EXPECT_TRUE(c.IsSatisfiedByCallCount(2));\n  EXPECT_FALSE(c.IsSatisfiedByCallCount(3));\n\n  EXPECT_FALSE(c.IsSaturatedByCallCount(10000));\n\n  stringstream ss;\n  c.DescribeTo(&ss);\n  EXPECT_EQ(\"called even number of times\", ss.str());\n}\n\n}  // Unnamed namespace\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock-function-mocker_test.cc",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Silence C4503 (decorated name length exceeded) for MSVC.\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 4503)\n#endif\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file tests the function mocker classes.\n#include \"gmock/gmock-function-mocker.h\"\n\n#if GTEST_OS_WINDOWS\n// MSDN says the header file to be included for STDMETHOD is BaseTyps.h but\n// we are getting compiler errors if we use basetyps.h, hence including\n// objbase.h for definition of STDMETHOD.\n#include <objbase.h>\n#endif  // GTEST_OS_WINDOWS\n\n#include <functional>\n#include <map>\n#include <string>\n#include <type_traits>\n\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n\nnamespace testing {\nnamespace gmock_function_mocker_test {\n\nusing testing::_;\nusing testing::A;\nusing testing::An;\nusing testing::AnyNumber;\nusing testing::Const;\nusing testing::DoDefault;\nusing testing::Eq;\nusing testing::Lt;\nusing testing::MockFunction;\nusing testing::Ref;\nusing testing::Return;\nusing testing::ReturnRef;\nusing testing::TypedEq;\n\ntemplate <typename T>\nclass TemplatedCopyable {\n public:\n  TemplatedCopyable() {}\n\n  template <typename U>\n  TemplatedCopyable(const U& other) {}  // NOLINT\n};\n\nclass FooInterface {\n public:\n  virtual ~FooInterface() {}\n\n  virtual void VoidReturning(int x) = 0;\n\n  virtual int Nullary() = 0;\n  virtual bool Unary(int x) = 0;\n  virtual long Binary(short x, int y) = 0;                     // NOLINT\n  virtual int Decimal(bool b, char c, short d, int e, long f,  // NOLINT\n                      float g, double h, unsigned i, char* j,\n                      const std::string& k) = 0;\n\n  virtual bool TakesNonConstReference(int& n) = 0;  // NOLINT\n  virtual std::string TakesConstReference(const int& n) = 0;\n  virtual bool TakesConst(const int x) = 0;\n\n  virtual int OverloadedOnArgumentNumber() = 0;\n  virtual int OverloadedOnArgumentNumber(int n) = 0;\n\n  virtual int OverloadedOnArgumentType(int n) = 0;\n  virtual char OverloadedOnArgumentType(char c) = 0;\n\n  virtual int OverloadedOnConstness() = 0;\n  virtual char OverloadedOnConstness() const = 0;\n\n  virtual int TypeWithHole(int (*func)()) = 0;\n  virtual int TypeWithComma(const std::map<int, std::string>& a_map) = 0;\n  virtual int TypeWithTemplatedCopyCtor(const TemplatedCopyable<int>&) = 0;\n\n  virtual int (*ReturnsFunctionPointer1(int))(bool) = 0;\n  using fn_ptr = int (*)(bool);\n  virtual fn_ptr ReturnsFunctionPointer2(int) = 0;\n\n  virtual int RefQualifiedConstRef() const& = 0;\n  virtual int RefQualifiedConstRefRef() const&& = 0;\n  virtual int RefQualifiedRef() & = 0;\n  virtual int RefQualifiedRefRef() && = 0;\n\n  virtual int RefQualifiedOverloaded() const& = 0;\n  virtual int RefQualifiedOverloaded() const&& = 0;\n  virtual int RefQualifiedOverloaded() & = 0;\n  virtual int RefQualifiedOverloaded() && = 0;\n\n#if GTEST_OS_WINDOWS\n  STDMETHOD_(int, CTNullary)() = 0;\n  STDMETHOD_(bool, CTUnary)(int x) = 0;\n  STDMETHOD_(int, CTDecimal)\n  (bool b, char c, short d, int e, long f,  // NOLINT\n   float g, double h, unsigned i, char* j, const std::string& k) = 0;\n  STDMETHOD_(char, CTConst)(int x) const = 0;\n#endif  // GTEST_OS_WINDOWS\n};\n\n// Const qualifiers on arguments were once (incorrectly) considered\n// significant in determining whether two virtual functions had the same\n// signature. This was fixed in Visual Studio 2008. However, the compiler\n// still emits a warning that alerts about this change in behavior.\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 4373)\n#endif\nclass MockFoo : public FooInterface {\n public:\n  MockFoo() {}\n\n  // Makes sure that a mock function parameter can be named.\n  MOCK_METHOD(void, VoidReturning, (int n));  // NOLINT\n\n  MOCK_METHOD(int, Nullary, ());  // NOLINT\n\n  // Makes sure that a mock function parameter can be unnamed.\n  MOCK_METHOD(bool, Unary, (int));          // NOLINT\n  MOCK_METHOD(long, Binary, (short, int));  // NOLINT\n  MOCK_METHOD(int, Decimal,\n              (bool, char, short, int, long, float,  // NOLINT\n               double, unsigned, char*, const std::string& str),\n              (override));\n\n  MOCK_METHOD(bool, TakesNonConstReference, (int&));  // NOLINT\n  MOCK_METHOD(std::string, TakesConstReference, (const int&));\n  MOCK_METHOD(bool, TakesConst, (const int));  // NOLINT\n\n  // Tests that the function return type can contain unprotected comma.\n  MOCK_METHOD((std::map<int, std::string>), ReturnTypeWithComma, (), ());\n  MOCK_METHOD((std::map<int, std::string>), ReturnTypeWithComma, (int),\n              (const));  // NOLINT\n\n  MOCK_METHOD(int, OverloadedOnArgumentNumber, ());     // NOLINT\n  MOCK_METHOD(int, OverloadedOnArgumentNumber, (int));  // NOLINT\n\n  MOCK_METHOD(int, OverloadedOnArgumentType, (int));    // NOLINT\n  MOCK_METHOD(char, OverloadedOnArgumentType, (char));  // NOLINT\n\n  MOCK_METHOD(int, OverloadedOnConstness, (), (override));          // NOLINT\n  MOCK_METHOD(char, OverloadedOnConstness, (), (override, const));  // NOLINT\n\n  MOCK_METHOD(int, TypeWithHole, (int (*)()), ());  // NOLINT\n  MOCK_METHOD(int, TypeWithComma, ((const std::map<int, std::string>&)));\n  MOCK_METHOD(int, TypeWithTemplatedCopyCtor,\n              (const TemplatedCopyable<int>&));  // NOLINT\n\n  MOCK_METHOD(int (*)(bool), ReturnsFunctionPointer1, (int), ());\n  MOCK_METHOD(fn_ptr, ReturnsFunctionPointer2, (int), ());\n\n#if GTEST_OS_WINDOWS\n  MOCK_METHOD(int, CTNullary, (), (Calltype(STDMETHODCALLTYPE)));\n  MOCK_METHOD(bool, CTUnary, (int), (Calltype(STDMETHODCALLTYPE)));\n  MOCK_METHOD(int, CTDecimal,\n              (bool b, char c, short d, int e, long f, float g, double h,\n               unsigned i, char* j, const std::string& k),\n              (Calltype(STDMETHODCALLTYPE)));\n  MOCK_METHOD(char, CTConst, (int), (const, Calltype(STDMETHODCALLTYPE)));\n  MOCK_METHOD((std::map<int, std::string>), CTReturnTypeWithComma, (),\n              (Calltype(STDMETHODCALLTYPE)));\n#endif  // GTEST_OS_WINDOWS\n\n  // Test reference qualified functions.\n  MOCK_METHOD(int, RefQualifiedConstRef, (), (const, ref(&), override));\n  MOCK_METHOD(int, RefQualifiedConstRefRef, (), (const, ref(&&), override));\n  MOCK_METHOD(int, RefQualifiedRef, (), (ref(&), override));\n  MOCK_METHOD(int, RefQualifiedRefRef, (), (ref(&&), override));\n\n  MOCK_METHOD(int, RefQualifiedOverloaded, (), (const, ref(&), override));\n  MOCK_METHOD(int, RefQualifiedOverloaded, (), (const, ref(&&), override));\n  MOCK_METHOD(int, RefQualifiedOverloaded, (), (ref(&), override));\n  MOCK_METHOD(int, RefQualifiedOverloaded, (), (ref(&&), override));\n\n private:\n  MockFoo(const MockFoo&) = delete;\n  MockFoo& operator=(const MockFoo&) = delete;\n};\n\nclass LegacyMockFoo : public FooInterface {\n public:\n  LegacyMockFoo() {}\n\n  // Makes sure that a mock function parameter can be named.\n  MOCK_METHOD1(VoidReturning, void(int n));  // NOLINT\n\n  MOCK_METHOD0(Nullary, int());  // NOLINT\n\n  // Makes sure that a mock function parameter can be unnamed.\n  MOCK_METHOD1(Unary, bool(int));                                  // NOLINT\n  MOCK_METHOD2(Binary, long(short, int));                          // NOLINT\n  MOCK_METHOD10(Decimal, int(bool, char, short, int, long, float,  // NOLINT\n                             double, unsigned, char*, const std::string& str));\n\n  MOCK_METHOD1(TakesNonConstReference, bool(int&));  // NOLINT\n  MOCK_METHOD1(TakesConstReference, std::string(const int&));\n  MOCK_METHOD1(TakesConst, bool(const int));  // NOLINT\n\n  // Tests that the function return type can contain unprotected comma.\n  MOCK_METHOD0(ReturnTypeWithComma, std::map<int, std::string>());\n  MOCK_CONST_METHOD1(ReturnTypeWithComma,\n                     std::map<int, std::string>(int));  // NOLINT\n\n  MOCK_METHOD0(OverloadedOnArgumentNumber, int());     // NOLINT\n  MOCK_METHOD1(OverloadedOnArgumentNumber, int(int));  // NOLINT\n\n  MOCK_METHOD1(OverloadedOnArgumentType, int(int));    // NOLINT\n  MOCK_METHOD1(OverloadedOnArgumentType, char(char));  // NOLINT\n\n  MOCK_METHOD0(OverloadedOnConstness, int());         // NOLINT\n  MOCK_CONST_METHOD0(OverloadedOnConstness, char());  // NOLINT\n\n  MOCK_METHOD1(TypeWithHole, int(int (*)()));  // NOLINT\n  MOCK_METHOD1(TypeWithComma,\n               int(const std::map<int, std::string>&));  // NOLINT\n  MOCK_METHOD1(TypeWithTemplatedCopyCtor,\n               int(const TemplatedCopyable<int>&));  // NOLINT\n\n  MOCK_METHOD1(ReturnsFunctionPointer1, int (*(int))(bool));\n  MOCK_METHOD1(ReturnsFunctionPointer2, fn_ptr(int));\n\n#if GTEST_OS_WINDOWS\n  MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTNullary, int());\n  MOCK_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTUnary, bool(int));  // NOLINT\n  MOCK_METHOD10_WITH_CALLTYPE(STDMETHODCALLTYPE, CTDecimal,\n                              int(bool b, char c, short d, int e,  // NOLINT\n                                  long f, float g, double h,       // NOLINT\n                                  unsigned i, char* j, const std::string& k));\n  MOCK_CONST_METHOD1_WITH_CALLTYPE(STDMETHODCALLTYPE, CTConst,\n                                   char(int));  // NOLINT\n\n  // Tests that the function return type can contain unprotected comma.\n  MOCK_METHOD0_WITH_CALLTYPE(STDMETHODCALLTYPE, CTReturnTypeWithComma,\n                             std::map<int, std::string>());\n#endif  // GTEST_OS_WINDOWS\n\n  // We can't mock these with the old macros, but we need to define them to make\n  // it concrete.\n  int RefQualifiedConstRef() const& override { return 0; }\n  int RefQualifiedConstRefRef() const&& override { return 0; }\n  int RefQualifiedRef() & override { return 0; }\n  int RefQualifiedRefRef() && override { return 0; }\n  int RefQualifiedOverloaded() const& override { return 0; }\n  int RefQualifiedOverloaded() const&& override { return 0; }\n  int RefQualifiedOverloaded() & override { return 0; }\n  int RefQualifiedOverloaded() && override { return 0; }\n\n private:\n  LegacyMockFoo(const LegacyMockFoo&) = delete;\n  LegacyMockFoo& operator=(const LegacyMockFoo&) = delete;\n};\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\ntemplate <class T>\nclass FunctionMockerTest : public testing::Test {\n protected:\n  FunctionMockerTest() : foo_(&mock_foo_) {}\n\n  FooInterface* const foo_;\n  T mock_foo_;\n};\nusing FunctionMockerTestTypes = ::testing::Types<MockFoo, LegacyMockFoo>;\nTYPED_TEST_SUITE(FunctionMockerTest, FunctionMockerTestTypes);\n\n// Tests mocking a void-returning function.\nTYPED_TEST(FunctionMockerTest, MocksVoidFunction) {\n  EXPECT_CALL(this->mock_foo_, VoidReturning(Lt(100)));\n  this->foo_->VoidReturning(0);\n}\n\n// Tests mocking a nullary function.\nTYPED_TEST(FunctionMockerTest, MocksNullaryFunction) {\n  EXPECT_CALL(this->mock_foo_, Nullary())\n      .WillOnce(DoDefault())\n      .WillOnce(Return(1));\n\n  EXPECT_EQ(0, this->foo_->Nullary());\n  EXPECT_EQ(1, this->foo_->Nullary());\n}\n\n// Tests mocking a unary function.\nTYPED_TEST(FunctionMockerTest, MocksUnaryFunction) {\n  EXPECT_CALL(this->mock_foo_, Unary(Eq(2))).Times(2).WillOnce(Return(true));\n\n  EXPECT_TRUE(this->foo_->Unary(2));\n  EXPECT_FALSE(this->foo_->Unary(2));\n}\n\n// Tests mocking a binary function.\nTYPED_TEST(FunctionMockerTest, MocksBinaryFunction) {\n  EXPECT_CALL(this->mock_foo_, Binary(2, _)).WillOnce(Return(3));\n\n  EXPECT_EQ(3, this->foo_->Binary(2, 1));\n}\n\n// Tests mocking a decimal function.\nTYPED_TEST(FunctionMockerTest, MocksDecimalFunction) {\n  EXPECT_CALL(this->mock_foo_,\n              Decimal(true, 'a', 0, 0, 1L, A<float>(), Lt(100), 5U, NULL, \"hi\"))\n      .WillOnce(Return(5));\n\n  EXPECT_EQ(5, this->foo_->Decimal(true, 'a', 0, 0, 1, 0, 0, 5, nullptr, \"hi\"));\n}\n\n// Tests mocking a function that takes a non-const reference.\nTYPED_TEST(FunctionMockerTest, MocksFunctionWithNonConstReferenceArgument) {\n  int a = 0;\n  EXPECT_CALL(this->mock_foo_, TakesNonConstReference(Ref(a)))\n      .WillOnce(Return(true));\n\n  EXPECT_TRUE(this->foo_->TakesNonConstReference(a));\n}\n\n// Tests mocking a function that takes a const reference.\nTYPED_TEST(FunctionMockerTest, MocksFunctionWithConstReferenceArgument) {\n  int a = 0;\n  EXPECT_CALL(this->mock_foo_, TakesConstReference(Ref(a)))\n      .WillOnce(Return(\"Hello\"));\n\n  EXPECT_EQ(\"Hello\", this->foo_->TakesConstReference(a));\n}\n\n// Tests mocking a function that takes a const variable.\nTYPED_TEST(FunctionMockerTest, MocksFunctionWithConstArgument) {\n  EXPECT_CALL(this->mock_foo_, TakesConst(Lt(10))).WillOnce(DoDefault());\n\n  EXPECT_FALSE(this->foo_->TakesConst(5));\n}\n\n// Tests mocking functions overloaded on the number of arguments.\nTYPED_TEST(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentNumber) {\n  EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentNumber())\n      .WillOnce(Return(1));\n  EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentNumber(_))\n      .WillOnce(Return(2));\n\n  EXPECT_EQ(2, this->foo_->OverloadedOnArgumentNumber(1));\n  EXPECT_EQ(1, this->foo_->OverloadedOnArgumentNumber());\n}\n\n// Tests mocking functions overloaded on the types of argument.\nTYPED_TEST(FunctionMockerTest, MocksFunctionsOverloadedOnArgumentType) {\n  EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentType(An<int>()))\n      .WillOnce(Return(1));\n  EXPECT_CALL(this->mock_foo_, OverloadedOnArgumentType(TypedEq<char>('a')))\n      .WillOnce(Return('b'));\n\n  EXPECT_EQ(1, this->foo_->OverloadedOnArgumentType(0));\n  EXPECT_EQ('b', this->foo_->OverloadedOnArgumentType('a'));\n}\n\n// Tests mocking functions overloaded on the const-ness of this object.\nTYPED_TEST(FunctionMockerTest, MocksFunctionsOverloadedOnConstnessOfThis) {\n  EXPECT_CALL(this->mock_foo_, OverloadedOnConstness());\n  EXPECT_CALL(Const(this->mock_foo_), OverloadedOnConstness())\n      .WillOnce(Return('a'));\n\n  EXPECT_EQ(0, this->foo_->OverloadedOnConstness());\n  EXPECT_EQ('a', Const(*this->foo_).OverloadedOnConstness());\n}\n\nTYPED_TEST(FunctionMockerTest, MocksReturnTypeWithComma) {\n  const std::map<int, std::string> a_map;\n  EXPECT_CALL(this->mock_foo_, ReturnTypeWithComma()).WillOnce(Return(a_map));\n  EXPECT_CALL(this->mock_foo_, ReturnTypeWithComma(42)).WillOnce(Return(a_map));\n\n  EXPECT_EQ(a_map, this->mock_foo_.ReturnTypeWithComma());\n  EXPECT_EQ(a_map, this->mock_foo_.ReturnTypeWithComma(42));\n}\n\nTYPED_TEST(FunctionMockerTest, MocksTypeWithTemplatedCopyCtor) {\n  EXPECT_CALL(this->mock_foo_, TypeWithTemplatedCopyCtor(_))\n      .WillOnce(Return(true));\n  EXPECT_TRUE(this->foo_->TypeWithTemplatedCopyCtor(TemplatedCopyable<int>()));\n}\n\n#if GTEST_OS_WINDOWS\n// Tests mocking a nullary function with calltype.\nTYPED_TEST(FunctionMockerTest, MocksNullaryFunctionWithCallType) {\n  EXPECT_CALL(this->mock_foo_, CTNullary())\n      .WillOnce(Return(-1))\n      .WillOnce(Return(0));\n\n  EXPECT_EQ(-1, this->foo_->CTNullary());\n  EXPECT_EQ(0, this->foo_->CTNullary());\n}\n\n// Tests mocking a unary function with calltype.\nTYPED_TEST(FunctionMockerTest, MocksUnaryFunctionWithCallType) {\n  EXPECT_CALL(this->mock_foo_, CTUnary(Eq(2)))\n      .Times(2)\n      .WillOnce(Return(true))\n      .WillOnce(Return(false));\n\n  EXPECT_TRUE(this->foo_->CTUnary(2));\n  EXPECT_FALSE(this->foo_->CTUnary(2));\n}\n\n// Tests mocking a decimal function with calltype.\nTYPED_TEST(FunctionMockerTest, MocksDecimalFunctionWithCallType) {\n  EXPECT_CALL(this->mock_foo_, CTDecimal(true, 'a', 0, 0, 1L, A<float>(),\n                                         Lt(100), 5U, NULL, \"hi\"))\n      .WillOnce(Return(10));\n\n  EXPECT_EQ(10, this->foo_->CTDecimal(true, 'a', 0, 0, 1, 0, 0, 5, NULL, \"hi\"));\n}\n\n// Tests mocking functions overloaded on the const-ness of this object.\nTYPED_TEST(FunctionMockerTest, MocksFunctionsConstFunctionWithCallType) {\n  EXPECT_CALL(Const(this->mock_foo_), CTConst(_)).WillOnce(Return('a'));\n\n  EXPECT_EQ('a', Const(*this->foo_).CTConst(0));\n}\n\nTYPED_TEST(FunctionMockerTest, MocksReturnTypeWithCommaAndCallType) {\n  const std::map<int, std::string> a_map;\n  EXPECT_CALL(this->mock_foo_, CTReturnTypeWithComma()).WillOnce(Return(a_map));\n\n  EXPECT_EQ(a_map, this->mock_foo_.CTReturnTypeWithComma());\n}\n\n#endif  // GTEST_OS_WINDOWS\n\nTEST(FunctionMockerTest, RefQualified) {\n  MockFoo mock_foo;\n\n  EXPECT_CALL(mock_foo, RefQualifiedConstRef).WillOnce(Return(1));\n  EXPECT_CALL(std::move(mock_foo),  // NOLINT\n              RefQualifiedConstRefRef)\n      .WillOnce(Return(2));\n  EXPECT_CALL(mock_foo, RefQualifiedRef).WillOnce(Return(3));\n  EXPECT_CALL(std::move(mock_foo),  // NOLINT\n              RefQualifiedRefRef)\n      .WillOnce(Return(4));\n\n  EXPECT_CALL(static_cast<const MockFoo&>(mock_foo), RefQualifiedOverloaded())\n      .WillOnce(Return(5));\n  EXPECT_CALL(static_cast<const MockFoo&&>(mock_foo), RefQualifiedOverloaded())\n      .WillOnce(Return(6));\n  EXPECT_CALL(static_cast<MockFoo&>(mock_foo), RefQualifiedOverloaded())\n      .WillOnce(Return(7));\n  EXPECT_CALL(static_cast<MockFoo&&>(mock_foo), RefQualifiedOverloaded())\n      .WillOnce(Return(8));\n\n  EXPECT_EQ(mock_foo.RefQualifiedConstRef(), 1);\n  EXPECT_EQ(std::move(mock_foo).RefQualifiedConstRefRef(), 2);  // NOLINT\n  EXPECT_EQ(mock_foo.RefQualifiedRef(), 3);\n  EXPECT_EQ(std::move(mock_foo).RefQualifiedRefRef(), 4);  // NOLINT\n\n  EXPECT_EQ(std::cref(mock_foo).get().RefQualifiedOverloaded(), 5);\n  EXPECT_EQ(std::move(std::cref(mock_foo).get())  // NOLINT\n                .RefQualifiedOverloaded(),\n            6);\n  EXPECT_EQ(mock_foo.RefQualifiedOverloaded(), 7);\n  EXPECT_EQ(std::move(mock_foo).RefQualifiedOverloaded(), 8);  // NOLINT\n}\n\nclass MockB {\n public:\n  MockB() {}\n\n  MOCK_METHOD(void, DoB, ());\n\n private:\n  MockB(const MockB&) = delete;\n  MockB& operator=(const MockB&) = delete;\n};\n\nclass LegacyMockB {\n public:\n  LegacyMockB() {}\n\n  MOCK_METHOD0(DoB, void());\n\n private:\n  LegacyMockB(const LegacyMockB&) = delete;\n  LegacyMockB& operator=(const LegacyMockB&) = delete;\n};\n\ntemplate <typename T>\nclass ExpectCallTest : public ::testing::Test {};\nusing ExpectCallTestTypes = ::testing::Types<MockB, LegacyMockB>;\nTYPED_TEST_SUITE(ExpectCallTest, ExpectCallTestTypes);\n\n// Tests that functions with no EXPECT_CALL() rules can be called any\n// number of times.\nTYPED_TEST(ExpectCallTest, UnmentionedFunctionCanBeCalledAnyNumberOfTimes) {\n  { TypeParam b; }\n\n  {\n    TypeParam b;\n    b.DoB();\n  }\n\n  {\n    TypeParam b;\n    b.DoB();\n    b.DoB();\n  }\n}\n\n// Tests mocking template interfaces.\n\ntemplate <typename T>\nclass StackInterface {\n public:\n  virtual ~StackInterface() {}\n\n  // Template parameter appears in function parameter.\n  virtual void Push(const T& value) = 0;\n  virtual void Pop() = 0;\n  virtual int GetSize() const = 0;\n  // Template parameter appears in function return type.\n  virtual const T& GetTop() const = 0;\n};\n\ntemplate <typename T>\nclass MockStack : public StackInterface<T> {\n public:\n  MockStack() {}\n\n  MOCK_METHOD(void, Push, (const T& elem), ());\n  MOCK_METHOD(void, Pop, (), (final));\n  MOCK_METHOD(int, GetSize, (), (const, override));\n  MOCK_METHOD(const T&, GetTop, (), (const));\n\n  // Tests that the function return type can contain unprotected comma.\n  MOCK_METHOD((std::map<int, int>), ReturnTypeWithComma, (), ());\n  MOCK_METHOD((std::map<int, int>), ReturnTypeWithComma, (int), (const));\n\n private:\n  MockStack(const MockStack&) = delete;\n  MockStack& operator=(const MockStack&) = delete;\n};\n\ntemplate <typename T>\nclass LegacyMockStack : public StackInterface<T> {\n public:\n  LegacyMockStack() {}\n\n  MOCK_METHOD1_T(Push, void(const T& elem));\n  MOCK_METHOD0_T(Pop, void());\n  MOCK_CONST_METHOD0_T(GetSize, int());  // NOLINT\n  MOCK_CONST_METHOD0_T(GetTop, const T&());\n\n  // Tests that the function return type can contain unprotected comma.\n  MOCK_METHOD0_T(ReturnTypeWithComma, std::map<int, int>());\n  MOCK_CONST_METHOD1_T(ReturnTypeWithComma, std::map<int, int>(int));  // NOLINT\n\n private:\n  LegacyMockStack(const LegacyMockStack&) = delete;\n  LegacyMockStack& operator=(const LegacyMockStack&) = delete;\n};\n\ntemplate <typename T>\nclass TemplateMockTest : public ::testing::Test {};\nusing TemplateMockTestTypes =\n    ::testing::Types<MockStack<int>, LegacyMockStack<int>>;\nTYPED_TEST_SUITE(TemplateMockTest, TemplateMockTestTypes);\n\n// Tests that template mock works.\nTYPED_TEST(TemplateMockTest, Works) {\n  TypeParam mock;\n\n  EXPECT_CALL(mock, GetSize())\n      .WillOnce(Return(0))\n      .WillOnce(Return(1))\n      .WillOnce(Return(0));\n  EXPECT_CALL(mock, Push(_));\n  int n = 5;\n  EXPECT_CALL(mock, GetTop()).WillOnce(ReturnRef(n));\n  EXPECT_CALL(mock, Pop()).Times(AnyNumber());\n\n  EXPECT_EQ(0, mock.GetSize());\n  mock.Push(5);\n  EXPECT_EQ(1, mock.GetSize());\n  EXPECT_EQ(5, mock.GetTop());\n  mock.Pop();\n  EXPECT_EQ(0, mock.GetSize());\n}\n\nTYPED_TEST(TemplateMockTest, MethodWithCommaInReturnTypeWorks) {\n  TypeParam mock;\n\n  const std::map<int, int> a_map;\n  EXPECT_CALL(mock, ReturnTypeWithComma()).WillOnce(Return(a_map));\n  EXPECT_CALL(mock, ReturnTypeWithComma(1)).WillOnce(Return(a_map));\n\n  EXPECT_EQ(a_map, mock.ReturnTypeWithComma());\n  EXPECT_EQ(a_map, mock.ReturnTypeWithComma(1));\n}\n\n#if GTEST_OS_WINDOWS\n// Tests mocking template interfaces with calltype.\n\ntemplate <typename T>\nclass StackInterfaceWithCallType {\n public:\n  virtual ~StackInterfaceWithCallType() {}\n\n  // Template parameter appears in function parameter.\n  STDMETHOD_(void, Push)(const T& value) = 0;\n  STDMETHOD_(void, Pop)() = 0;\n  STDMETHOD_(int, GetSize)() const = 0;\n  // Template parameter appears in function return type.\n  STDMETHOD_(const T&, GetTop)() const = 0;\n};\n\ntemplate <typename T>\nclass MockStackWithCallType : public StackInterfaceWithCallType<T> {\n public:\n  MockStackWithCallType() {}\n\n  MOCK_METHOD(void, Push, (const T& elem),\n              (Calltype(STDMETHODCALLTYPE), override));\n  MOCK_METHOD(void, Pop, (), (Calltype(STDMETHODCALLTYPE), override));\n  MOCK_METHOD(int, GetSize, (), (Calltype(STDMETHODCALLTYPE), override, const));\n  MOCK_METHOD(const T&, GetTop, (),\n              (Calltype(STDMETHODCALLTYPE), override, const));\n\n private:\n  MockStackWithCallType(const MockStackWithCallType&) = delete;\n  MockStackWithCallType& operator=(const MockStackWithCallType&) = delete;\n};\n\ntemplate <typename T>\nclass LegacyMockStackWithCallType : public StackInterfaceWithCallType<T> {\n public:\n  LegacyMockStackWithCallType() {}\n\n  MOCK_METHOD1_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Push, void(const T& elem));\n  MOCK_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, Pop, void());\n  MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetSize, int());\n  MOCK_CONST_METHOD0_T_WITH_CALLTYPE(STDMETHODCALLTYPE, GetTop, const T&());\n\n private:\n  LegacyMockStackWithCallType(const LegacyMockStackWithCallType&) = delete;\n  LegacyMockStackWithCallType& operator=(const LegacyMockStackWithCallType&) =\n      delete;\n};\n\ntemplate <typename T>\nclass TemplateMockTestWithCallType : public ::testing::Test {};\nusing TemplateMockTestWithCallTypeTypes =\n    ::testing::Types<MockStackWithCallType<int>,\n                     LegacyMockStackWithCallType<int>>;\nTYPED_TEST_SUITE(TemplateMockTestWithCallType,\n                 TemplateMockTestWithCallTypeTypes);\n\n// Tests that template mock with calltype works.\nTYPED_TEST(TemplateMockTestWithCallType, Works) {\n  TypeParam mock;\n\n  EXPECT_CALL(mock, GetSize())\n      .WillOnce(Return(0))\n      .WillOnce(Return(1))\n      .WillOnce(Return(0));\n  EXPECT_CALL(mock, Push(_));\n  int n = 5;\n  EXPECT_CALL(mock, GetTop()).WillOnce(ReturnRef(n));\n  EXPECT_CALL(mock, Pop()).Times(AnyNumber());\n\n  EXPECT_EQ(0, mock.GetSize());\n  mock.Push(5);\n  EXPECT_EQ(1, mock.GetSize());\n  EXPECT_EQ(5, mock.GetTop());\n  mock.Pop();\n  EXPECT_EQ(0, mock.GetSize());\n}\n#endif  // GTEST_OS_WINDOWS\n\n#define MY_MOCK_METHODS1_                       \\\n  MOCK_METHOD(void, Overloaded, ());            \\\n  MOCK_METHOD(int, Overloaded, (int), (const)); \\\n  MOCK_METHOD(bool, Overloaded, (bool f, int n))\n\n#define LEGACY_MY_MOCK_METHODS1_              \\\n  MOCK_METHOD0(Overloaded, void());           \\\n  MOCK_CONST_METHOD1(Overloaded, int(int n)); \\\n  MOCK_METHOD2(Overloaded, bool(bool f, int n))\n\nclass MockOverloadedOnArgNumber {\n public:\n  MockOverloadedOnArgNumber() {}\n\n  MY_MOCK_METHODS1_;\n\n private:\n  MockOverloadedOnArgNumber(const MockOverloadedOnArgNumber&) = delete;\n  MockOverloadedOnArgNumber& operator=(const MockOverloadedOnArgNumber&) =\n      delete;\n};\n\nclass LegacyMockOverloadedOnArgNumber {\n public:\n  LegacyMockOverloadedOnArgNumber() {}\n\n  LEGACY_MY_MOCK_METHODS1_;\n\n private:\n  LegacyMockOverloadedOnArgNumber(const LegacyMockOverloadedOnArgNumber&) =\n      delete;\n  LegacyMockOverloadedOnArgNumber& operator=(\n      const LegacyMockOverloadedOnArgNumber&) = delete;\n};\n\ntemplate <typename T>\nclass OverloadedMockMethodTest : public ::testing::Test {};\nusing OverloadedMockMethodTestTypes =\n    ::testing::Types<MockOverloadedOnArgNumber,\n                     LegacyMockOverloadedOnArgNumber>;\nTYPED_TEST_SUITE(OverloadedMockMethodTest, OverloadedMockMethodTestTypes);\n\nTYPED_TEST(OverloadedMockMethodTest, CanOverloadOnArgNumberInMacroBody) {\n  TypeParam mock;\n  EXPECT_CALL(mock, Overloaded());\n  EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2));\n  EXPECT_CALL(mock, Overloaded(true, 1)).WillOnce(Return(true));\n\n  mock.Overloaded();\n  EXPECT_EQ(2, mock.Overloaded(1));\n  EXPECT_TRUE(mock.Overloaded(true, 1));\n}\n\n#define MY_MOCK_METHODS2_                     \\\n  MOCK_CONST_METHOD1(Overloaded, int(int n)); \\\n  MOCK_METHOD1(Overloaded, int(int n))\n\nclass MockOverloadedOnConstness {\n public:\n  MockOverloadedOnConstness() {}\n\n  MY_MOCK_METHODS2_;\n\n private:\n  MockOverloadedOnConstness(const MockOverloadedOnConstness&) = delete;\n  MockOverloadedOnConstness& operator=(const MockOverloadedOnConstness&) =\n      delete;\n};\n\nTEST(MockMethodOverloadedMockMethodTest, CanOverloadOnConstnessInMacroBody) {\n  MockOverloadedOnConstness mock;\n  const MockOverloadedOnConstness* const_mock = &mock;\n  EXPECT_CALL(mock, Overloaded(1)).WillOnce(Return(2));\n  EXPECT_CALL(*const_mock, Overloaded(1)).WillOnce(Return(3));\n\n  EXPECT_EQ(2, mock.Overloaded(1));\n  EXPECT_EQ(3, const_mock->Overloaded(1));\n}\n\nTEST(MockMethodMockFunctionTest, WorksForVoidNullary) {\n  MockFunction<void()> foo;\n  EXPECT_CALL(foo, Call());\n  foo.Call();\n}\n\nTEST(MockMethodMockFunctionTest, WorksForNonVoidNullary) {\n  MockFunction<int()> foo;\n  EXPECT_CALL(foo, Call()).WillOnce(Return(1)).WillOnce(Return(2));\n  EXPECT_EQ(1, foo.Call());\n  EXPECT_EQ(2, foo.Call());\n}\n\nTEST(MockMethodMockFunctionTest, WorksForVoidUnary) {\n  MockFunction<void(int)> foo;\n  EXPECT_CALL(foo, Call(1));\n  foo.Call(1);\n}\n\nTEST(MockMethodMockFunctionTest, WorksForNonVoidBinary) {\n  MockFunction<int(bool, int)> foo;\n  EXPECT_CALL(foo, Call(false, 42)).WillOnce(Return(1)).WillOnce(Return(2));\n  EXPECT_CALL(foo, Call(true, Ge(100))).WillOnce(Return(3));\n  EXPECT_EQ(1, foo.Call(false, 42));\n  EXPECT_EQ(2, foo.Call(false, 42));\n  EXPECT_EQ(3, foo.Call(true, 120));\n}\n\nTEST(MockMethodMockFunctionTest, WorksFor10Arguments) {\n  MockFunction<int(bool a0, char a1, int a2, int a3, int a4, int a5, int a6,\n                   char a7, int a8, bool a9)>\n      foo;\n  EXPECT_CALL(foo, Call(_, 'a', _, _, _, _, _, _, _, _))\n      .WillOnce(Return(1))\n      .WillOnce(Return(2));\n  EXPECT_EQ(1, foo.Call(false, 'a', 0, 0, 0, 0, 0, 'b', 0, true));\n  EXPECT_EQ(2, foo.Call(true, 'a', 0, 0, 0, 0, 0, 'b', 1, false));\n}\n\nTEST(MockMethodMockFunctionTest, AsStdFunction) {\n  MockFunction<int(int)> foo;\n  auto call = [](const std::function<int(int)>& f, int i) { return f(i); };\n  EXPECT_CALL(foo, Call(1)).WillOnce(Return(-1));\n  EXPECT_CALL(foo, Call(2)).WillOnce(Return(-2));\n  EXPECT_EQ(-1, call(foo.AsStdFunction(), 1));\n  EXPECT_EQ(-2, call(foo.AsStdFunction(), 2));\n}\n\nTEST(MockMethodMockFunctionTest, AsStdFunctionReturnsReference) {\n  MockFunction<int&()> foo;\n  int value = 1;\n  EXPECT_CALL(foo, Call()).WillOnce(ReturnRef(value));\n  int& ref = foo.AsStdFunction()();\n  EXPECT_EQ(1, ref);\n  value = 2;\n  EXPECT_EQ(2, ref);\n}\n\nTEST(MockMethodMockFunctionTest, AsStdFunctionWithReferenceParameter) {\n  MockFunction<int(int&)> foo;\n  auto call = [](const std::function<int(int&)>& f, int& i) { return f(i); };\n  int i = 42;\n  EXPECT_CALL(foo, Call(i)).WillOnce(Return(-1));\n  EXPECT_EQ(-1, call(foo.AsStdFunction(), i));\n}\n\nnamespace {\n\ntemplate <typename Expected, typename F>\nstatic constexpr bool IsMockFunctionTemplateArgumentDeducedTo(\n    const internal::MockFunction<F>&) {\n  return std::is_same<F, Expected>::value;\n}\n\n}  // namespace\n\ntemplate <typename F>\nclass MockMethodMockFunctionSignatureTest : public Test {};\n\nusing MockMethodMockFunctionSignatureTypes =\n    Types<void(), int(), void(int), int(int), int(bool, int),\n          int(bool, char, int, int, int, int, int, char, int, bool)>;\nTYPED_TEST_SUITE(MockMethodMockFunctionSignatureTest,\n                 MockMethodMockFunctionSignatureTypes);\n\nTYPED_TEST(MockMethodMockFunctionSignatureTest,\n           IsMockFunctionTemplateArgumentDeducedForRawSignature) {\n  using Argument = TypeParam;\n  MockFunction<Argument> foo;\n  EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<TypeParam>(foo));\n}\n\nTYPED_TEST(MockMethodMockFunctionSignatureTest,\n           IsMockFunctionTemplateArgumentDeducedForStdFunction) {\n  using Argument = std::function<TypeParam>;\n  MockFunction<Argument> foo;\n  EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<TypeParam>(foo));\n}\n\nTYPED_TEST(\n    MockMethodMockFunctionSignatureTest,\n    IsMockFunctionCallMethodSignatureTheSameForRawSignatureAndStdFunction) {\n  using ForRawSignature = decltype(&MockFunction<TypeParam>::Call);\n  using ForStdFunction =\n      decltype(&MockFunction<std::function<TypeParam>>::Call);\n  EXPECT_TRUE((std::is_same<ForRawSignature, ForStdFunction>::value));\n}\n\ntemplate <typename F>\nstruct AlternateCallable {};\n\nTYPED_TEST(MockMethodMockFunctionSignatureTest,\n           IsMockFunctionTemplateArgumentDeducedForAlternateCallable) {\n  using Argument = AlternateCallable<TypeParam>;\n  MockFunction<Argument> foo;\n  EXPECT_TRUE(IsMockFunctionTemplateArgumentDeducedTo<TypeParam>(foo));\n}\n\nTYPED_TEST(MockMethodMockFunctionSignatureTest,\n           IsMockFunctionCallMethodSignatureTheSameForAlternateCallable) {\n  using ForRawSignature = decltype(&MockFunction<TypeParam>::Call);\n  using ForStdFunction =\n      decltype(&MockFunction<std::function<TypeParam>>::Call);\n  EXPECT_TRUE((std::is_same<ForRawSignature, ForStdFunction>::value));\n}\n\nstruct MockMethodSizes0 {\n  MOCK_METHOD(void, func, ());\n};\nstruct MockMethodSizes1 {\n  MOCK_METHOD(void, func, (int));\n};\nstruct MockMethodSizes2 {\n  MOCK_METHOD(void, func, (int, int));\n};\nstruct MockMethodSizes3 {\n  MOCK_METHOD(void, func, (int, int, int));\n};\nstruct MockMethodSizes4 {\n  MOCK_METHOD(void, func, (int, int, int, int));\n};\n\nstruct LegacyMockMethodSizes0 {\n  MOCK_METHOD0(func, void());\n};\nstruct LegacyMockMethodSizes1 {\n  MOCK_METHOD1(func, void(int));\n};\nstruct LegacyMockMethodSizes2 {\n  MOCK_METHOD2(func, void(int, int));\n};\nstruct LegacyMockMethodSizes3 {\n  MOCK_METHOD3(func, void(int, int, int));\n};\nstruct LegacyMockMethodSizes4 {\n  MOCK_METHOD4(func, void(int, int, int, int));\n};\n\nTEST(MockMethodMockFunctionTest, MockMethodSizeOverhead) {\n  EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes1));\n  EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes2));\n  EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes3));\n  EXPECT_EQ(sizeof(MockMethodSizes0), sizeof(MockMethodSizes4));\n\n  EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes1));\n  EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes2));\n  EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes3));\n  EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(LegacyMockMethodSizes4));\n\n  EXPECT_EQ(sizeof(LegacyMockMethodSizes0), sizeof(MockMethodSizes0));\n}\n\nvoid hasTwoParams(int, int);\nvoid MaybeThrows();\nvoid DoesntThrow() noexcept;\nstruct MockMethodNoexceptSpecifier {\n  MOCK_METHOD(void, func1, (), (noexcept));\n  MOCK_METHOD(void, func2, (), (noexcept(true)));\n  MOCK_METHOD(void, func3, (), (noexcept(false)));\n  MOCK_METHOD(void, func4, (), (noexcept(noexcept(MaybeThrows()))));\n  MOCK_METHOD(void, func5, (), (noexcept(noexcept(DoesntThrow()))));\n  MOCK_METHOD(void, func6, (), (noexcept(noexcept(DoesntThrow())), const));\n  MOCK_METHOD(void, func7, (), (const, noexcept(noexcept(DoesntThrow()))));\n  // Put commas in the noexcept expression\n  MOCK_METHOD(void, func8, (), (noexcept(noexcept(hasTwoParams(1, 2))), const));\n};\n\nTEST(MockMethodMockFunctionTest, NoexceptSpecifierPreserved) {\n  EXPECT_TRUE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func1()));\n  EXPECT_TRUE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func2()));\n  EXPECT_FALSE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func3()));\n  EXPECT_FALSE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func4()));\n  EXPECT_TRUE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func5()));\n  EXPECT_TRUE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func6()));\n  EXPECT_TRUE(noexcept(std::declval<MockMethodNoexceptSpecifier>().func7()));\n  EXPECT_EQ(noexcept(std::declval<MockMethodNoexceptSpecifier>().func8()),\n            noexcept(hasTwoParams(1, 2)));\n}\n\n}  // namespace gmock_function_mocker_test\n}  // namespace testing\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock-internal-utils_test.cc",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file tests the internal utilities.\n\n#include \"gmock/internal/gmock-internal-utils.h\"\n\n#include <stdlib.h>\n\n#include <cstdint>\n#include <map>\n#include <memory>\n#include <sstream>\n#include <string>\n#include <vector>\n\n#include \"gmock/gmock.h\"\n#include \"gmock/internal/gmock-port.h\"\n#include \"gtest/gtest-spi.h\"\n#include \"gtest/gtest.h\"\n\n// Indicates that this translation unit is part of Google Test's\n// implementation.  It must come before gtest-internal-inl.h is\n// included, or there will be a compiler error.  This trick is to\n// prevent a user from accidentally including gtest-internal-inl.h in\n// their code.\n#define GTEST_IMPLEMENTATION_ 1\n#include \"src/gtest-internal-inl.h\"\n#undef GTEST_IMPLEMENTATION_\n\n#if GTEST_OS_CYGWIN\n#include <sys/types.h>  // For ssize_t. NOLINT\n#endif\n\nnamespace proto2 {\nclass Message;\n}  // namespace proto2\n\nnamespace testing {\nnamespace internal {\n\nnamespace {\n\nTEST(JoinAsKeyValueTupleTest, JoinsEmptyTuple) {\n  EXPECT_EQ(\"\", JoinAsKeyValueTuple({}, Strings()));\n}\n\nTEST(JoinAsKeyValueTupleTest, JoinsOneTuple) {\n  EXPECT_EQ(\"(a: 1)\", JoinAsKeyValueTuple({\"a\"}, {\"1\"}));\n}\n\nTEST(JoinAsKeyValueTupleTest, JoinsTwoTuple) {\n  EXPECT_EQ(\"(a: 1, b: 2)\", JoinAsKeyValueTuple({\"a\", \"b\"}, {\"1\", \"2\"}));\n}\n\nTEST(JoinAsKeyValueTupleTest, JoinsTenTuple) {\n  EXPECT_EQ(\n      \"(a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10)\",\n      JoinAsKeyValueTuple({\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\"},\n                          {\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\"}));\n}\n\nTEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsNoWord) {\n  EXPECT_EQ(\"\", ConvertIdentifierNameToWords(\"\"));\n  EXPECT_EQ(\"\", ConvertIdentifierNameToWords(\"_\"));\n  EXPECT_EQ(\"\", ConvertIdentifierNameToWords(\"__\"));\n}\n\nTEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsDigits) {\n  EXPECT_EQ(\"1\", ConvertIdentifierNameToWords(\"_1\"));\n  EXPECT_EQ(\"2\", ConvertIdentifierNameToWords(\"2_\"));\n  EXPECT_EQ(\"34\", ConvertIdentifierNameToWords(\"_34_\"));\n  EXPECT_EQ(\"34 56\", ConvertIdentifierNameToWords(\"_34_56\"));\n}\n\nTEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContainsCamelCaseWords) {\n  EXPECT_EQ(\"a big word\", ConvertIdentifierNameToWords(\"ABigWord\"));\n  EXPECT_EQ(\"foo bar\", ConvertIdentifierNameToWords(\"FooBar\"));\n  EXPECT_EQ(\"foo\", ConvertIdentifierNameToWords(\"Foo_\"));\n  EXPECT_EQ(\"foo bar\", ConvertIdentifierNameToWords(\"_Foo_Bar_\"));\n  EXPECT_EQ(\"foo and bar\", ConvertIdentifierNameToWords(\"_Foo__And_Bar\"));\n}\n\nTEST(ConvertIdentifierNameToWordsTest, WorksWhenNameContains_SeparatedWords) {\n  EXPECT_EQ(\"foo bar\", ConvertIdentifierNameToWords(\"foo_bar\"));\n  EXPECT_EQ(\"foo\", ConvertIdentifierNameToWords(\"_foo_\"));\n  EXPECT_EQ(\"foo bar\", ConvertIdentifierNameToWords(\"_foo_bar_\"));\n  EXPECT_EQ(\"foo and bar\", ConvertIdentifierNameToWords(\"_foo__and_bar\"));\n}\n\nTEST(ConvertIdentifierNameToWordsTest, WorksWhenNameIsMixture) {\n  EXPECT_EQ(\"foo bar 123\", ConvertIdentifierNameToWords(\"Foo_bar123\"));\n  EXPECT_EQ(\"chapter 11 section 1\",\n            ConvertIdentifierNameToWords(\"_Chapter11Section_1_\"));\n}\n\nTEST(GetRawPointerTest, WorksForSmartPointers) {\n  const char* const raw_p1 = new const char('a');  // NOLINT\n  const std::unique_ptr<const char> p1(raw_p1);\n  EXPECT_EQ(raw_p1, GetRawPointer(p1));\n  double* const raw_p2 = new double(2.5);  // NOLINT\n  const std::shared_ptr<double> p2(raw_p2);\n  EXPECT_EQ(raw_p2, GetRawPointer(p2));\n}\n\nTEST(GetRawPointerTest, WorksForRawPointers) {\n  int* p = nullptr;\n  EXPECT_TRUE(nullptr == GetRawPointer(p));\n  int n = 1;\n  EXPECT_EQ(&n, GetRawPointer(&n));\n}\n\nTEST(GetRawPointerTest, WorksForStdReferenceWrapper) {\n  int n = 1;\n  EXPECT_EQ(&n, GetRawPointer(std::ref(n)));\n  EXPECT_EQ(&n, GetRawPointer(std::cref(n)));\n}\n\n// Tests KindOf<T>.\n\nclass Base {};\nclass Derived : public Base {};\n\nTEST(KindOfTest, Bool) {\n  EXPECT_EQ(kBool, GMOCK_KIND_OF_(bool));  // NOLINT\n}\n\nTEST(KindOfTest, Integer) {\n  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(char));                // NOLINT\n  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(signed char));         // NOLINT\n  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned char));       // NOLINT\n  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(short));               // NOLINT\n  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned short));      // NOLINT\n  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(int));                 // NOLINT\n  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned int));        // NOLINT\n  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long));                // NOLINT\n  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long));       // NOLINT\n  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(long long));           // NOLINT\n  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(unsigned long long));  // NOLINT\n  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(wchar_t));             // NOLINT\n  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(size_t));              // NOLINT\n#if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_CYGWIN\n  // ssize_t is not defined on Windows and possibly some other OSes.\n  EXPECT_EQ(kInteger, GMOCK_KIND_OF_(ssize_t));  // NOLINT\n#endif\n}\n\nTEST(KindOfTest, FloatingPoint) {\n  EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(float));        // NOLINT\n  EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(double));       // NOLINT\n  EXPECT_EQ(kFloatingPoint, GMOCK_KIND_OF_(long double));  // NOLINT\n}\n\nTEST(KindOfTest, Other) {\n  EXPECT_EQ(kOther, GMOCK_KIND_OF_(void*));   // NOLINT\n  EXPECT_EQ(kOther, GMOCK_KIND_OF_(char**));  // NOLINT\n  EXPECT_EQ(kOther, GMOCK_KIND_OF_(Base));    // NOLINT\n}\n\n// Tests LosslessArithmeticConvertible<T, U>.\n\nTEST(LosslessArithmeticConvertibleTest, BoolToBool) {\n  EXPECT_TRUE((LosslessArithmeticConvertible<bool, bool>::value));\n}\n\nTEST(LosslessArithmeticConvertibleTest, BoolToInteger) {\n  EXPECT_TRUE((LosslessArithmeticConvertible<bool, char>::value));\n  EXPECT_TRUE((LosslessArithmeticConvertible<bool, int>::value));\n  EXPECT_TRUE(\n      (LosslessArithmeticConvertible<bool, unsigned long>::value));  // NOLINT\n}\n\nTEST(LosslessArithmeticConvertibleTest, BoolToFloatingPoint) {\n  EXPECT_TRUE((LosslessArithmeticConvertible<bool, float>::value));\n  EXPECT_TRUE((LosslessArithmeticConvertible<bool, double>::value));\n}\n\nTEST(LosslessArithmeticConvertibleTest, IntegerToBool) {\n  EXPECT_FALSE((LosslessArithmeticConvertible<unsigned char, bool>::value));\n  EXPECT_FALSE((LosslessArithmeticConvertible<int, bool>::value));\n}\n\nTEST(LosslessArithmeticConvertibleTest, IntegerToInteger) {\n  // Unsigned => larger signed is fine.\n  EXPECT_TRUE((LosslessArithmeticConvertible<unsigned char, int>::value));\n\n  // Unsigned => larger unsigned is fine.\n  EXPECT_TRUE((LosslessArithmeticConvertible<unsigned short,\n                                             uint64_t>::value));  // NOLINT\n\n  // Signed => unsigned is not fine.\n  EXPECT_FALSE(\n      (LosslessArithmeticConvertible<short, uint64_t>::value));  // NOLINT\n  EXPECT_FALSE((LosslessArithmeticConvertible<signed char,\n                                              unsigned int>::value));  // NOLINT\n\n  // Same size and same signedness: fine too.\n  EXPECT_TRUE(\n      (LosslessArithmeticConvertible<unsigned char, unsigned char>::value));\n  EXPECT_TRUE((LosslessArithmeticConvertible<int, int>::value));\n  EXPECT_TRUE((LosslessArithmeticConvertible<wchar_t, wchar_t>::value));\n  EXPECT_TRUE((LosslessArithmeticConvertible<unsigned long,\n                                             unsigned long>::value));  // NOLINT\n\n  // Same size, different signedness: not fine.\n  EXPECT_FALSE(\n      (LosslessArithmeticConvertible<unsigned char, signed char>::value));\n  EXPECT_FALSE((LosslessArithmeticConvertible<int, unsigned int>::value));\n  EXPECT_FALSE((LosslessArithmeticConvertible<uint64_t, int64_t>::value));\n\n  // Larger size => smaller size is not fine.\n  EXPECT_FALSE((LosslessArithmeticConvertible<long, char>::value));  // NOLINT\n  EXPECT_FALSE((LosslessArithmeticConvertible<int, signed char>::value));\n  EXPECT_FALSE((LosslessArithmeticConvertible<int64_t, unsigned int>::value));\n}\n\nTEST(LosslessArithmeticConvertibleTest, IntegerToFloatingPoint) {\n  // Integers cannot be losslessly converted to floating-points, as\n  // the format of the latter is implementation-defined.\n  EXPECT_FALSE((LosslessArithmeticConvertible<char, float>::value));\n  EXPECT_FALSE((LosslessArithmeticConvertible<int, double>::value));\n  EXPECT_FALSE(\n      (LosslessArithmeticConvertible<short, long double>::value));  // NOLINT\n}\n\nTEST(LosslessArithmeticConvertibleTest, FloatingPointToBool) {\n  EXPECT_FALSE((LosslessArithmeticConvertible<float, bool>::value));\n  EXPECT_FALSE((LosslessArithmeticConvertible<double, bool>::value));\n}\n\nTEST(LosslessArithmeticConvertibleTest, FloatingPointToInteger) {\n  EXPECT_FALSE((LosslessArithmeticConvertible<float, long>::value));  // NOLINT\n  EXPECT_FALSE((LosslessArithmeticConvertible<double, int64_t>::value));\n  EXPECT_FALSE((LosslessArithmeticConvertible<long double, int>::value));\n}\n\nTEST(LosslessArithmeticConvertibleTest, FloatingPointToFloatingPoint) {\n  // Smaller size => larger size is fine.\n  EXPECT_TRUE((LosslessArithmeticConvertible<float, double>::value));\n  EXPECT_TRUE((LosslessArithmeticConvertible<float, long double>::value));\n  EXPECT_TRUE((LosslessArithmeticConvertible<double, long double>::value));\n\n  // Same size: fine.\n  EXPECT_TRUE((LosslessArithmeticConvertible<float, float>::value));\n  EXPECT_TRUE((LosslessArithmeticConvertible<double, double>::value));\n\n  // Larger size => smaller size is not fine.\n  EXPECT_FALSE((LosslessArithmeticConvertible<double, float>::value));\n  GTEST_INTENTIONAL_CONST_COND_PUSH_()\n  if (sizeof(double) == sizeof(long double)) {  // NOLINT\n    GTEST_INTENTIONAL_CONST_COND_POP_()\n    // In some implementations (e.g. MSVC), double and long double\n    // have the same size.\n    EXPECT_TRUE((LosslessArithmeticConvertible<long double, double>::value));\n  } else {\n    EXPECT_FALSE((LosslessArithmeticConvertible<long double, double>::value));\n  }\n}\n\n// Tests the TupleMatches() template function.\n\nTEST(TupleMatchesTest, WorksForSize0) {\n  std::tuple<> matchers;\n  std::tuple<> values;\n\n  EXPECT_TRUE(TupleMatches(matchers, values));\n}\n\nTEST(TupleMatchesTest, WorksForSize1) {\n  std::tuple<Matcher<int>> matchers(Eq(1));\n  std::tuple<int> values1(1), values2(2);\n\n  EXPECT_TRUE(TupleMatches(matchers, values1));\n  EXPECT_FALSE(TupleMatches(matchers, values2));\n}\n\nTEST(TupleMatchesTest, WorksForSize2) {\n  std::tuple<Matcher<int>, Matcher<char>> matchers(Eq(1), Eq('a'));\n  std::tuple<int, char> values1(1, 'a'), values2(1, 'b'), values3(2, 'a'),\n      values4(2, 'b');\n\n  EXPECT_TRUE(TupleMatches(matchers, values1));\n  EXPECT_FALSE(TupleMatches(matchers, values2));\n  EXPECT_FALSE(TupleMatches(matchers, values3));\n  EXPECT_FALSE(TupleMatches(matchers, values4));\n}\n\nTEST(TupleMatchesTest, WorksForSize5) {\n  std::tuple<Matcher<int>, Matcher<char>, Matcher<bool>,\n             Matcher<long>,  // NOLINT\n             Matcher<std::string>>\n      matchers(Eq(1), Eq('a'), Eq(true), Eq(2L), Eq(\"hi\"));\n  std::tuple<int, char, bool, long, std::string>  // NOLINT\n      values1(1, 'a', true, 2L, \"hi\"), values2(1, 'a', true, 2L, \"hello\"),\n      values3(2, 'a', true, 2L, \"hi\");\n\n  EXPECT_TRUE(TupleMatches(matchers, values1));\n  EXPECT_FALSE(TupleMatches(matchers, values2));\n  EXPECT_FALSE(TupleMatches(matchers, values3));\n}\n\n// Tests that Assert(true, ...) succeeds.\nTEST(AssertTest, SucceedsOnTrue) {\n  Assert(true, __FILE__, __LINE__, \"This should succeed.\");\n  Assert(true, __FILE__, __LINE__);  // This should succeed too.\n}\n\n// Tests that Assert(false, ...) generates a fatal failure.\nTEST(AssertTest, FailsFatallyOnFalse) {\n  EXPECT_DEATH_IF_SUPPORTED(\n      { Assert(false, __FILE__, __LINE__, \"This should fail.\"); }, \"\");\n\n  EXPECT_DEATH_IF_SUPPORTED({ Assert(false, __FILE__, __LINE__); }, \"\");\n}\n\n// Tests that Expect(true, ...) succeeds.\nTEST(ExpectTest, SucceedsOnTrue) {\n  Expect(true, __FILE__, __LINE__, \"This should succeed.\");\n  Expect(true, __FILE__, __LINE__);  // This should succeed too.\n}\n\n// Tests that Expect(false, ...) generates a non-fatal failure.\nTEST(ExpectTest, FailsNonfatallyOnFalse) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        Expect(false, __FILE__, __LINE__, \"This should fail.\");\n      },\n      \"This should fail\");\n\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        Expect(false, __FILE__, __LINE__);\n      },\n      \"Expectation failed\");\n}\n\n// Tests LogIsVisible().\n\nclass LogIsVisibleTest : public ::testing::Test {\n protected:\n  void SetUp() override { original_verbose_ = GMOCK_FLAG_GET(verbose); }\n\n  void TearDown() override { GMOCK_FLAG_SET(verbose, original_verbose_); }\n\n  std::string original_verbose_;\n};\n\nTEST_F(LogIsVisibleTest, AlwaysReturnsTrueIfVerbosityIsInfo) {\n  GMOCK_FLAG_SET(verbose, kInfoVerbosity);\n  EXPECT_TRUE(LogIsVisible(kInfo));\n  EXPECT_TRUE(LogIsVisible(kWarning));\n}\n\nTEST_F(LogIsVisibleTest, AlwaysReturnsFalseIfVerbosityIsError) {\n  GMOCK_FLAG_SET(verbose, kErrorVerbosity);\n  EXPECT_FALSE(LogIsVisible(kInfo));\n  EXPECT_FALSE(LogIsVisible(kWarning));\n}\n\nTEST_F(LogIsVisibleTest, WorksWhenVerbosityIsWarning) {\n  GMOCK_FLAG_SET(verbose, kWarningVerbosity);\n  EXPECT_FALSE(LogIsVisible(kInfo));\n  EXPECT_TRUE(LogIsVisible(kWarning));\n}\n\n#if GTEST_HAS_STREAM_REDIRECTION\n\n// Tests the Log() function.\n\n// Verifies that Log() behaves correctly for the given verbosity level\n// and log severity.\nvoid TestLogWithSeverity(const std::string& verbosity, LogSeverity severity,\n                         bool should_print) {\n  const std::string old_flag = GMOCK_FLAG_GET(verbose);\n  GMOCK_FLAG_SET(verbose, verbosity);\n  CaptureStdout();\n  Log(severity, \"Test log.\\n\", 0);\n  if (should_print) {\n    EXPECT_THAT(\n        GetCapturedStdout().c_str(),\n        ContainsRegex(severity == kWarning\n                          ? \"^\\nGMOCK WARNING:\\nTest log\\\\.\\nStack trace:\\n\"\n                          : \"^\\nTest log\\\\.\\nStack trace:\\n\"));\n  } else {\n    EXPECT_STREQ(\"\", GetCapturedStdout().c_str());\n  }\n  GMOCK_FLAG_SET(verbose, old_flag);\n}\n\n// Tests that when the stack_frames_to_skip parameter is negative,\n// Log() doesn't include the stack trace in the output.\nTEST(LogTest, NoStackTraceWhenStackFramesToSkipIsNegative) {\n  const std::string saved_flag = GMOCK_FLAG_GET(verbose);\n  GMOCK_FLAG_SET(verbose, kInfoVerbosity);\n  CaptureStdout();\n  Log(kInfo, \"Test log.\\n\", -1);\n  EXPECT_STREQ(\"\\nTest log.\\n\", GetCapturedStdout().c_str());\n  GMOCK_FLAG_SET(verbose, saved_flag);\n}\n\nstruct MockStackTraceGetter : testing::internal::OsStackTraceGetterInterface {\n  std::string CurrentStackTrace(int max_depth, int skip_count) override {\n    return (testing::Message() << max_depth << \"::\" << skip_count << \"\\n\")\n        .GetString();\n  }\n  void UponLeavingGTest() override {}\n};\n\n// Tests that in opt mode, a positive stack_frames_to_skip argument is\n// treated as 0.\nTEST(LogTest, NoSkippingStackFrameInOptMode) {\n  MockStackTraceGetter* mock_os_stack_trace_getter = new MockStackTraceGetter;\n  GetUnitTestImpl()->set_os_stack_trace_getter(mock_os_stack_trace_getter);\n\n  CaptureStdout();\n  Log(kWarning, \"Test log.\\n\", 100);\n  const std::string log = GetCapturedStdout();\n\n  std::string expected_trace =\n      (testing::Message() << GTEST_FLAG_GET(stack_trace_depth) << \"::\")\n          .GetString();\n  std::string expected_message =\n      \"\\nGMOCK WARNING:\\n\"\n      \"Test log.\\n\"\n      \"Stack trace:\\n\" +\n      expected_trace;\n  EXPECT_THAT(log, HasSubstr(expected_message));\n  int skip_count = atoi(log.substr(expected_message.size()).c_str());\n\n#if defined(NDEBUG)\n  // In opt mode, no stack frame should be skipped.\n  const int expected_skip_count = 0;\n#else\n  // In dbg mode, the stack frames should be skipped.\n  const int expected_skip_count = 100;\n#endif\n\n  // Note that each inner implementation layer will +1 the number to remove\n  // itself from the trace. This means that the value is a little higher than\n  // expected, but close enough.\n  EXPECT_THAT(skip_count,\n              AllOf(Ge(expected_skip_count), Le(expected_skip_count + 10)));\n\n  // Restores the default OS stack trace getter.\n  GetUnitTestImpl()->set_os_stack_trace_getter(nullptr);\n}\n\n// Tests that all logs are printed when the value of the\n// --gmock_verbose flag is \"info\".\nTEST(LogTest, AllLogsArePrintedWhenVerbosityIsInfo) {\n  TestLogWithSeverity(kInfoVerbosity, kInfo, true);\n  TestLogWithSeverity(kInfoVerbosity, kWarning, true);\n}\n\n// Tests that only warnings are printed when the value of the\n// --gmock_verbose flag is \"warning\".\nTEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsWarning) {\n  TestLogWithSeverity(kWarningVerbosity, kInfo, false);\n  TestLogWithSeverity(kWarningVerbosity, kWarning, true);\n}\n\n// Tests that no logs are printed when the value of the\n// --gmock_verbose flag is \"error\".\nTEST(LogTest, NoLogsArePrintedWhenVerbosityIsError) {\n  TestLogWithSeverity(kErrorVerbosity, kInfo, false);\n  TestLogWithSeverity(kErrorVerbosity, kWarning, false);\n}\n\n// Tests that only warnings are printed when the value of the\n// --gmock_verbose flag is invalid.\nTEST(LogTest, OnlyWarningsArePrintedWhenVerbosityIsInvalid) {\n  TestLogWithSeverity(\"invalid\", kInfo, false);\n  TestLogWithSeverity(\"invalid\", kWarning, true);\n}\n\n// Verifies that Log() behaves correctly for the given verbosity level\n// and log severity.\nstd::string GrabOutput(void (*logger)(), const char* verbosity) {\n  const std::string saved_flag = GMOCK_FLAG_GET(verbose);\n  GMOCK_FLAG_SET(verbose, verbosity);\n  CaptureStdout();\n  logger();\n  GMOCK_FLAG_SET(verbose, saved_flag);\n  return GetCapturedStdout();\n}\n\nclass DummyMock {\n public:\n  MOCK_METHOD0(TestMethod, void());\n  MOCK_METHOD1(TestMethodArg, void(int dummy));\n};\n\nvoid ExpectCallLogger() {\n  DummyMock mock;\n  EXPECT_CALL(mock, TestMethod());\n  mock.TestMethod();\n}\n\n// Verifies that EXPECT_CALL logs if the --gmock_verbose flag is set to \"info\".\nTEST(ExpectCallTest, LogsWhenVerbosityIsInfo) {\n  EXPECT_THAT(std::string(GrabOutput(ExpectCallLogger, kInfoVerbosity)),\n              HasSubstr(\"EXPECT_CALL(mock, TestMethod())\"));\n}\n\n// Verifies that EXPECT_CALL doesn't log\n// if the --gmock_verbose flag is set to \"warning\".\nTEST(ExpectCallTest, DoesNotLogWhenVerbosityIsWarning) {\n  EXPECT_STREQ(\"\", GrabOutput(ExpectCallLogger, kWarningVerbosity).c_str());\n}\n\n// Verifies that EXPECT_CALL doesn't log\n// if the --gmock_verbose flag is set to \"error\".\nTEST(ExpectCallTest, DoesNotLogWhenVerbosityIsError) {\n  EXPECT_STREQ(\"\", GrabOutput(ExpectCallLogger, kErrorVerbosity).c_str());\n}\n\nvoid OnCallLogger() {\n  DummyMock mock;\n  ON_CALL(mock, TestMethod());\n}\n\n// Verifies that ON_CALL logs if the --gmock_verbose flag is set to \"info\".\nTEST(OnCallTest, LogsWhenVerbosityIsInfo) {\n  EXPECT_THAT(std::string(GrabOutput(OnCallLogger, kInfoVerbosity)),\n              HasSubstr(\"ON_CALL(mock, TestMethod())\"));\n}\n\n// Verifies that ON_CALL doesn't log\n// if the --gmock_verbose flag is set to \"warning\".\nTEST(OnCallTest, DoesNotLogWhenVerbosityIsWarning) {\n  EXPECT_STREQ(\"\", GrabOutput(OnCallLogger, kWarningVerbosity).c_str());\n}\n\n// Verifies that ON_CALL doesn't log if\n// the --gmock_verbose flag is set to \"error\".\nTEST(OnCallTest, DoesNotLogWhenVerbosityIsError) {\n  EXPECT_STREQ(\"\", GrabOutput(OnCallLogger, kErrorVerbosity).c_str());\n}\n\nvoid OnCallAnyArgumentLogger() {\n  DummyMock mock;\n  ON_CALL(mock, TestMethodArg(_));\n}\n\n// Verifies that ON_CALL prints provided _ argument.\nTEST(OnCallTest, LogsAnythingArgument) {\n  EXPECT_THAT(std::string(GrabOutput(OnCallAnyArgumentLogger, kInfoVerbosity)),\n              HasSubstr(\"ON_CALL(mock, TestMethodArg(_)\"));\n}\n\n#endif  // GTEST_HAS_STREAM_REDIRECTION\n\n// Tests StlContainerView.\n\nTEST(StlContainerViewTest, WorksForStlContainer) {\n  StaticAssertTypeEq<std::vector<int>,\n                     StlContainerView<std::vector<int>>::type>();\n  StaticAssertTypeEq<const std::vector<double>&,\n                     StlContainerView<std::vector<double>>::const_reference>();\n\n  typedef std::vector<char> Chars;\n  Chars v1;\n  const Chars& v2(StlContainerView<Chars>::ConstReference(v1));\n  EXPECT_EQ(&v1, &v2);\n\n  v1.push_back('a');\n  Chars v3 = StlContainerView<Chars>::Copy(v1);\n  EXPECT_THAT(v3, Eq(v3));\n}\n\nTEST(StlContainerViewTest, WorksForStaticNativeArray) {\n  StaticAssertTypeEq<NativeArray<int>, StlContainerView<int[3]>::type>();\n  StaticAssertTypeEq<NativeArray<double>,\n                     StlContainerView<const double[4]>::type>();\n  StaticAssertTypeEq<NativeArray<char[3]>,\n                     StlContainerView<const char[2][3]>::type>();\n\n  StaticAssertTypeEq<const NativeArray<int>,\n                     StlContainerView<int[2]>::const_reference>();\n\n  int a1[3] = {0, 1, 2};\n  NativeArray<int> a2 = StlContainerView<int[3]>::ConstReference(a1);\n  EXPECT_EQ(3U, a2.size());\n  EXPECT_EQ(a1, a2.begin());\n\n  const NativeArray<int> a3 = StlContainerView<int[3]>::Copy(a1);\n  ASSERT_EQ(3U, a3.size());\n  EXPECT_EQ(0, a3.begin()[0]);\n  EXPECT_EQ(1, a3.begin()[1]);\n  EXPECT_EQ(2, a3.begin()[2]);\n\n  // Makes sure a1 and a3 aren't aliases.\n  a1[0] = 3;\n  EXPECT_EQ(0, a3.begin()[0]);\n}\n\nTEST(StlContainerViewTest, WorksForDynamicNativeArray) {\n  StaticAssertTypeEq<NativeArray<int>,\n                     StlContainerView<std::tuple<const int*, size_t>>::type>();\n  StaticAssertTypeEq<\n      NativeArray<double>,\n      StlContainerView<std::tuple<std::shared_ptr<double>, int>>::type>();\n\n  StaticAssertTypeEq<\n      const NativeArray<int>,\n      StlContainerView<std::tuple<const int*, int>>::const_reference>();\n\n  int a1[3] = {0, 1, 2};\n  const int* const p1 = a1;\n  NativeArray<int> a2 =\n      StlContainerView<std::tuple<const int*, int>>::ConstReference(\n          std::make_tuple(p1, 3));\n  EXPECT_EQ(3U, a2.size());\n  EXPECT_EQ(a1, a2.begin());\n\n  const NativeArray<int> a3 = StlContainerView<std::tuple<int*, size_t>>::Copy(\n      std::make_tuple(static_cast<int*>(a1), 3));\n  ASSERT_EQ(3U, a3.size());\n  EXPECT_EQ(0, a3.begin()[0]);\n  EXPECT_EQ(1, a3.begin()[1]);\n  EXPECT_EQ(2, a3.begin()[2]);\n\n  // Makes sure a1 and a3 aren't aliases.\n  a1[0] = 3;\n  EXPECT_EQ(0, a3.begin()[0]);\n}\n\n// Tests the Function template struct.\n\nTEST(FunctionTest, Nullary) {\n  typedef Function<int()> F;  // NOLINT\n  EXPECT_EQ(0u, F::ArgumentCount);\n  EXPECT_TRUE((std::is_same<int, F::Result>::value));\n  EXPECT_TRUE((std::is_same<std::tuple<>, F::ArgumentTuple>::value));\n  EXPECT_TRUE((std::is_same<std::tuple<>, F::ArgumentMatcherTuple>::value));\n  EXPECT_TRUE((std::is_same<void(), F::MakeResultVoid>::value));\n  EXPECT_TRUE((std::is_same<IgnoredValue(), F::MakeResultIgnoredValue>::value));\n}\n\nTEST(FunctionTest, Unary) {\n  typedef Function<int(bool)> F;  // NOLINT\n  EXPECT_EQ(1u, F::ArgumentCount);\n  EXPECT_TRUE((std::is_same<int, F::Result>::value));\n  EXPECT_TRUE((std::is_same<bool, F::Arg<0>::type>::value));\n  EXPECT_TRUE((std::is_same<std::tuple<bool>, F::ArgumentTuple>::value));\n  EXPECT_TRUE((\n      std::is_same<std::tuple<Matcher<bool>>, F::ArgumentMatcherTuple>::value));\n  EXPECT_TRUE((std::is_same<void(bool), F::MakeResultVoid>::value));  // NOLINT\n  EXPECT_TRUE((std::is_same<IgnoredValue(bool),                       // NOLINT\n                            F::MakeResultIgnoredValue>::value));\n}\n\nTEST(FunctionTest, Binary) {\n  typedef Function<int(bool, const long&)> F;  // NOLINT\n  EXPECT_EQ(2u, F::ArgumentCount);\n  EXPECT_TRUE((std::is_same<int, F::Result>::value));\n  EXPECT_TRUE((std::is_same<bool, F::Arg<0>::type>::value));\n  EXPECT_TRUE((std::is_same<const long&, F::Arg<1>::type>::value));  // NOLINT\n  EXPECT_TRUE((std::is_same<std::tuple<bool, const long&>,           // NOLINT\n                            F::ArgumentTuple>::value));\n  EXPECT_TRUE(\n      (std::is_same<std::tuple<Matcher<bool>, Matcher<const long&>>,  // NOLINT\n                    F::ArgumentMatcherTuple>::value));\n  EXPECT_TRUE((std::is_same<void(bool, const long&),  // NOLINT\n                            F::MakeResultVoid>::value));\n  EXPECT_TRUE((std::is_same<IgnoredValue(bool, const long&),  // NOLINT\n                            F::MakeResultIgnoredValue>::value));\n}\n\nTEST(FunctionTest, LongArgumentList) {\n  typedef Function<char(bool, int, char*, int&, const long&)> F;  // NOLINT\n  EXPECT_EQ(5u, F::ArgumentCount);\n  EXPECT_TRUE((std::is_same<char, F::Result>::value));\n  EXPECT_TRUE((std::is_same<bool, F::Arg<0>::type>::value));\n  EXPECT_TRUE((std::is_same<int, F::Arg<1>::type>::value));\n  EXPECT_TRUE((std::is_same<char*, F::Arg<2>::type>::value));\n  EXPECT_TRUE((std::is_same<int&, F::Arg<3>::type>::value));\n  EXPECT_TRUE((std::is_same<const long&, F::Arg<4>::type>::value));  // NOLINT\n  EXPECT_TRUE(\n      (std::is_same<std::tuple<bool, int, char*, int&, const long&>,  // NOLINT\n                    F::ArgumentTuple>::value));\n  EXPECT_TRUE(\n      (std::is_same<\n          std::tuple<Matcher<bool>, Matcher<int>, Matcher<char*>, Matcher<int&>,\n                     Matcher<const long&>>,  // NOLINT\n          F::ArgumentMatcherTuple>::value));\n  EXPECT_TRUE(\n      (std::is_same<void(bool, int, char*, int&, const long&),  // NOLINT\n                    F::MakeResultVoid>::value));\n  EXPECT_TRUE((\n      std::is_same<IgnoredValue(bool, int, char*, int&, const long&),  // NOLINT\n                   F::MakeResultIgnoredValue>::value));\n}\n\nTEST(Base64Unescape, InvalidString) {\n  std::string unescaped;\n  EXPECT_FALSE(Base64Unescape(\"(invalid)\", &unescaped));\n}\n\nTEST(Base64Unescape, ShortString) {\n  std::string unescaped;\n  EXPECT_TRUE(Base64Unescape(\"SGVsbG8gd29ybGQh\", &unescaped));\n  EXPECT_EQ(\"Hello world!\", unescaped);\n}\n\nTEST(Base64Unescape, ShortStringWithPadding) {\n  std::string unescaped;\n  EXPECT_TRUE(Base64Unescape(\"SGVsbG8gd29ybGQ=\", &unescaped));\n  EXPECT_EQ(\"Hello world\", unescaped);\n}\n\nTEST(Base64Unescape, ShortStringWithoutPadding) {\n  std::string unescaped;\n  EXPECT_TRUE(Base64Unescape(\"SGVsbG8gd29ybGQ\", &unescaped));\n  EXPECT_EQ(\"Hello world\", unescaped);\n}\n\nTEST(Base64Unescape, LongStringWithWhiteSpaces) {\n  std::string escaped =\n      R\"(TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz\n  IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg\n  dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu\n  dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo\n  ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=)\";\n  std::string expected =\n      \"Man is distinguished, not only by his reason, but by this singular \"\n      \"passion from other animals, which is a lust of the mind, that by a \"\n      \"perseverance of delight in the continued and indefatigable generation \"\n      \"of knowledge, exceeds the short vehemence of any carnal pleasure.\";\n  std::string unescaped;\n  EXPECT_TRUE(Base64Unescape(escaped, &unescaped));\n  EXPECT_EQ(expected, unescaped);\n}\n\n}  // namespace\n}  // namespace internal\n}  // namespace testing\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock-matchers-arithmetic_test.cc",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file tests some commonly used argument matchers.\n\n// Silence warning C4244: 'initializing': conversion from 'int' to 'short',\n// possible loss of data and C4100, unreferenced local parameter\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#pragma warning(disable : 4100)\n#endif\n\n#include \"test/gmock-matchers_test.h\"\n\nnamespace testing {\nnamespace gmock_matchers_test {\nnamespace {\n\ntypedef ::std::tuple<long, int> Tuple2;  // NOLINT\n\n// Tests that Eq() matches a 2-tuple where the first field == the\n// second field.\nTEST(Eq2Test, MatchesEqualArguments) {\n  Matcher<const Tuple2&> m = Eq();\n  EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));\n  EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));\n}\n\n// Tests that Eq() describes itself properly.\nTEST(Eq2Test, CanDescribeSelf) {\n  Matcher<const Tuple2&> m = Eq();\n  EXPECT_EQ(\"are an equal pair\", Describe(m));\n}\n\n// Tests that Ge() matches a 2-tuple where the first field >= the\n// second field.\nTEST(Ge2Test, MatchesGreaterThanOrEqualArguments) {\n  Matcher<const Tuple2&> m = Ge();\n  EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));\n  EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));\n  EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));\n}\n\n// Tests that Ge() describes itself properly.\nTEST(Ge2Test, CanDescribeSelf) {\n  Matcher<const Tuple2&> m = Ge();\n  EXPECT_EQ(\"are a pair where the first >= the second\", Describe(m));\n}\n\n// Tests that Gt() matches a 2-tuple where the first field > the\n// second field.\nTEST(Gt2Test, MatchesGreaterThanArguments) {\n  Matcher<const Tuple2&> m = Gt();\n  EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));\n  EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));\n  EXPECT_FALSE(m.Matches(Tuple2(5L, 6)));\n}\n\n// Tests that Gt() describes itself properly.\nTEST(Gt2Test, CanDescribeSelf) {\n  Matcher<const Tuple2&> m = Gt();\n  EXPECT_EQ(\"are a pair where the first > the second\", Describe(m));\n}\n\n// Tests that Le() matches a 2-tuple where the first field <= the\n// second field.\nTEST(Le2Test, MatchesLessThanOrEqualArguments) {\n  Matcher<const Tuple2&> m = Le();\n  EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));\n  EXPECT_TRUE(m.Matches(Tuple2(5L, 5)));\n  EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));\n}\n\n// Tests that Le() describes itself properly.\nTEST(Le2Test, CanDescribeSelf) {\n  Matcher<const Tuple2&> m = Le();\n  EXPECT_EQ(\"are a pair where the first <= the second\", Describe(m));\n}\n\n// Tests that Lt() matches a 2-tuple where the first field < the\n// second field.\nTEST(Lt2Test, MatchesLessThanArguments) {\n  Matcher<const Tuple2&> m = Lt();\n  EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));\n  EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));\n  EXPECT_FALSE(m.Matches(Tuple2(5L, 4)));\n}\n\n// Tests that Lt() describes itself properly.\nTEST(Lt2Test, CanDescribeSelf) {\n  Matcher<const Tuple2&> m = Lt();\n  EXPECT_EQ(\"are a pair where the first < the second\", Describe(m));\n}\n\n// Tests that Ne() matches a 2-tuple where the first field != the\n// second field.\nTEST(Ne2Test, MatchesUnequalArguments) {\n  Matcher<const Tuple2&> m = Ne();\n  EXPECT_TRUE(m.Matches(Tuple2(5L, 6)));\n  EXPECT_TRUE(m.Matches(Tuple2(5L, 4)));\n  EXPECT_FALSE(m.Matches(Tuple2(5L, 5)));\n}\n\n// Tests that Ne() describes itself properly.\nTEST(Ne2Test, CanDescribeSelf) {\n  Matcher<const Tuple2&> m = Ne();\n  EXPECT_EQ(\"are an unequal pair\", Describe(m));\n}\n\nTEST(PairMatchBaseTest, WorksWithMoveOnly) {\n  using Pointers = std::tuple<std::unique_ptr<int>, std::unique_ptr<int>>;\n  Matcher<Pointers> matcher = Eq();\n  Pointers pointers;\n  // Tested values don't matter; the point is that matcher does not copy the\n  // matched values.\n  EXPECT_TRUE(matcher.Matches(pointers));\n}\n\n// Tests that IsNan() matches a NaN, with float.\nTEST(IsNan, FloatMatchesNan) {\n  float quiet_nan = std::numeric_limits<float>::quiet_NaN();\n  float other_nan = std::nanf(\"1\");\n  float real_value = 1.0f;\n\n  Matcher<float> m = IsNan();\n  EXPECT_TRUE(m.Matches(quiet_nan));\n  EXPECT_TRUE(m.Matches(other_nan));\n  EXPECT_FALSE(m.Matches(real_value));\n\n  Matcher<float&> m_ref = IsNan();\n  EXPECT_TRUE(m_ref.Matches(quiet_nan));\n  EXPECT_TRUE(m_ref.Matches(other_nan));\n  EXPECT_FALSE(m_ref.Matches(real_value));\n\n  Matcher<const float&> m_cref = IsNan();\n  EXPECT_TRUE(m_cref.Matches(quiet_nan));\n  EXPECT_TRUE(m_cref.Matches(other_nan));\n  EXPECT_FALSE(m_cref.Matches(real_value));\n}\n\n// Tests that IsNan() matches a NaN, with double.\nTEST(IsNan, DoubleMatchesNan) {\n  double quiet_nan = std::numeric_limits<double>::quiet_NaN();\n  double other_nan = std::nan(\"1\");\n  double real_value = 1.0;\n\n  Matcher<double> m = IsNan();\n  EXPECT_TRUE(m.Matches(quiet_nan));\n  EXPECT_TRUE(m.Matches(other_nan));\n  EXPECT_FALSE(m.Matches(real_value));\n\n  Matcher<double&> m_ref = IsNan();\n  EXPECT_TRUE(m_ref.Matches(quiet_nan));\n  EXPECT_TRUE(m_ref.Matches(other_nan));\n  EXPECT_FALSE(m_ref.Matches(real_value));\n\n  Matcher<const double&> m_cref = IsNan();\n  EXPECT_TRUE(m_cref.Matches(quiet_nan));\n  EXPECT_TRUE(m_cref.Matches(other_nan));\n  EXPECT_FALSE(m_cref.Matches(real_value));\n}\n\n// Tests that IsNan() matches a NaN, with long double.\nTEST(IsNan, LongDoubleMatchesNan) {\n  long double quiet_nan = std::numeric_limits<long double>::quiet_NaN();\n  long double other_nan = std::nan(\"1\");\n  long double real_value = 1.0;\n\n  Matcher<long double> m = IsNan();\n  EXPECT_TRUE(m.Matches(quiet_nan));\n  EXPECT_TRUE(m.Matches(other_nan));\n  EXPECT_FALSE(m.Matches(real_value));\n\n  Matcher<long double&> m_ref = IsNan();\n  EXPECT_TRUE(m_ref.Matches(quiet_nan));\n  EXPECT_TRUE(m_ref.Matches(other_nan));\n  EXPECT_FALSE(m_ref.Matches(real_value));\n\n  Matcher<const long double&> m_cref = IsNan();\n  EXPECT_TRUE(m_cref.Matches(quiet_nan));\n  EXPECT_TRUE(m_cref.Matches(other_nan));\n  EXPECT_FALSE(m_cref.Matches(real_value));\n}\n\n// Tests that IsNan() works with Not.\nTEST(IsNan, NotMatchesNan) {\n  Matcher<float> mf = Not(IsNan());\n  EXPECT_FALSE(mf.Matches(std::numeric_limits<float>::quiet_NaN()));\n  EXPECT_FALSE(mf.Matches(std::nanf(\"1\")));\n  EXPECT_TRUE(mf.Matches(1.0));\n\n  Matcher<double> md = Not(IsNan());\n  EXPECT_FALSE(md.Matches(std::numeric_limits<double>::quiet_NaN()));\n  EXPECT_FALSE(md.Matches(std::nan(\"1\")));\n  EXPECT_TRUE(md.Matches(1.0));\n\n  Matcher<long double> mld = Not(IsNan());\n  EXPECT_FALSE(mld.Matches(std::numeric_limits<long double>::quiet_NaN()));\n  EXPECT_FALSE(mld.Matches(std::nanl(\"1\")));\n  EXPECT_TRUE(mld.Matches(1.0));\n}\n\n// Tests that IsNan() can describe itself.\nTEST(IsNan, CanDescribeSelf) {\n  Matcher<float> mf = IsNan();\n  EXPECT_EQ(\"is NaN\", Describe(mf));\n\n  Matcher<double> md = IsNan();\n  EXPECT_EQ(\"is NaN\", Describe(md));\n\n  Matcher<long double> mld = IsNan();\n  EXPECT_EQ(\"is NaN\", Describe(mld));\n}\n\n// Tests that IsNan() can describe itself with Not.\nTEST(IsNan, CanDescribeSelfWithNot) {\n  Matcher<float> mf = Not(IsNan());\n  EXPECT_EQ(\"isn't NaN\", Describe(mf));\n\n  Matcher<double> md = Not(IsNan());\n  EXPECT_EQ(\"isn't NaN\", Describe(md));\n\n  Matcher<long double> mld = Not(IsNan());\n  EXPECT_EQ(\"isn't NaN\", Describe(mld));\n}\n\n// Tests that FloatEq() matches a 2-tuple where\n// FloatEq(first field) matches the second field.\nTEST(FloatEq2Test, MatchesEqualArguments) {\n  typedef ::std::tuple<float, float> Tpl;\n  Matcher<const Tpl&> m = FloatEq();\n  EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));\n  EXPECT_TRUE(m.Matches(Tpl(0.3f, 0.1f + 0.1f + 0.1f)));\n  EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));\n}\n\n// Tests that FloatEq() describes itself properly.\nTEST(FloatEq2Test, CanDescribeSelf) {\n  Matcher<const ::std::tuple<float, float>&> m = FloatEq();\n  EXPECT_EQ(\"are an almost-equal pair\", Describe(m));\n}\n\n// Tests that NanSensitiveFloatEq() matches a 2-tuple where\n// NanSensitiveFloatEq(first field) matches the second field.\nTEST(NanSensitiveFloatEqTest, MatchesEqualArgumentsWithNaN) {\n  typedef ::std::tuple<float, float> Tpl;\n  Matcher<const Tpl&> m = NanSensitiveFloatEq();\n  EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));\n  EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),\n                            std::numeric_limits<float>::quiet_NaN())));\n  EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));\n  EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));\n  EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));\n}\n\n// Tests that NanSensitiveFloatEq() describes itself properly.\nTEST(NanSensitiveFloatEqTest, CanDescribeSelfWithNaNs) {\n  Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatEq();\n  EXPECT_EQ(\"are an almost-equal pair\", Describe(m));\n}\n\n// Tests that DoubleEq() matches a 2-tuple where\n// DoubleEq(first field) matches the second field.\nTEST(DoubleEq2Test, MatchesEqualArguments) {\n  typedef ::std::tuple<double, double> Tpl;\n  Matcher<const Tpl&> m = DoubleEq();\n  EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));\n  EXPECT_TRUE(m.Matches(Tpl(0.3, 0.1 + 0.1 + 0.1)));\n  EXPECT_FALSE(m.Matches(Tpl(1.1, 1.0)));\n}\n\n// Tests that DoubleEq() describes itself properly.\nTEST(DoubleEq2Test, CanDescribeSelf) {\n  Matcher<const ::std::tuple<double, double>&> m = DoubleEq();\n  EXPECT_EQ(\"are an almost-equal pair\", Describe(m));\n}\n\n// Tests that NanSensitiveDoubleEq() matches a 2-tuple where\n// NanSensitiveDoubleEq(first field) matches the second field.\nTEST(NanSensitiveDoubleEqTest, MatchesEqualArgumentsWithNaN) {\n  typedef ::std::tuple<double, double> Tpl;\n  Matcher<const Tpl&> m = NanSensitiveDoubleEq();\n  EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));\n  EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),\n                            std::numeric_limits<double>::quiet_NaN())));\n  EXPECT_FALSE(m.Matches(Tpl(1.1f, 1.0f)));\n  EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));\n  EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));\n}\n\n// Tests that DoubleEq() describes itself properly.\nTEST(NanSensitiveDoubleEqTest, CanDescribeSelfWithNaNs) {\n  Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleEq();\n  EXPECT_EQ(\"are an almost-equal pair\", Describe(m));\n}\n\n// Tests that FloatEq() matches a 2-tuple where\n// FloatNear(first field, max_abs_error) matches the second field.\nTEST(FloatNear2Test, MatchesEqualArguments) {\n  typedef ::std::tuple<float, float> Tpl;\n  Matcher<const Tpl&> m = FloatNear(0.5f);\n  EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));\n  EXPECT_TRUE(m.Matches(Tpl(1.3f, 1.0f)));\n  EXPECT_FALSE(m.Matches(Tpl(1.8f, 1.0f)));\n}\n\n// Tests that FloatNear() describes itself properly.\nTEST(FloatNear2Test, CanDescribeSelf) {\n  Matcher<const ::std::tuple<float, float>&> m = FloatNear(0.5f);\n  EXPECT_EQ(\"are an almost-equal pair\", Describe(m));\n}\n\n// Tests that NanSensitiveFloatNear() matches a 2-tuple where\n// NanSensitiveFloatNear(first field) matches the second field.\nTEST(NanSensitiveFloatNearTest, MatchesNearbyArgumentsWithNaN) {\n  typedef ::std::tuple<float, float> Tpl;\n  Matcher<const Tpl&> m = NanSensitiveFloatNear(0.5f);\n  EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));\n  EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));\n  EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(),\n                            std::numeric_limits<float>::quiet_NaN())));\n  EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));\n  EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<float>::quiet_NaN())));\n  EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<float>::quiet_NaN(), 1.0f)));\n}\n\n// Tests that NanSensitiveFloatNear() describes itself properly.\nTEST(NanSensitiveFloatNearTest, CanDescribeSelfWithNaNs) {\n  Matcher<const ::std::tuple<float, float>&> m = NanSensitiveFloatNear(0.5f);\n  EXPECT_EQ(\"are an almost-equal pair\", Describe(m));\n}\n\n// Tests that FloatEq() matches a 2-tuple where\n// DoubleNear(first field, max_abs_error) matches the second field.\nTEST(DoubleNear2Test, MatchesEqualArguments) {\n  typedef ::std::tuple<double, double> Tpl;\n  Matcher<const Tpl&> m = DoubleNear(0.5);\n  EXPECT_TRUE(m.Matches(Tpl(1.0, 1.0)));\n  EXPECT_TRUE(m.Matches(Tpl(1.3, 1.0)));\n  EXPECT_FALSE(m.Matches(Tpl(1.8, 1.0)));\n}\n\n// Tests that DoubleNear() describes itself properly.\nTEST(DoubleNear2Test, CanDescribeSelf) {\n  Matcher<const ::std::tuple<double, double>&> m = DoubleNear(0.5);\n  EXPECT_EQ(\"are an almost-equal pair\", Describe(m));\n}\n\n// Tests that NanSensitiveDoubleNear() matches a 2-tuple where\n// NanSensitiveDoubleNear(first field) matches the second field.\nTEST(NanSensitiveDoubleNearTest, MatchesNearbyArgumentsWithNaN) {\n  typedef ::std::tuple<double, double> Tpl;\n  Matcher<const Tpl&> m = NanSensitiveDoubleNear(0.5f);\n  EXPECT_TRUE(m.Matches(Tpl(1.0f, 1.0f)));\n  EXPECT_TRUE(m.Matches(Tpl(1.1f, 1.0f)));\n  EXPECT_TRUE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(),\n                            std::numeric_limits<double>::quiet_NaN())));\n  EXPECT_FALSE(m.Matches(Tpl(1.6f, 1.0f)));\n  EXPECT_FALSE(m.Matches(Tpl(1.0f, std::numeric_limits<double>::quiet_NaN())));\n  EXPECT_FALSE(m.Matches(Tpl(std::numeric_limits<double>::quiet_NaN(), 1.0f)));\n}\n\n// Tests that NanSensitiveDoubleNear() describes itself properly.\nTEST(NanSensitiveDoubleNearTest, CanDescribeSelfWithNaNs) {\n  Matcher<const ::std::tuple<double, double>&> m = NanSensitiveDoubleNear(0.5f);\n  EXPECT_EQ(\"are an almost-equal pair\", Describe(m));\n}\n\n// Tests that Not(m) matches any value that doesn't match m.\nTEST(NotTest, NegatesMatcher) {\n  Matcher<int> m;\n  m = Not(Eq(2));\n  EXPECT_TRUE(m.Matches(3));\n  EXPECT_FALSE(m.Matches(2));\n}\n\n// Tests that Not(m) describes itself properly.\nTEST(NotTest, CanDescribeSelf) {\n  Matcher<int> m = Not(Eq(5));\n  EXPECT_EQ(\"isn't equal to 5\", Describe(m));\n}\n\n// Tests that monomorphic matchers are safely cast by the Not matcher.\nTEST(NotTest, NotMatcherSafelyCastsMonomorphicMatchers) {\n  // greater_than_5 is a monomorphic matcher.\n  Matcher<int> greater_than_5 = Gt(5);\n\n  Matcher<const int&> m = Not(greater_than_5);\n  Matcher<int&> m2 = Not(greater_than_5);\n  Matcher<int&> m3 = Not(m);\n}\n\n// Helper to allow easy testing of AllOf matchers with num parameters.\nvoid AllOfMatches(int num, const Matcher<int>& m) {\n  SCOPED_TRACE(Describe(m));\n  EXPECT_TRUE(m.Matches(0));\n  for (int i = 1; i <= num; ++i) {\n    EXPECT_FALSE(m.Matches(i));\n  }\n  EXPECT_TRUE(m.Matches(num + 1));\n}\n\nINSTANTIATE_GTEST_MATCHER_TEST_P(AllOfTest);\n\n// Tests that AllOf(m1, ..., mn) matches any value that matches all of\n// the given matchers.\nTEST(AllOfTest, MatchesWhenAllMatch) {\n  Matcher<int> m;\n  m = AllOf(Le(2), Ge(1));\n  EXPECT_TRUE(m.Matches(1));\n  EXPECT_TRUE(m.Matches(2));\n  EXPECT_FALSE(m.Matches(0));\n  EXPECT_FALSE(m.Matches(3));\n\n  m = AllOf(Gt(0), Ne(1), Ne(2));\n  EXPECT_TRUE(m.Matches(3));\n  EXPECT_FALSE(m.Matches(2));\n  EXPECT_FALSE(m.Matches(1));\n  EXPECT_FALSE(m.Matches(0));\n\n  m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));\n  EXPECT_TRUE(m.Matches(4));\n  EXPECT_FALSE(m.Matches(3));\n  EXPECT_FALSE(m.Matches(2));\n  EXPECT_FALSE(m.Matches(1));\n  EXPECT_FALSE(m.Matches(0));\n\n  m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));\n  EXPECT_TRUE(m.Matches(0));\n  EXPECT_TRUE(m.Matches(1));\n  EXPECT_FALSE(m.Matches(3));\n\n  // The following tests for varying number of sub-matchers. Due to the way\n  // the sub-matchers are handled it is enough to test every sub-matcher once\n  // with sub-matchers using the same matcher type. Varying matcher types are\n  // checked for above.\n  AllOfMatches(2, AllOf(Ne(1), Ne(2)));\n  AllOfMatches(3, AllOf(Ne(1), Ne(2), Ne(3)));\n  AllOfMatches(4, AllOf(Ne(1), Ne(2), Ne(3), Ne(4)));\n  AllOfMatches(5, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5)));\n  AllOfMatches(6, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6)));\n  AllOfMatches(7, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7)));\n  AllOfMatches(8,\n               AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8)));\n  AllOfMatches(\n      9, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9)));\n  AllOfMatches(10, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8),\n                         Ne(9), Ne(10)));\n  AllOfMatches(\n      50, AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),\n                Ne(10), Ne(11), Ne(12), Ne(13), Ne(14), Ne(15), Ne(16), Ne(17),\n                Ne(18), Ne(19), Ne(20), Ne(21), Ne(22), Ne(23), Ne(24), Ne(25),\n                Ne(26), Ne(27), Ne(28), Ne(29), Ne(30), Ne(31), Ne(32), Ne(33),\n                Ne(34), Ne(35), Ne(36), Ne(37), Ne(38), Ne(39), Ne(40), Ne(41),\n                Ne(42), Ne(43), Ne(44), Ne(45), Ne(46), Ne(47), Ne(48), Ne(49),\n                Ne(50)));\n}\n\n// Tests that AllOf(m1, ..., mn) describes itself properly.\nTEST(AllOfTest, CanDescribeSelf) {\n  Matcher<int> m;\n  m = AllOf(Le(2), Ge(1));\n  EXPECT_EQ(\"(is <= 2) and (is >= 1)\", Describe(m));\n\n  m = AllOf(Gt(0), Ne(1), Ne(2));\n  std::string expected_descr1 =\n      \"(is > 0) and (isn't equal to 1) and (isn't equal to 2)\";\n  EXPECT_EQ(expected_descr1, Describe(m));\n\n  m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));\n  std::string expected_descr2 =\n      \"(is > 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't equal \"\n      \"to 3)\";\n  EXPECT_EQ(expected_descr2, Describe(m));\n\n  m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));\n  std::string expected_descr3 =\n      \"(is >= 0) and (is < 10) and (isn't equal to 3) and (isn't equal to 5) \"\n      \"and (isn't equal to 7)\";\n  EXPECT_EQ(expected_descr3, Describe(m));\n}\n\n// Tests that AllOf(m1, ..., mn) describes its negation properly.\nTEST(AllOfTest, CanDescribeNegation) {\n  Matcher<int> m;\n  m = AllOf(Le(2), Ge(1));\n  std::string expected_descr4 = \"(isn't <= 2) or (isn't >= 1)\";\n  EXPECT_EQ(expected_descr4, DescribeNegation(m));\n\n  m = AllOf(Gt(0), Ne(1), Ne(2));\n  std::string expected_descr5 =\n      \"(isn't > 0) or (is equal to 1) or (is equal to 2)\";\n  EXPECT_EQ(expected_descr5, DescribeNegation(m));\n\n  m = AllOf(Gt(0), Ne(1), Ne(2), Ne(3));\n  std::string expected_descr6 =\n      \"(isn't > 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)\";\n  EXPECT_EQ(expected_descr6, DescribeNegation(m));\n\n  m = AllOf(Ge(0), Lt(10), Ne(3), Ne(5), Ne(7));\n  std::string expected_desr7 =\n      \"(isn't >= 0) or (isn't < 10) or (is equal to 3) or (is equal to 5) or \"\n      \"(is equal to 7)\";\n  EXPECT_EQ(expected_desr7, DescribeNegation(m));\n\n  m = AllOf(Ne(1), Ne(2), Ne(3), Ne(4), Ne(5), Ne(6), Ne(7), Ne(8), Ne(9),\n            Ne(10), Ne(11));\n  AllOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);\n  EXPECT_THAT(Describe(m), EndsWith(\"and (isn't equal to 11)\"));\n  AllOfMatches(11, m);\n}\n\n// Tests that monomorphic matchers are safely cast by the AllOf matcher.\nTEST(AllOfTest, AllOfMatcherSafelyCastsMonomorphicMatchers) {\n  // greater_than_5 and less_than_10 are monomorphic matchers.\n  Matcher<int> greater_than_5 = Gt(5);\n  Matcher<int> less_than_10 = Lt(10);\n\n  Matcher<const int&> m = AllOf(greater_than_5, less_than_10);\n  Matcher<int&> m2 = AllOf(greater_than_5, less_than_10);\n  Matcher<int&> m3 = AllOf(greater_than_5, m2);\n\n  // Tests that BothOf works when composing itself.\n  Matcher<const int&> m4 = AllOf(greater_than_5, less_than_10, less_than_10);\n  Matcher<int&> m5 = AllOf(greater_than_5, less_than_10, less_than_10);\n}\n\nTEST_P(AllOfTestP, ExplainsResult) {\n  Matcher<int> m;\n\n  // Successful match.  Both matchers need to explain.  The second\n  // matcher doesn't give an explanation, so only the first matcher's\n  // explanation is printed.\n  m = AllOf(GreaterThan(10), Lt(30));\n  EXPECT_EQ(\"which is 15 more than 10\", Explain(m, 25));\n\n  // Successful match.  Both matchers need to explain.\n  m = AllOf(GreaterThan(10), GreaterThan(20));\n  EXPECT_EQ(\"which is 20 more than 10, and which is 10 more than 20\",\n            Explain(m, 30));\n\n  // Successful match.  All matchers need to explain.  The second\n  // matcher doesn't given an explanation.\n  m = AllOf(GreaterThan(10), Lt(30), GreaterThan(20));\n  EXPECT_EQ(\"which is 15 more than 10, and which is 5 more than 20\",\n            Explain(m, 25));\n\n  // Successful match.  All matchers need to explain.\n  m = AllOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));\n  EXPECT_EQ(\n      \"which is 30 more than 10, and which is 20 more than 20, \"\n      \"and which is 10 more than 30\",\n      Explain(m, 40));\n\n  // Failed match.  The first matcher, which failed, needs to\n  // explain.\n  m = AllOf(GreaterThan(10), GreaterThan(20));\n  EXPECT_EQ(\"which is 5 less than 10\", Explain(m, 5));\n\n  // Failed match.  The second matcher, which failed, needs to\n  // explain.  Since it doesn't given an explanation, nothing is\n  // printed.\n  m = AllOf(GreaterThan(10), Lt(30));\n  EXPECT_EQ(\"\", Explain(m, 40));\n\n  // Failed match.  The second matcher, which failed, needs to\n  // explain.\n  m = AllOf(GreaterThan(10), GreaterThan(20));\n  EXPECT_EQ(\"which is 5 less than 20\", Explain(m, 15));\n}\n\n// Helper to allow easy testing of AnyOf matchers with num parameters.\nstatic void AnyOfMatches(int num, const Matcher<int>& m) {\n  SCOPED_TRACE(Describe(m));\n  EXPECT_FALSE(m.Matches(0));\n  for (int i = 1; i <= num; ++i) {\n    EXPECT_TRUE(m.Matches(i));\n  }\n  EXPECT_FALSE(m.Matches(num + 1));\n}\n\nstatic void AnyOfStringMatches(int num, const Matcher<std::string>& m) {\n  SCOPED_TRACE(Describe(m));\n  EXPECT_FALSE(m.Matches(std::to_string(0)));\n\n  for (int i = 1; i <= num; ++i) {\n    EXPECT_TRUE(m.Matches(std::to_string(i)));\n  }\n  EXPECT_FALSE(m.Matches(std::to_string(num + 1)));\n}\n\nINSTANTIATE_GTEST_MATCHER_TEST_P(AnyOfTest);\n\n// Tests that AnyOf(m1, ..., mn) matches any value that matches at\n// least one of the given matchers.\nTEST(AnyOfTest, MatchesWhenAnyMatches) {\n  Matcher<int> m;\n  m = AnyOf(Le(1), Ge(3));\n  EXPECT_TRUE(m.Matches(1));\n  EXPECT_TRUE(m.Matches(4));\n  EXPECT_FALSE(m.Matches(2));\n\n  m = AnyOf(Lt(0), Eq(1), Eq(2));\n  EXPECT_TRUE(m.Matches(-1));\n  EXPECT_TRUE(m.Matches(1));\n  EXPECT_TRUE(m.Matches(2));\n  EXPECT_FALSE(m.Matches(0));\n\n  m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));\n  EXPECT_TRUE(m.Matches(-1));\n  EXPECT_TRUE(m.Matches(1));\n  EXPECT_TRUE(m.Matches(2));\n  EXPECT_TRUE(m.Matches(3));\n  EXPECT_FALSE(m.Matches(0));\n\n  m = AnyOf(Le(0), Gt(10), 3, 5, 7);\n  EXPECT_TRUE(m.Matches(0));\n  EXPECT_TRUE(m.Matches(11));\n  EXPECT_TRUE(m.Matches(3));\n  EXPECT_FALSE(m.Matches(2));\n\n  // The following tests for varying number of sub-matchers. Due to the way\n  // the sub-matchers are handled it is enough to test every sub-matcher once\n  // with sub-matchers using the same matcher type. Varying matcher types are\n  // checked for above.\n  AnyOfMatches(2, AnyOf(1, 2));\n  AnyOfMatches(3, AnyOf(1, 2, 3));\n  AnyOfMatches(4, AnyOf(1, 2, 3, 4));\n  AnyOfMatches(5, AnyOf(1, 2, 3, 4, 5));\n  AnyOfMatches(6, AnyOf(1, 2, 3, 4, 5, 6));\n  AnyOfMatches(7, AnyOf(1, 2, 3, 4, 5, 6, 7));\n  AnyOfMatches(8, AnyOf(1, 2, 3, 4, 5, 6, 7, 8));\n  AnyOfMatches(9, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9));\n  AnyOfMatches(10, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));\n}\n\n// Tests the variadic version of the AnyOfMatcher.\nTEST(AnyOfTest, VariadicMatchesWhenAnyMatches) {\n  // Also make sure AnyOf is defined in the right namespace and does not depend\n  // on ADL.\n  Matcher<int> m = ::testing::AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);\n\n  EXPECT_THAT(Describe(m), EndsWith(\"or (is equal to 11)\"));\n  AnyOfMatches(11, m);\n  AnyOfMatches(50, AnyOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,\n                         17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30,\n                         31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,\n                         45, 46, 47, 48, 49, 50));\n  AnyOfStringMatches(\n      50, AnyOf(\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\", \"12\",\n                \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", \"19\", \"20\", \"21\", \"22\",\n                \"23\", \"24\", \"25\", \"26\", \"27\", \"28\", \"29\", \"30\", \"31\", \"32\",\n                \"33\", \"34\", \"35\", \"36\", \"37\", \"38\", \"39\", \"40\", \"41\", \"42\",\n                \"43\", \"44\", \"45\", \"46\", \"47\", \"48\", \"49\", \"50\"));\n}\n\nTEST(ConditionalTest, MatchesFirstIfCondition) {\n  Matcher<std::string> eq_red = Eq(\"red\");\n  Matcher<std::string> ne_red = Ne(\"red\");\n  Matcher<std::string> m = Conditional(true, eq_red, ne_red);\n  EXPECT_TRUE(m.Matches(\"red\"));\n  EXPECT_FALSE(m.Matches(\"green\"));\n\n  StringMatchResultListener listener;\n  StringMatchResultListener expected;\n  EXPECT_FALSE(m.MatchAndExplain(\"green\", &listener));\n  EXPECT_FALSE(eq_red.MatchAndExplain(\"green\", &expected));\n  EXPECT_THAT(listener.str(), Eq(expected.str()));\n}\n\nTEST(ConditionalTest, MatchesSecondIfCondition) {\n  Matcher<std::string> eq_red = Eq(\"red\");\n  Matcher<std::string> ne_red = Ne(\"red\");\n  Matcher<std::string> m = Conditional(false, eq_red, ne_red);\n  EXPECT_FALSE(m.Matches(\"red\"));\n  EXPECT_TRUE(m.Matches(\"green\"));\n\n  StringMatchResultListener listener;\n  StringMatchResultListener expected;\n  EXPECT_FALSE(m.MatchAndExplain(\"red\", &listener));\n  EXPECT_FALSE(ne_red.MatchAndExplain(\"red\", &expected));\n  EXPECT_THAT(listener.str(), Eq(expected.str()));\n}\n\n// Tests that AnyOf(m1, ..., mn) describes itself properly.\nTEST(AnyOfTest, CanDescribeSelf) {\n  Matcher<int> m;\n  m = AnyOf(Le(1), Ge(3));\n\n  EXPECT_EQ(\"(is <= 1) or (is >= 3)\", Describe(m));\n\n  m = AnyOf(Lt(0), Eq(1), Eq(2));\n  EXPECT_EQ(\"(is < 0) or (is equal to 1) or (is equal to 2)\", Describe(m));\n\n  m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));\n  EXPECT_EQ(\"(is < 0) or (is equal to 1) or (is equal to 2) or (is equal to 3)\",\n            Describe(m));\n\n  m = AnyOf(Le(0), Gt(10), 3, 5, 7);\n  EXPECT_EQ(\n      \"(is <= 0) or (is > 10) or (is equal to 3) or (is equal to 5) or (is \"\n      \"equal to 7)\",\n      Describe(m));\n}\n\n// Tests that AnyOf(m1, ..., mn) describes its negation properly.\nTEST(AnyOfTest, CanDescribeNegation) {\n  Matcher<int> m;\n  m = AnyOf(Le(1), Ge(3));\n  EXPECT_EQ(\"(isn't <= 1) and (isn't >= 3)\", DescribeNegation(m));\n\n  m = AnyOf(Lt(0), Eq(1), Eq(2));\n  EXPECT_EQ(\"(isn't < 0) and (isn't equal to 1) and (isn't equal to 2)\",\n            DescribeNegation(m));\n\n  m = AnyOf(Lt(0), Eq(1), Eq(2), Eq(3));\n  EXPECT_EQ(\n      \"(isn't < 0) and (isn't equal to 1) and (isn't equal to 2) and (isn't \"\n      \"equal to 3)\",\n      DescribeNegation(m));\n\n  m = AnyOf(Le(0), Gt(10), 3, 5, 7);\n  EXPECT_EQ(\n      \"(isn't <= 0) and (isn't > 10) and (isn't equal to 3) and (isn't equal \"\n      \"to 5) and (isn't equal to 7)\",\n      DescribeNegation(m));\n}\n\n// Tests that monomorphic matchers are safely cast by the AnyOf matcher.\nTEST(AnyOfTest, AnyOfMatcherSafelyCastsMonomorphicMatchers) {\n  // greater_than_5 and less_than_10 are monomorphic matchers.\n  Matcher<int> greater_than_5 = Gt(5);\n  Matcher<int> less_than_10 = Lt(10);\n\n  Matcher<const int&> m = AnyOf(greater_than_5, less_than_10);\n  Matcher<int&> m2 = AnyOf(greater_than_5, less_than_10);\n  Matcher<int&> m3 = AnyOf(greater_than_5, m2);\n\n  // Tests that EitherOf works when composing itself.\n  Matcher<const int&> m4 = AnyOf(greater_than_5, less_than_10, less_than_10);\n  Matcher<int&> m5 = AnyOf(greater_than_5, less_than_10, less_than_10);\n}\n\nTEST_P(AnyOfTestP, ExplainsResult) {\n  Matcher<int> m;\n\n  // Failed match.  Both matchers need to explain.  The second\n  // matcher doesn't give an explanation, so only the first matcher's\n  // explanation is printed.\n  m = AnyOf(GreaterThan(10), Lt(0));\n  EXPECT_EQ(\"which is 5 less than 10\", Explain(m, 5));\n\n  // Failed match.  Both matchers need to explain.\n  m = AnyOf(GreaterThan(10), GreaterThan(20));\n  EXPECT_EQ(\"which is 5 less than 10, and which is 15 less than 20\",\n            Explain(m, 5));\n\n  // Failed match.  All matchers need to explain.  The second\n  // matcher doesn't given an explanation.\n  m = AnyOf(GreaterThan(10), Gt(20), GreaterThan(30));\n  EXPECT_EQ(\"which is 5 less than 10, and which is 25 less than 30\",\n            Explain(m, 5));\n\n  // Failed match.  All matchers need to explain.\n  m = AnyOf(GreaterThan(10), GreaterThan(20), GreaterThan(30));\n  EXPECT_EQ(\n      \"which is 5 less than 10, and which is 15 less than 20, \"\n      \"and which is 25 less than 30\",\n      Explain(m, 5));\n\n  // Successful match.  The first matcher, which succeeded, needs to\n  // explain.\n  m = AnyOf(GreaterThan(10), GreaterThan(20));\n  EXPECT_EQ(\"which is 5 more than 10\", Explain(m, 15));\n\n  // Successful match.  The second matcher, which succeeded, needs to\n  // explain.  Since it doesn't given an explanation, nothing is\n  // printed.\n  m = AnyOf(GreaterThan(10), Lt(30));\n  EXPECT_EQ(\"\", Explain(m, 0));\n\n  // Successful match.  The second matcher, which succeeded, needs to\n  // explain.\n  m = AnyOf(GreaterThan(30), GreaterThan(20));\n  EXPECT_EQ(\"which is 5 more than 20\", Explain(m, 25));\n}\n\n// The following predicate function and predicate functor are for\n// testing the Truly(predicate) matcher.\n\n// Returns non-zero if the input is positive.  Note that the return\n// type of this function is not bool.  It's OK as Truly() accepts any\n// unary function or functor whose return type can be implicitly\n// converted to bool.\nint IsPositive(double x) { return x > 0 ? 1 : 0; }\n\n// This functor returns true if the input is greater than the given\n// number.\nclass IsGreaterThan {\n public:\n  explicit IsGreaterThan(int threshold) : threshold_(threshold) {}\n\n  bool operator()(int n) const { return n > threshold_; }\n\n private:\n  int threshold_;\n};\n\n// For testing Truly().\nconst int foo = 0;\n\n// This predicate returns true if and only if the argument references foo and\n// has a zero value.\nbool ReferencesFooAndIsZero(const int& n) { return (&n == &foo) && (n == 0); }\n\n// Tests that Truly(predicate) matches what satisfies the given\n// predicate.\nTEST(TrulyTest, MatchesWhatSatisfiesThePredicate) {\n  Matcher<double> m = Truly(IsPositive);\n  EXPECT_TRUE(m.Matches(2.0));\n  EXPECT_FALSE(m.Matches(-1.5));\n}\n\n// Tests that Truly(predicate_functor) works too.\nTEST(TrulyTest, CanBeUsedWithFunctor) {\n  Matcher<int> m = Truly(IsGreaterThan(5));\n  EXPECT_TRUE(m.Matches(6));\n  EXPECT_FALSE(m.Matches(4));\n}\n\n// A class that can be implicitly converted to bool.\nclass ConvertibleToBool {\n public:\n  explicit ConvertibleToBool(int number) : number_(number) {}\n  operator bool() const { return number_ != 0; }\n\n private:\n  int number_;\n};\n\nConvertibleToBool IsNotZero(int number) { return ConvertibleToBool(number); }\n\n// Tests that the predicate used in Truly() may return a class that's\n// implicitly convertible to bool, even when the class has no\n// operator!().\nTEST(TrulyTest, PredicateCanReturnAClassConvertibleToBool) {\n  Matcher<int> m = Truly(IsNotZero);\n  EXPECT_TRUE(m.Matches(1));\n  EXPECT_FALSE(m.Matches(0));\n}\n\n// Tests that Truly(predicate) can describe itself properly.\nTEST(TrulyTest, CanDescribeSelf) {\n  Matcher<double> m = Truly(IsPositive);\n  EXPECT_EQ(\"satisfies the given predicate\", Describe(m));\n}\n\n// Tests that Truly(predicate) works when the matcher takes its\n// argument by reference.\nTEST(TrulyTest, WorksForByRefArguments) {\n  Matcher<const int&> m = Truly(ReferencesFooAndIsZero);\n  EXPECT_TRUE(m.Matches(foo));\n  int n = 0;\n  EXPECT_FALSE(m.Matches(n));\n}\n\n// Tests that Truly(predicate) provides a helpful reason when it fails.\nTEST(TrulyTest, ExplainsFailures) {\n  StringMatchResultListener listener;\n  EXPECT_FALSE(ExplainMatchResult(Truly(IsPositive), -1, &listener));\n  EXPECT_EQ(listener.str(), \"didn't satisfy the given predicate\");\n}\n\n// Tests that Matches(m) is a predicate satisfied by whatever that\n// matches matcher m.\nTEST(MatchesTest, IsSatisfiedByWhatMatchesTheMatcher) {\n  EXPECT_TRUE(Matches(Ge(0))(1));\n  EXPECT_FALSE(Matches(Eq('a'))('b'));\n}\n\n// Tests that Matches(m) works when the matcher takes its argument by\n// reference.\nTEST(MatchesTest, WorksOnByRefArguments) {\n  int m = 0, n = 0;\n  EXPECT_TRUE(Matches(AllOf(Ref(n), Eq(0)))(n));\n  EXPECT_FALSE(Matches(Ref(m))(n));\n}\n\n// Tests that a Matcher on non-reference type can be used in\n// Matches().\nTEST(MatchesTest, WorksWithMatcherOnNonRefType) {\n  Matcher<int> eq5 = Eq(5);\n  EXPECT_TRUE(Matches(eq5)(5));\n  EXPECT_FALSE(Matches(eq5)(2));\n}\n\n// Tests Value(value, matcher).  Since Value() is a simple wrapper for\n// Matches(), which has been tested already, we don't spend a lot of\n// effort on testing Value().\nTEST(ValueTest, WorksWithPolymorphicMatcher) {\n  EXPECT_TRUE(Value(\"hi\", StartsWith(\"h\")));\n  EXPECT_FALSE(Value(5, Gt(10)));\n}\n\nTEST(ValueTest, WorksWithMonomorphicMatcher) {\n  const Matcher<int> is_zero = Eq(0);\n  EXPECT_TRUE(Value(0, is_zero));\n  EXPECT_FALSE(Value('a', is_zero));\n\n  int n = 0;\n  const Matcher<const int&> ref_n = Ref(n);\n  EXPECT_TRUE(Value(n, ref_n));\n  EXPECT_FALSE(Value(1, ref_n));\n}\n\nTEST(AllArgsTest, WorksForTuple) {\n  EXPECT_THAT(std::make_tuple(1, 2L), AllArgs(Lt()));\n  EXPECT_THAT(std::make_tuple(2L, 1), Not(AllArgs(Lt())));\n}\n\nTEST(AllArgsTest, WorksForNonTuple) {\n  EXPECT_THAT(42, AllArgs(Gt(0)));\n  EXPECT_THAT('a', Not(AllArgs(Eq('b'))));\n}\n\nclass AllArgsHelper {\n public:\n  AllArgsHelper() {}\n\n  MOCK_METHOD2(Helper, int(char x, int y));\n\n private:\n  AllArgsHelper(const AllArgsHelper&) = delete;\n  AllArgsHelper& operator=(const AllArgsHelper&) = delete;\n};\n\nTEST(AllArgsTest, WorksInWithClause) {\n  AllArgsHelper helper;\n  ON_CALL(helper, Helper(_, _)).With(AllArgs(Lt())).WillByDefault(Return(1));\n  EXPECT_CALL(helper, Helper(_, _));\n  EXPECT_CALL(helper, Helper(_, _)).With(AllArgs(Gt())).WillOnce(Return(2));\n\n  EXPECT_EQ(1, helper.Helper('\\1', 2));\n  EXPECT_EQ(2, helper.Helper('a', 1));\n}\n\nclass OptionalMatchersHelper {\n public:\n  OptionalMatchersHelper() {}\n\n  MOCK_METHOD0(NoArgs, int());\n\n  MOCK_METHOD1(OneArg, int(int y));\n\n  MOCK_METHOD2(TwoArgs, int(char x, int y));\n\n  MOCK_METHOD1(Overloaded, int(char x));\n  MOCK_METHOD2(Overloaded, int(char x, int y));\n\n private:\n  OptionalMatchersHelper(const OptionalMatchersHelper&) = delete;\n  OptionalMatchersHelper& operator=(const OptionalMatchersHelper&) = delete;\n};\n\nTEST(AllArgsTest, WorksWithoutMatchers) {\n  OptionalMatchersHelper helper;\n\n  ON_CALL(helper, NoArgs).WillByDefault(Return(10));\n  ON_CALL(helper, OneArg).WillByDefault(Return(20));\n  ON_CALL(helper, TwoArgs).WillByDefault(Return(30));\n\n  EXPECT_EQ(10, helper.NoArgs());\n  EXPECT_EQ(20, helper.OneArg(1));\n  EXPECT_EQ(30, helper.TwoArgs('\\1', 2));\n\n  EXPECT_CALL(helper, NoArgs).Times(1);\n  EXPECT_CALL(helper, OneArg).WillOnce(Return(100));\n  EXPECT_CALL(helper, OneArg(17)).WillOnce(Return(200));\n  EXPECT_CALL(helper, TwoArgs).Times(0);\n\n  EXPECT_EQ(10, helper.NoArgs());\n  EXPECT_EQ(100, helper.OneArg(1));\n  EXPECT_EQ(200, helper.OneArg(17));\n}\n\n// Tests floating-point matchers.\ntemplate <typename RawType>\nclass FloatingPointTest : public testing::Test {\n protected:\n  typedef testing::internal::FloatingPoint<RawType> Floating;\n  typedef typename Floating::Bits Bits;\n\n  FloatingPointTest()\n      : max_ulps_(Floating::kMaxUlps),\n        zero_bits_(Floating(0).bits()),\n        one_bits_(Floating(1).bits()),\n        infinity_bits_(Floating(Floating::Infinity()).bits()),\n        close_to_positive_zero_(\n            Floating::ReinterpretBits(zero_bits_ + max_ulps_ / 2)),\n        close_to_negative_zero_(\n            -Floating::ReinterpretBits(zero_bits_ + max_ulps_ - max_ulps_ / 2)),\n        further_from_negative_zero_(-Floating::ReinterpretBits(\n            zero_bits_ + max_ulps_ + 1 - max_ulps_ / 2)),\n        close_to_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_)),\n        further_from_one_(Floating::ReinterpretBits(one_bits_ + max_ulps_ + 1)),\n        infinity_(Floating::Infinity()),\n        close_to_infinity_(\n            Floating::ReinterpretBits(infinity_bits_ - max_ulps_)),\n        further_from_infinity_(\n            Floating::ReinterpretBits(infinity_bits_ - max_ulps_ - 1)),\n        max_(Floating::Max()),\n        nan1_(Floating::ReinterpretBits(Floating::kExponentBitMask | 1)),\n        nan2_(Floating::ReinterpretBits(Floating::kExponentBitMask | 200)) {}\n\n  void TestSize() { EXPECT_EQ(sizeof(RawType), sizeof(Bits)); }\n\n  // A battery of tests for FloatingEqMatcher::Matches.\n  // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.\n  void TestMatches(\n      testing::internal::FloatingEqMatcher<RawType> (*matcher_maker)(RawType)) {\n    Matcher<RawType> m1 = matcher_maker(0.0);\n    EXPECT_TRUE(m1.Matches(-0.0));\n    EXPECT_TRUE(m1.Matches(close_to_positive_zero_));\n    EXPECT_TRUE(m1.Matches(close_to_negative_zero_));\n    EXPECT_FALSE(m1.Matches(1.0));\n\n    Matcher<RawType> m2 = matcher_maker(close_to_positive_zero_);\n    EXPECT_FALSE(m2.Matches(further_from_negative_zero_));\n\n    Matcher<RawType> m3 = matcher_maker(1.0);\n    EXPECT_TRUE(m3.Matches(close_to_one_));\n    EXPECT_FALSE(m3.Matches(further_from_one_));\n\n    // Test commutativity: matcher_maker(0.0).Matches(1.0) was tested above.\n    EXPECT_FALSE(m3.Matches(0.0));\n\n    Matcher<RawType> m4 = matcher_maker(-infinity_);\n    EXPECT_TRUE(m4.Matches(-close_to_infinity_));\n\n    Matcher<RawType> m5 = matcher_maker(infinity_);\n    EXPECT_TRUE(m5.Matches(close_to_infinity_));\n\n    // This is interesting as the representations of infinity_ and nan1_\n    // are only 1 DLP apart.\n    EXPECT_FALSE(m5.Matches(nan1_));\n\n    // matcher_maker can produce a Matcher<const RawType&>, which is needed in\n    // some cases.\n    Matcher<const RawType&> m6 = matcher_maker(0.0);\n    EXPECT_TRUE(m6.Matches(-0.0));\n    EXPECT_TRUE(m6.Matches(close_to_positive_zero_));\n    EXPECT_FALSE(m6.Matches(1.0));\n\n    // matcher_maker can produce a Matcher<RawType&>, which is needed in some\n    // cases.\n    Matcher<RawType&> m7 = matcher_maker(0.0);\n    RawType x = 0.0;\n    EXPECT_TRUE(m7.Matches(x));\n    x = 0.01f;\n    EXPECT_FALSE(m7.Matches(x));\n  }\n\n  // Pre-calculated numbers to be used by the tests.\n\n  const Bits max_ulps_;\n\n  const Bits zero_bits_;      // The bits that represent 0.0.\n  const Bits one_bits_;       // The bits that represent 1.0.\n  const Bits infinity_bits_;  // The bits that represent +infinity.\n\n  // Some numbers close to 0.0.\n  const RawType close_to_positive_zero_;\n  const RawType close_to_negative_zero_;\n  const RawType further_from_negative_zero_;\n\n  // Some numbers close to 1.0.\n  const RawType close_to_one_;\n  const RawType further_from_one_;\n\n  // Some numbers close to +infinity.\n  const RawType infinity_;\n  const RawType close_to_infinity_;\n  const RawType further_from_infinity_;\n\n  // Maximum representable value that's not infinity.\n  const RawType max_;\n\n  // Some NaNs.\n  const RawType nan1_;\n  const RawType nan2_;\n};\n\n// Tests floating-point matchers with fixed epsilons.\ntemplate <typename RawType>\nclass FloatingPointNearTest : public FloatingPointTest<RawType> {\n protected:\n  typedef FloatingPointTest<RawType> ParentType;\n\n  // A battery of tests for FloatingEqMatcher::Matches with a fixed epsilon.\n  // matcher_maker is a pointer to a function which creates a FloatingEqMatcher.\n  void TestNearMatches(testing::internal::FloatingEqMatcher<RawType> (\n      *matcher_maker)(RawType, RawType)) {\n    Matcher<RawType> m1 = matcher_maker(0.0, 0.0);\n    EXPECT_TRUE(m1.Matches(0.0));\n    EXPECT_TRUE(m1.Matches(-0.0));\n    EXPECT_FALSE(m1.Matches(ParentType::close_to_positive_zero_));\n    EXPECT_FALSE(m1.Matches(ParentType::close_to_negative_zero_));\n    EXPECT_FALSE(m1.Matches(1.0));\n\n    Matcher<RawType> m2 = matcher_maker(0.0, 1.0);\n    EXPECT_TRUE(m2.Matches(0.0));\n    EXPECT_TRUE(m2.Matches(-0.0));\n    EXPECT_TRUE(m2.Matches(1.0));\n    EXPECT_TRUE(m2.Matches(-1.0));\n    EXPECT_FALSE(m2.Matches(ParentType::close_to_one_));\n    EXPECT_FALSE(m2.Matches(-ParentType::close_to_one_));\n\n    // Check that inf matches inf, regardless of the of the specified max\n    // absolute error.\n    Matcher<RawType> m3 = matcher_maker(ParentType::infinity_, 0.0);\n    EXPECT_TRUE(m3.Matches(ParentType::infinity_));\n    EXPECT_FALSE(m3.Matches(ParentType::close_to_infinity_));\n    EXPECT_FALSE(m3.Matches(-ParentType::infinity_));\n\n    Matcher<RawType> m4 = matcher_maker(-ParentType::infinity_, 0.0);\n    EXPECT_TRUE(m4.Matches(-ParentType::infinity_));\n    EXPECT_FALSE(m4.Matches(-ParentType::close_to_infinity_));\n    EXPECT_FALSE(m4.Matches(ParentType::infinity_));\n\n    // Test various overflow scenarios.\n    Matcher<RawType> m5 = matcher_maker(ParentType::max_, ParentType::max_);\n    EXPECT_TRUE(m5.Matches(ParentType::max_));\n    EXPECT_FALSE(m5.Matches(-ParentType::max_));\n\n    Matcher<RawType> m6 = matcher_maker(-ParentType::max_, ParentType::max_);\n    EXPECT_FALSE(m6.Matches(ParentType::max_));\n    EXPECT_TRUE(m6.Matches(-ParentType::max_));\n\n    Matcher<RawType> m7 = matcher_maker(ParentType::max_, 0);\n    EXPECT_TRUE(m7.Matches(ParentType::max_));\n    EXPECT_FALSE(m7.Matches(-ParentType::max_));\n\n    Matcher<RawType> m8 = matcher_maker(-ParentType::max_, 0);\n    EXPECT_FALSE(m8.Matches(ParentType::max_));\n    EXPECT_TRUE(m8.Matches(-ParentType::max_));\n\n    // The difference between max() and -max() normally overflows to infinity,\n    // but it should still match if the max_abs_error is also infinity.\n    Matcher<RawType> m9 =\n        matcher_maker(ParentType::max_, ParentType::infinity_);\n    EXPECT_TRUE(m8.Matches(-ParentType::max_));\n\n    // matcher_maker can produce a Matcher<const RawType&>, which is needed in\n    // some cases.\n    Matcher<const RawType&> m10 = matcher_maker(0.0, 1.0);\n    EXPECT_TRUE(m10.Matches(-0.0));\n    EXPECT_TRUE(m10.Matches(ParentType::close_to_positive_zero_));\n    EXPECT_FALSE(m10.Matches(ParentType::close_to_one_));\n\n    // matcher_maker can produce a Matcher<RawType&>, which is needed in some\n    // cases.\n    Matcher<RawType&> m11 = matcher_maker(0.0, 1.0);\n    RawType x = 0.0;\n    EXPECT_TRUE(m11.Matches(x));\n    x = 1.0f;\n    EXPECT_TRUE(m11.Matches(x));\n    x = -1.0f;\n    EXPECT_TRUE(m11.Matches(x));\n    x = 1.1f;\n    EXPECT_FALSE(m11.Matches(x));\n    x = -1.1f;\n    EXPECT_FALSE(m11.Matches(x));\n  }\n};\n\n// Instantiate FloatingPointTest for testing floats.\ntypedef FloatingPointTest<float> FloatTest;\n\nTEST_F(FloatTest, FloatEqApproximatelyMatchesFloats) { TestMatches(&FloatEq); }\n\nTEST_F(FloatTest, NanSensitiveFloatEqApproximatelyMatchesFloats) {\n  TestMatches(&NanSensitiveFloatEq);\n}\n\nTEST_F(FloatTest, FloatEqCannotMatchNaN) {\n  // FloatEq never matches NaN.\n  Matcher<float> m = FloatEq(nan1_);\n  EXPECT_FALSE(m.Matches(nan1_));\n  EXPECT_FALSE(m.Matches(nan2_));\n  EXPECT_FALSE(m.Matches(1.0));\n}\n\nTEST_F(FloatTest, NanSensitiveFloatEqCanMatchNaN) {\n  // NanSensitiveFloatEq will match NaN.\n  Matcher<float> m = NanSensitiveFloatEq(nan1_);\n  EXPECT_TRUE(m.Matches(nan1_));\n  EXPECT_TRUE(m.Matches(nan2_));\n  EXPECT_FALSE(m.Matches(1.0));\n}\n\nTEST_F(FloatTest, FloatEqCanDescribeSelf) {\n  Matcher<float> m1 = FloatEq(2.0f);\n  EXPECT_EQ(\"is approximately 2\", Describe(m1));\n  EXPECT_EQ(\"isn't approximately 2\", DescribeNegation(m1));\n\n  Matcher<float> m2 = FloatEq(0.5f);\n  EXPECT_EQ(\"is approximately 0.5\", Describe(m2));\n  EXPECT_EQ(\"isn't approximately 0.5\", DescribeNegation(m2));\n\n  Matcher<float> m3 = FloatEq(nan1_);\n  EXPECT_EQ(\"never matches\", Describe(m3));\n  EXPECT_EQ(\"is anything\", DescribeNegation(m3));\n}\n\nTEST_F(FloatTest, NanSensitiveFloatEqCanDescribeSelf) {\n  Matcher<float> m1 = NanSensitiveFloatEq(2.0f);\n  EXPECT_EQ(\"is approximately 2\", Describe(m1));\n  EXPECT_EQ(\"isn't approximately 2\", DescribeNegation(m1));\n\n  Matcher<float> m2 = NanSensitiveFloatEq(0.5f);\n  EXPECT_EQ(\"is approximately 0.5\", Describe(m2));\n  EXPECT_EQ(\"isn't approximately 0.5\", DescribeNegation(m2));\n\n  Matcher<float> m3 = NanSensitiveFloatEq(nan1_);\n  EXPECT_EQ(\"is NaN\", Describe(m3));\n  EXPECT_EQ(\"isn't NaN\", DescribeNegation(m3));\n}\n\n// Instantiate FloatingPointTest for testing floats with a user-specified\n// max absolute error.\ntypedef FloatingPointNearTest<float> FloatNearTest;\n\nTEST_F(FloatNearTest, FloatNearMatches) { TestNearMatches(&FloatNear); }\n\nTEST_F(FloatNearTest, NanSensitiveFloatNearApproximatelyMatchesFloats) {\n  TestNearMatches(&NanSensitiveFloatNear);\n}\n\nTEST_F(FloatNearTest, FloatNearCanDescribeSelf) {\n  Matcher<float> m1 = FloatNear(2.0f, 0.5f);\n  EXPECT_EQ(\"is approximately 2 (absolute error <= 0.5)\", Describe(m1));\n  EXPECT_EQ(\"isn't approximately 2 (absolute error > 0.5)\",\n            DescribeNegation(m1));\n\n  Matcher<float> m2 = FloatNear(0.5f, 0.5f);\n  EXPECT_EQ(\"is approximately 0.5 (absolute error <= 0.5)\", Describe(m2));\n  EXPECT_EQ(\"isn't approximately 0.5 (absolute error > 0.5)\",\n            DescribeNegation(m2));\n\n  Matcher<float> m3 = FloatNear(nan1_, 0.0);\n  EXPECT_EQ(\"never matches\", Describe(m3));\n  EXPECT_EQ(\"is anything\", DescribeNegation(m3));\n}\n\nTEST_F(FloatNearTest, NanSensitiveFloatNearCanDescribeSelf) {\n  Matcher<float> m1 = NanSensitiveFloatNear(2.0f, 0.5f);\n  EXPECT_EQ(\"is approximately 2 (absolute error <= 0.5)\", Describe(m1));\n  EXPECT_EQ(\"isn't approximately 2 (absolute error > 0.5)\",\n            DescribeNegation(m1));\n\n  Matcher<float> m2 = NanSensitiveFloatNear(0.5f, 0.5f);\n  EXPECT_EQ(\"is approximately 0.5 (absolute error <= 0.5)\", Describe(m2));\n  EXPECT_EQ(\"isn't approximately 0.5 (absolute error > 0.5)\",\n            DescribeNegation(m2));\n\n  Matcher<float> m3 = NanSensitiveFloatNear(nan1_, 0.1f);\n  EXPECT_EQ(\"is NaN\", Describe(m3));\n  EXPECT_EQ(\"isn't NaN\", DescribeNegation(m3));\n}\n\nTEST_F(FloatNearTest, FloatNearCannotMatchNaN) {\n  // FloatNear never matches NaN.\n  Matcher<float> m = FloatNear(ParentType::nan1_, 0.1f);\n  EXPECT_FALSE(m.Matches(nan1_));\n  EXPECT_FALSE(m.Matches(nan2_));\n  EXPECT_FALSE(m.Matches(1.0));\n}\n\nTEST_F(FloatNearTest, NanSensitiveFloatNearCanMatchNaN) {\n  // NanSensitiveFloatNear will match NaN.\n  Matcher<float> m = NanSensitiveFloatNear(nan1_, 0.1f);\n  EXPECT_TRUE(m.Matches(nan1_));\n  EXPECT_TRUE(m.Matches(nan2_));\n  EXPECT_FALSE(m.Matches(1.0));\n}\n\n// Instantiate FloatingPointTest for testing doubles.\ntypedef FloatingPointTest<double> DoubleTest;\n\nTEST_F(DoubleTest, DoubleEqApproximatelyMatchesDoubles) {\n  TestMatches(&DoubleEq);\n}\n\nTEST_F(DoubleTest, NanSensitiveDoubleEqApproximatelyMatchesDoubles) {\n  TestMatches(&NanSensitiveDoubleEq);\n}\n\nTEST_F(DoubleTest, DoubleEqCannotMatchNaN) {\n  // DoubleEq never matches NaN.\n  Matcher<double> m = DoubleEq(nan1_);\n  EXPECT_FALSE(m.Matches(nan1_));\n  EXPECT_FALSE(m.Matches(nan2_));\n  EXPECT_FALSE(m.Matches(1.0));\n}\n\nTEST_F(DoubleTest, NanSensitiveDoubleEqCanMatchNaN) {\n  // NanSensitiveDoubleEq will match NaN.\n  Matcher<double> m = NanSensitiveDoubleEq(nan1_);\n  EXPECT_TRUE(m.Matches(nan1_));\n  EXPECT_TRUE(m.Matches(nan2_));\n  EXPECT_FALSE(m.Matches(1.0));\n}\n\nTEST_F(DoubleTest, DoubleEqCanDescribeSelf) {\n  Matcher<double> m1 = DoubleEq(2.0);\n  EXPECT_EQ(\"is approximately 2\", Describe(m1));\n  EXPECT_EQ(\"isn't approximately 2\", DescribeNegation(m1));\n\n  Matcher<double> m2 = DoubleEq(0.5);\n  EXPECT_EQ(\"is approximately 0.5\", Describe(m2));\n  EXPECT_EQ(\"isn't approximately 0.5\", DescribeNegation(m2));\n\n  Matcher<double> m3 = DoubleEq(nan1_);\n  EXPECT_EQ(\"never matches\", Describe(m3));\n  EXPECT_EQ(\"is anything\", DescribeNegation(m3));\n}\n\nTEST_F(DoubleTest, NanSensitiveDoubleEqCanDescribeSelf) {\n  Matcher<double> m1 = NanSensitiveDoubleEq(2.0);\n  EXPECT_EQ(\"is approximately 2\", Describe(m1));\n  EXPECT_EQ(\"isn't approximately 2\", DescribeNegation(m1));\n\n  Matcher<double> m2 = NanSensitiveDoubleEq(0.5);\n  EXPECT_EQ(\"is approximately 0.5\", Describe(m2));\n  EXPECT_EQ(\"isn't approximately 0.5\", DescribeNegation(m2));\n\n  Matcher<double> m3 = NanSensitiveDoubleEq(nan1_);\n  EXPECT_EQ(\"is NaN\", Describe(m3));\n  EXPECT_EQ(\"isn't NaN\", DescribeNegation(m3));\n}\n\n// Instantiate FloatingPointTest for testing floats with a user-specified\n// max absolute error.\ntypedef FloatingPointNearTest<double> DoubleNearTest;\n\nTEST_F(DoubleNearTest, DoubleNearMatches) { TestNearMatches(&DoubleNear); }\n\nTEST_F(DoubleNearTest, NanSensitiveDoubleNearApproximatelyMatchesDoubles) {\n  TestNearMatches(&NanSensitiveDoubleNear);\n}\n\nTEST_F(DoubleNearTest, DoubleNearCanDescribeSelf) {\n  Matcher<double> m1 = DoubleNear(2.0, 0.5);\n  EXPECT_EQ(\"is approximately 2 (absolute error <= 0.5)\", Describe(m1));\n  EXPECT_EQ(\"isn't approximately 2 (absolute error > 0.5)\",\n            DescribeNegation(m1));\n\n  Matcher<double> m2 = DoubleNear(0.5, 0.5);\n  EXPECT_EQ(\"is approximately 0.5 (absolute error <= 0.5)\", Describe(m2));\n  EXPECT_EQ(\"isn't approximately 0.5 (absolute error > 0.5)\",\n            DescribeNegation(m2));\n\n  Matcher<double> m3 = DoubleNear(nan1_, 0.0);\n  EXPECT_EQ(\"never matches\", Describe(m3));\n  EXPECT_EQ(\"is anything\", DescribeNegation(m3));\n}\n\nTEST_F(DoubleNearTest, ExplainsResultWhenMatchFails) {\n  EXPECT_EQ(\"\", Explain(DoubleNear(2.0, 0.1), 2.05));\n  EXPECT_EQ(\"which is 0.2 from 2\", Explain(DoubleNear(2.0, 0.1), 2.2));\n  EXPECT_EQ(\"which is -0.3 from 2\", Explain(DoubleNear(2.0, 0.1), 1.7));\n\n  const std::string explanation =\n      Explain(DoubleNear(2.1, 1e-10), 2.1 + 1.2e-10);\n  // Different C++ implementations may print floating-point numbers\n  // slightly differently.\n  EXPECT_TRUE(explanation == \"which is 1.2e-10 from 2.1\" ||  // GCC\n              explanation == \"which is 1.2e-010 from 2.1\")   // MSVC\n      << \" where explanation is \\\"\" << explanation << \"\\\".\";\n}\n\nTEST_F(DoubleNearTest, NanSensitiveDoubleNearCanDescribeSelf) {\n  Matcher<double> m1 = NanSensitiveDoubleNear(2.0, 0.5);\n  EXPECT_EQ(\"is approximately 2 (absolute error <= 0.5)\", Describe(m1));\n  EXPECT_EQ(\"isn't approximately 2 (absolute error > 0.5)\",\n            DescribeNegation(m1));\n\n  Matcher<double> m2 = NanSensitiveDoubleNear(0.5, 0.5);\n  EXPECT_EQ(\"is approximately 0.5 (absolute error <= 0.5)\", Describe(m2));\n  EXPECT_EQ(\"isn't approximately 0.5 (absolute error > 0.5)\",\n            DescribeNegation(m2));\n\n  Matcher<double> m3 = NanSensitiveDoubleNear(nan1_, 0.1);\n  EXPECT_EQ(\"is NaN\", Describe(m3));\n  EXPECT_EQ(\"isn't NaN\", DescribeNegation(m3));\n}\n\nTEST_F(DoubleNearTest, DoubleNearCannotMatchNaN) {\n  // DoubleNear never matches NaN.\n  Matcher<double> m = DoubleNear(ParentType::nan1_, 0.1);\n  EXPECT_FALSE(m.Matches(nan1_));\n  EXPECT_FALSE(m.Matches(nan2_));\n  EXPECT_FALSE(m.Matches(1.0));\n}\n\nTEST_F(DoubleNearTest, NanSensitiveDoubleNearCanMatchNaN) {\n  // NanSensitiveDoubleNear will match NaN.\n  Matcher<double> m = NanSensitiveDoubleNear(nan1_, 0.1);\n  EXPECT_TRUE(m.Matches(nan1_));\n  EXPECT_TRUE(m.Matches(nan2_));\n  EXPECT_FALSE(m.Matches(1.0));\n}\n\nTEST(NotTest, WorksOnMoveOnlyType) {\n  std::unique_ptr<int> p(new int(3));\n  EXPECT_THAT(p, Pointee(Eq(3)));\n  EXPECT_THAT(p, Not(Pointee(Eq(2))));\n}\n\nTEST(AllOfTest, HugeMatcher) {\n  // Verify that using AllOf with many arguments doesn't cause\n  // the compiler to exceed template instantiation depth limit.\n  EXPECT_THAT(0, testing::AllOf(_, _, _, _, _, _, _, _, _,\n                                testing::AllOf(_, _, _, _, _, _, _, _, _, _)));\n}\n\nTEST(AnyOfTest, HugeMatcher) {\n  // Verify that using AnyOf with many arguments doesn't cause\n  // the compiler to exceed template instantiation depth limit.\n  EXPECT_THAT(0, testing::AnyOf(_, _, _, _, _, _, _, _, _,\n                                testing::AnyOf(_, _, _, _, _, _, _, _, _, _)));\n}\n\nnamespace adl_test {\n\n// Verifies that the implementation of ::testing::AllOf and ::testing::AnyOf\n// don't issue unqualified recursive calls.  If they do, the argument dependent\n// name lookup will cause AllOf/AnyOf in the 'adl_test' namespace to be found\n// as a candidate and the compilation will break due to an ambiguous overload.\n\n// The matcher must be in the same namespace as AllOf/AnyOf to make argument\n// dependent lookup find those.\nMATCHER(M, \"\") {\n  (void)arg;\n  return true;\n}\n\ntemplate <typename T1, typename T2>\nbool AllOf(const T1& /*t1*/, const T2& /*t2*/) {\n  return true;\n}\n\nTEST(AllOfTest, DoesNotCallAllOfUnqualified) {\n  EXPECT_THAT(42,\n              testing::AllOf(M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));\n}\n\ntemplate <typename T1, typename T2>\nbool AnyOf(const T1&, const T2&) {\n  return true;\n}\n\nTEST(AnyOfTest, DoesNotCallAnyOfUnqualified) {\n  EXPECT_THAT(42,\n              testing::AnyOf(M(), M(), M(), M(), M(), M(), M(), M(), M(), M()));\n}\n\n}  // namespace adl_test\n\nTEST(AllOfTest, WorksOnMoveOnlyType) {\n  std::unique_ptr<int> p(new int(3));\n  EXPECT_THAT(p, AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(5))));\n  EXPECT_THAT(p, Not(AllOf(Pointee(Eq(3)), Pointee(Gt(0)), Pointee(Lt(3)))));\n}\n\nTEST(AnyOfTest, WorksOnMoveOnlyType) {\n  std::unique_ptr<int> p(new int(3));\n  EXPECT_THAT(p, AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Lt(5))));\n  EXPECT_THAT(p, Not(AnyOf(Pointee(Eq(5)), Pointee(Lt(0)), Pointee(Gt(5)))));\n}\n\n}  // namespace\n}  // namespace gmock_matchers_test\n}  // namespace testing\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock-matchers-comparisons_test.cc",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file tests some commonly used argument matchers.\n\n// Silence warning C4244: 'initializing': conversion from 'int' to 'short',\n// possible loss of data and C4100, unreferenced local parameter\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#pragma warning(disable : 4100)\n#endif\n\n#include \"test/gmock-matchers_test.h\"\n\nnamespace testing {\nnamespace gmock_matchers_test {\nnamespace {\n\nINSTANTIATE_GTEST_MATCHER_TEST_P(MonotonicMatcherTest);\n\nTEST_P(MonotonicMatcherTestP, IsPrintable) {\n  stringstream ss;\n  ss << GreaterThan(5);\n  EXPECT_EQ(\"is > 5\", ss.str());\n}\n\nTEST(MatchResultListenerTest, StreamingWorks) {\n  StringMatchResultListener listener;\n  listener << \"hi\" << 5;\n  EXPECT_EQ(\"hi5\", listener.str());\n\n  listener.Clear();\n  EXPECT_EQ(\"\", listener.str());\n\n  listener << 42;\n  EXPECT_EQ(\"42\", listener.str());\n\n  // Streaming shouldn't crash when the underlying ostream is NULL.\n  DummyMatchResultListener dummy;\n  dummy << \"hi\" << 5;\n}\n\nTEST(MatchResultListenerTest, CanAccessUnderlyingStream) {\n  EXPECT_TRUE(DummyMatchResultListener().stream() == nullptr);\n  EXPECT_TRUE(StreamMatchResultListener(nullptr).stream() == nullptr);\n\n  EXPECT_EQ(&std::cout, StreamMatchResultListener(&std::cout).stream());\n}\n\nTEST(MatchResultListenerTest, IsInterestedWorks) {\n  EXPECT_TRUE(StringMatchResultListener().IsInterested());\n  EXPECT_TRUE(StreamMatchResultListener(&std::cout).IsInterested());\n\n  EXPECT_FALSE(DummyMatchResultListener().IsInterested());\n  EXPECT_FALSE(StreamMatchResultListener(nullptr).IsInterested());\n}\n\n// Makes sure that the MatcherInterface<T> interface doesn't\n// change.\nclass EvenMatcherImpl : public MatcherInterface<int> {\n public:\n  bool MatchAndExplain(int x,\n                       MatchResultListener* /* listener */) const override {\n    return x % 2 == 0;\n  }\n\n  void DescribeTo(ostream* os) const override { *os << \"is an even number\"; }\n\n  // We deliberately don't define DescribeNegationTo() and\n  // ExplainMatchResultTo() here, to make sure the definition of these\n  // two methods is optional.\n};\n\n// Makes sure that the MatcherInterface API doesn't change.\nTEST(MatcherInterfaceTest, CanBeImplementedUsingPublishedAPI) {\n  EvenMatcherImpl m;\n}\n\n// Tests implementing a monomorphic matcher using MatchAndExplain().\n\nclass NewEvenMatcherImpl : public MatcherInterface<int> {\n public:\n  bool MatchAndExplain(int x, MatchResultListener* listener) const override {\n    const bool match = x % 2 == 0;\n    // Verifies that we can stream to a listener directly.\n    *listener << \"value % \" << 2;\n    if (listener->stream() != nullptr) {\n      // Verifies that we can stream to a listener's underlying stream\n      // too.\n      *listener->stream() << \" == \" << (x % 2);\n    }\n    return match;\n  }\n\n  void DescribeTo(ostream* os) const override { *os << \"is an even number\"; }\n};\n\nTEST(MatcherInterfaceTest, CanBeImplementedUsingNewAPI) {\n  Matcher<int> m = MakeMatcher(new NewEvenMatcherImpl);\n  EXPECT_TRUE(m.Matches(2));\n  EXPECT_FALSE(m.Matches(3));\n  EXPECT_EQ(\"value % 2 == 0\", Explain(m, 2));\n  EXPECT_EQ(\"value % 2 == 1\", Explain(m, 3));\n}\n\nINSTANTIATE_GTEST_MATCHER_TEST_P(MatcherTest);\n\n// Tests default-constructing a matcher.\nTEST(MatcherTest, CanBeDefaultConstructed) { Matcher<double> m; }\n\n// Tests that Matcher<T> can be constructed from a MatcherInterface<T>*.\nTEST(MatcherTest, CanBeConstructedFromMatcherInterface) {\n  const MatcherInterface<int>* impl = new EvenMatcherImpl;\n  Matcher<int> m(impl);\n  EXPECT_TRUE(m.Matches(4));\n  EXPECT_FALSE(m.Matches(5));\n}\n\n// Tests that value can be used in place of Eq(value).\nTEST(MatcherTest, CanBeImplicitlyConstructedFromValue) {\n  Matcher<int> m1 = 5;\n  EXPECT_TRUE(m1.Matches(5));\n  EXPECT_FALSE(m1.Matches(6));\n}\n\n// Tests that NULL can be used in place of Eq(NULL).\nTEST(MatcherTest, CanBeImplicitlyConstructedFromNULL) {\n  Matcher<int*> m1 = nullptr;\n  EXPECT_TRUE(m1.Matches(nullptr));\n  int n = 0;\n  EXPECT_FALSE(m1.Matches(&n));\n}\n\n// Tests that matchers can be constructed from a variable that is not properly\n// defined. This should be illegal, but many users rely on this accidentally.\nstruct Undefined {\n  virtual ~Undefined() = 0;\n  static const int kInt = 1;\n};\n\nTEST(MatcherTest, CanBeConstructedFromUndefinedVariable) {\n  Matcher<int> m1 = Undefined::kInt;\n  EXPECT_TRUE(m1.Matches(1));\n  EXPECT_FALSE(m1.Matches(2));\n}\n\n// Test that a matcher parameterized with an abstract class compiles.\nTEST(MatcherTest, CanAcceptAbstractClass) { Matcher<const Undefined&> m = _; }\n\n// Tests that matchers are copyable.\nTEST(MatcherTest, IsCopyable) {\n  // Tests the copy constructor.\n  Matcher<bool> m1 = Eq(false);\n  EXPECT_TRUE(m1.Matches(false));\n  EXPECT_FALSE(m1.Matches(true));\n\n  // Tests the assignment operator.\n  m1 = Eq(true);\n  EXPECT_TRUE(m1.Matches(true));\n  EXPECT_FALSE(m1.Matches(false));\n}\n\n// Tests that Matcher<T>::DescribeTo() calls\n// MatcherInterface<T>::DescribeTo().\nTEST(MatcherTest, CanDescribeItself) {\n  EXPECT_EQ(\"is an even number\", Describe(Matcher<int>(new EvenMatcherImpl)));\n}\n\n// Tests Matcher<T>::MatchAndExplain().\nTEST_P(MatcherTestP, MatchAndExplain) {\n  Matcher<int> m = GreaterThan(0);\n  StringMatchResultListener listener1;\n  EXPECT_TRUE(m.MatchAndExplain(42, &listener1));\n  EXPECT_EQ(\"which is 42 more than 0\", listener1.str());\n\n  StringMatchResultListener listener2;\n  EXPECT_FALSE(m.MatchAndExplain(-9, &listener2));\n  EXPECT_EQ(\"which is 9 less than 0\", listener2.str());\n}\n\n// Tests that a C-string literal can be implicitly converted to a\n// Matcher<std::string> or Matcher<const std::string&>.\nTEST(StringMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {\n  Matcher<std::string> m1 = \"hi\";\n  EXPECT_TRUE(m1.Matches(\"hi\"));\n  EXPECT_FALSE(m1.Matches(\"hello\"));\n\n  Matcher<const std::string&> m2 = \"hi\";\n  EXPECT_TRUE(m2.Matches(\"hi\"));\n  EXPECT_FALSE(m2.Matches(\"hello\"));\n}\n\n// Tests that a string object can be implicitly converted to a\n// Matcher<std::string> or Matcher<const std::string&>.\nTEST(StringMatcherTest, CanBeImplicitlyConstructedFromString) {\n  Matcher<std::string> m1 = std::string(\"hi\");\n  EXPECT_TRUE(m1.Matches(\"hi\"));\n  EXPECT_FALSE(m1.Matches(\"hello\"));\n\n  Matcher<const std::string&> m2 = std::string(\"hi\");\n  EXPECT_TRUE(m2.Matches(\"hi\"));\n  EXPECT_FALSE(m2.Matches(\"hello\"));\n}\n\n#if GTEST_INTERNAL_HAS_STRING_VIEW\n// Tests that a C-string literal can be implicitly converted to a\n// Matcher<StringView> or Matcher<const StringView&>.\nTEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromCStringLiteral) {\n  Matcher<internal::StringView> m1 = \"cats\";\n  EXPECT_TRUE(m1.Matches(\"cats\"));\n  EXPECT_FALSE(m1.Matches(\"dogs\"));\n\n  Matcher<const internal::StringView&> m2 = \"cats\";\n  EXPECT_TRUE(m2.Matches(\"cats\"));\n  EXPECT_FALSE(m2.Matches(\"dogs\"));\n}\n\n// Tests that a std::string object can be implicitly converted to a\n// Matcher<StringView> or Matcher<const StringView&>.\nTEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromString) {\n  Matcher<internal::StringView> m1 = std::string(\"cats\");\n  EXPECT_TRUE(m1.Matches(\"cats\"));\n  EXPECT_FALSE(m1.Matches(\"dogs\"));\n\n  Matcher<const internal::StringView&> m2 = std::string(\"cats\");\n  EXPECT_TRUE(m2.Matches(\"cats\"));\n  EXPECT_FALSE(m2.Matches(\"dogs\"));\n}\n\n// Tests that a StringView object can be implicitly converted to a\n// Matcher<StringView> or Matcher<const StringView&>.\nTEST(StringViewMatcherTest, CanBeImplicitlyConstructedFromStringView) {\n  Matcher<internal::StringView> m1 = internal::StringView(\"cats\");\n  EXPECT_TRUE(m1.Matches(\"cats\"));\n  EXPECT_FALSE(m1.Matches(\"dogs\"));\n\n  Matcher<const internal::StringView&> m2 = internal::StringView(\"cats\");\n  EXPECT_TRUE(m2.Matches(\"cats\"));\n  EXPECT_FALSE(m2.Matches(\"dogs\"));\n}\n#endif  // GTEST_INTERNAL_HAS_STRING_VIEW\n\n// Tests that a std::reference_wrapper<std::string> object can be implicitly\n// converted to a Matcher<std::string> or Matcher<const std::string&> via Eq().\nTEST(StringMatcherTest,\n     CanBeImplicitlyConstructedFromEqReferenceWrapperString) {\n  std::string value = \"cats\";\n  Matcher<std::string> m1 = Eq(std::ref(value));\n  EXPECT_TRUE(m1.Matches(\"cats\"));\n  EXPECT_FALSE(m1.Matches(\"dogs\"));\n\n  Matcher<const std::string&> m2 = Eq(std::ref(value));\n  EXPECT_TRUE(m2.Matches(\"cats\"));\n  EXPECT_FALSE(m2.Matches(\"dogs\"));\n}\n\n// Tests that MakeMatcher() constructs a Matcher<T> from a\n// MatcherInterface* without requiring the user to explicitly\n// write the type.\nTEST(MakeMatcherTest, ConstructsMatcherFromMatcherInterface) {\n  const MatcherInterface<int>* dummy_impl = new EvenMatcherImpl;\n  Matcher<int> m = MakeMatcher(dummy_impl);\n}\n\n// Tests that MakePolymorphicMatcher() can construct a polymorphic\n// matcher from its implementation using the old API.\nconst int g_bar = 1;\nclass ReferencesBarOrIsZeroImpl {\n public:\n  template <typename T>\n  bool MatchAndExplain(const T& x, MatchResultListener* /* listener */) const {\n    const void* p = &x;\n    return p == &g_bar || x == 0;\n  }\n\n  void DescribeTo(ostream* os) const { *os << \"g_bar or zero\"; }\n\n  void DescribeNegationTo(ostream* os) const {\n    *os << \"doesn't reference g_bar and is not zero\";\n  }\n};\n\n// This function verifies that MakePolymorphicMatcher() returns a\n// PolymorphicMatcher<T> where T is the argument's type.\nPolymorphicMatcher<ReferencesBarOrIsZeroImpl> ReferencesBarOrIsZero() {\n  return MakePolymorphicMatcher(ReferencesBarOrIsZeroImpl());\n}\n\nTEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingOldAPI) {\n  // Using a polymorphic matcher to match a reference type.\n  Matcher<const int&> m1 = ReferencesBarOrIsZero();\n  EXPECT_TRUE(m1.Matches(0));\n  // Verifies that the identity of a by-reference argument is preserved.\n  EXPECT_TRUE(m1.Matches(g_bar));\n  EXPECT_FALSE(m1.Matches(1));\n  EXPECT_EQ(\"g_bar or zero\", Describe(m1));\n\n  // Using a polymorphic matcher to match a value type.\n  Matcher<double> m2 = ReferencesBarOrIsZero();\n  EXPECT_TRUE(m2.Matches(0.0));\n  EXPECT_FALSE(m2.Matches(0.1));\n  EXPECT_EQ(\"g_bar or zero\", Describe(m2));\n}\n\n// Tests implementing a polymorphic matcher using MatchAndExplain().\n\nclass PolymorphicIsEvenImpl {\n public:\n  void DescribeTo(ostream* os) const { *os << \"is even\"; }\n\n  void DescribeNegationTo(ostream* os) const { *os << \"is odd\"; }\n\n  template <typename T>\n  bool MatchAndExplain(const T& x, MatchResultListener* listener) const {\n    // Verifies that we can stream to the listener directly.\n    *listener << \"% \" << 2;\n    if (listener->stream() != nullptr) {\n      // Verifies that we can stream to the listener's underlying stream\n      // too.\n      *listener->stream() << \" == \" << (x % 2);\n    }\n    return (x % 2) == 0;\n  }\n};\n\nPolymorphicMatcher<PolymorphicIsEvenImpl> PolymorphicIsEven() {\n  return MakePolymorphicMatcher(PolymorphicIsEvenImpl());\n}\n\nTEST(MakePolymorphicMatcherTest, ConstructsMatcherUsingNewAPI) {\n  // Using PolymorphicIsEven() as a Matcher<int>.\n  const Matcher<int> m1 = PolymorphicIsEven();\n  EXPECT_TRUE(m1.Matches(42));\n  EXPECT_FALSE(m1.Matches(43));\n  EXPECT_EQ(\"is even\", Describe(m1));\n\n  const Matcher<int> not_m1 = Not(m1);\n  EXPECT_EQ(\"is odd\", Describe(not_m1));\n\n  EXPECT_EQ(\"% 2 == 0\", Explain(m1, 42));\n\n  // Using PolymorphicIsEven() as a Matcher<char>.\n  const Matcher<char> m2 = PolymorphicIsEven();\n  EXPECT_TRUE(m2.Matches('\\x42'));\n  EXPECT_FALSE(m2.Matches('\\x43'));\n  EXPECT_EQ(\"is even\", Describe(m2));\n\n  const Matcher<char> not_m2 = Not(m2);\n  EXPECT_EQ(\"is odd\", Describe(not_m2));\n\n  EXPECT_EQ(\"% 2 == 0\", Explain(m2, '\\x42'));\n}\n\nINSTANTIATE_GTEST_MATCHER_TEST_P(MatcherCastTest);\n\n// Tests that MatcherCast<T>(m) works when m is a polymorphic matcher.\nTEST_P(MatcherCastTestP, FromPolymorphicMatcher) {\n  Matcher<int16_t> m;\n  if (use_gtest_matcher_) {\n    m = MatcherCast<int16_t>(GtestGreaterThan(int64_t{5}));\n  } else {\n    m = MatcherCast<int16_t>(Gt(int64_t{5}));\n  }\n  EXPECT_TRUE(m.Matches(6));\n  EXPECT_FALSE(m.Matches(4));\n}\n\n// For testing casting matchers between compatible types.\nclass IntValue {\n public:\n  // An int can be statically (although not implicitly) cast to a\n  // IntValue.\n  explicit IntValue(int a_value) : value_(a_value) {}\n\n  int value() const { return value_; }\n\n private:\n  int value_;\n};\n\n// For testing casting matchers between compatible types.\nbool IsPositiveIntValue(const IntValue& foo) { return foo.value() > 0; }\n\n// Tests that MatcherCast<T>(m) works when m is a Matcher<U> where T\n// can be statically converted to U.\nTEST(MatcherCastTest, FromCompatibleType) {\n  Matcher<double> m1 = Eq(2.0);\n  Matcher<int> m2 = MatcherCast<int>(m1);\n  EXPECT_TRUE(m2.Matches(2));\n  EXPECT_FALSE(m2.Matches(3));\n\n  Matcher<IntValue> m3 = Truly(IsPositiveIntValue);\n  Matcher<int> m4 = MatcherCast<int>(m3);\n  // In the following, the arguments 1 and 0 are statically converted\n  // to IntValue objects, and then tested by the IsPositiveIntValue()\n  // predicate.\n  EXPECT_TRUE(m4.Matches(1));\n  EXPECT_FALSE(m4.Matches(0));\n}\n\n// Tests that MatcherCast<T>(m) works when m is a Matcher<const T&>.\nTEST(MatcherCastTest, FromConstReferenceToNonReference) {\n  Matcher<const int&> m1 = Eq(0);\n  Matcher<int> m2 = MatcherCast<int>(m1);\n  EXPECT_TRUE(m2.Matches(0));\n  EXPECT_FALSE(m2.Matches(1));\n}\n\n// Tests that MatcherCast<T>(m) works when m is a Matcher<T&>.\nTEST(MatcherCastTest, FromReferenceToNonReference) {\n  Matcher<int&> m1 = Eq(0);\n  Matcher<int> m2 = MatcherCast<int>(m1);\n  EXPECT_TRUE(m2.Matches(0));\n  EXPECT_FALSE(m2.Matches(1));\n}\n\n// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.\nTEST(MatcherCastTest, FromNonReferenceToConstReference) {\n  Matcher<int> m1 = Eq(0);\n  Matcher<const int&> m2 = MatcherCast<const int&>(m1);\n  EXPECT_TRUE(m2.Matches(0));\n  EXPECT_FALSE(m2.Matches(1));\n}\n\n// Tests that MatcherCast<T&>(m) works when m is a Matcher<T>.\nTEST(MatcherCastTest, FromNonReferenceToReference) {\n  Matcher<int> m1 = Eq(0);\n  Matcher<int&> m2 = MatcherCast<int&>(m1);\n  int n = 0;\n  EXPECT_TRUE(m2.Matches(n));\n  n = 1;\n  EXPECT_FALSE(m2.Matches(n));\n}\n\n// Tests that MatcherCast<T>(m) works when m is a Matcher<T>.\nTEST(MatcherCastTest, FromSameType) {\n  Matcher<int> m1 = Eq(0);\n  Matcher<int> m2 = MatcherCast<int>(m1);\n  EXPECT_TRUE(m2.Matches(0));\n  EXPECT_FALSE(m2.Matches(1));\n}\n\n// Tests that MatcherCast<T>(m) works when m is a value of the same type as the\n// value type of the Matcher.\nTEST(MatcherCastTest, FromAValue) {\n  Matcher<int> m = MatcherCast<int>(42);\n  EXPECT_TRUE(m.Matches(42));\n  EXPECT_FALSE(m.Matches(239));\n}\n\n// Tests that MatcherCast<T>(m) works when m is a value of the type implicitly\n// convertible to the value type of the Matcher.\nTEST(MatcherCastTest, FromAnImplicitlyConvertibleValue) {\n  const int kExpected = 'c';\n  Matcher<int> m = MatcherCast<int>('c');\n  EXPECT_TRUE(m.Matches(kExpected));\n  EXPECT_FALSE(m.Matches(kExpected + 1));\n}\n\nstruct NonImplicitlyConstructibleTypeWithOperatorEq {\n  friend bool operator==(\n      const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */,\n      int rhs) {\n    return 42 == rhs;\n  }\n  friend bool operator==(\n      int lhs,\n      const NonImplicitlyConstructibleTypeWithOperatorEq& /* ignored */) {\n    return lhs == 42;\n  }\n};\n\n// Tests that MatcherCast<T>(m) works when m is a neither a matcher nor\n// implicitly convertible to the value type of the Matcher, but the value type\n// of the matcher has operator==() overload accepting m.\nTEST(MatcherCastTest, NonImplicitlyConstructibleTypeWithOperatorEq) {\n  Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m1 =\n      MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(42);\n  EXPECT_TRUE(m1.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));\n\n  Matcher<NonImplicitlyConstructibleTypeWithOperatorEq> m2 =\n      MatcherCast<NonImplicitlyConstructibleTypeWithOperatorEq>(239);\n  EXPECT_FALSE(m2.Matches(NonImplicitlyConstructibleTypeWithOperatorEq()));\n\n  // When updating the following lines please also change the comment to\n  // namespace convertible_from_any.\n  Matcher<int> m3 =\n      MatcherCast<int>(NonImplicitlyConstructibleTypeWithOperatorEq());\n  EXPECT_TRUE(m3.Matches(42));\n  EXPECT_FALSE(m3.Matches(239));\n}\n\n// ConvertibleFromAny does not work with MSVC. resulting in\n// error C2440: 'initializing': cannot convert from 'Eq' to 'M'\n// No constructor could take the source type, or constructor overload\n// resolution was ambiguous\n\n#if !defined _MSC_VER\n\n// The below ConvertibleFromAny struct is implicitly constructible from anything\n// and when in the same namespace can interact with other tests. In particular,\n// if it is in the same namespace as other tests and one removes\n//   NonImplicitlyConstructibleTypeWithOperatorEq::operator==(int lhs, ...);\n// then the corresponding test still compiles (and it should not!) by implicitly\n// converting NonImplicitlyConstructibleTypeWithOperatorEq to ConvertibleFromAny\n// in m3.Matcher().\nnamespace convertible_from_any {\n// Implicitly convertible from any type.\nstruct ConvertibleFromAny {\n  ConvertibleFromAny(int a_value) : value(a_value) {}\n  template <typename T>\n  ConvertibleFromAny(const T& /*a_value*/) : value(-1) {\n    ADD_FAILURE() << \"Conversion constructor called\";\n  }\n  int value;\n};\n\nbool operator==(const ConvertibleFromAny& a, const ConvertibleFromAny& b) {\n  return a.value == b.value;\n}\n\nostream& operator<<(ostream& os, const ConvertibleFromAny& a) {\n  return os << a.value;\n}\n\nTEST(MatcherCastTest, ConversionConstructorIsUsed) {\n  Matcher<ConvertibleFromAny> m = MatcherCast<ConvertibleFromAny>(1);\n  EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));\n  EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));\n}\n\nTEST(MatcherCastTest, FromConvertibleFromAny) {\n  Matcher<ConvertibleFromAny> m =\n      MatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));\n  EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));\n  EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));\n}\n}  // namespace convertible_from_any\n\n#endif  // !defined _MSC_VER\n\nstruct IntReferenceWrapper {\n  IntReferenceWrapper(const int& a_value) : value(&a_value) {}\n  const int* value;\n};\n\nbool operator==(const IntReferenceWrapper& a, const IntReferenceWrapper& b) {\n  return a.value == b.value;\n}\n\nTEST(MatcherCastTest, ValueIsNotCopied) {\n  int n = 42;\n  Matcher<IntReferenceWrapper> m = MatcherCast<IntReferenceWrapper>(n);\n  // Verify that the matcher holds a reference to n, not to its temporary copy.\n  EXPECT_TRUE(m.Matches(n));\n}\n\nclass Base {\n public:\n  virtual ~Base() {}\n  Base() {}\n\n private:\n  Base(const Base&) = delete;\n  Base& operator=(const Base&) = delete;\n};\n\nclass Derived : public Base {\n public:\n  Derived() : Base() {}\n  int i;\n};\n\nclass OtherDerived : public Base {};\n\nINSTANTIATE_GTEST_MATCHER_TEST_P(SafeMatcherCastTest);\n\n// Tests that SafeMatcherCast<T>(m) works when m is a polymorphic matcher.\nTEST_P(SafeMatcherCastTestP, FromPolymorphicMatcher) {\n  Matcher<char> m2;\n  if (use_gtest_matcher_) {\n    m2 = SafeMatcherCast<char>(GtestGreaterThan(32));\n  } else {\n    m2 = SafeMatcherCast<char>(Gt(32));\n  }\n  EXPECT_TRUE(m2.Matches('A'));\n  EXPECT_FALSE(m2.Matches('\\n'));\n}\n\n// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where\n// T and U are arithmetic types and T can be losslessly converted to\n// U.\nTEST(SafeMatcherCastTest, FromLosslesslyConvertibleArithmeticType) {\n  Matcher<double> m1 = DoubleEq(1.0);\n  Matcher<float> m2 = SafeMatcherCast<float>(m1);\n  EXPECT_TRUE(m2.Matches(1.0f));\n  EXPECT_FALSE(m2.Matches(2.0f));\n\n  Matcher<char> m3 = SafeMatcherCast<char>(TypedEq<int>('a'));\n  EXPECT_TRUE(m3.Matches('a'));\n  EXPECT_FALSE(m3.Matches('b'));\n}\n\n// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<U> where T and U\n// are pointers or references to a derived and a base class, correspondingly.\nTEST(SafeMatcherCastTest, FromBaseClass) {\n  Derived d, d2;\n  Matcher<Base*> m1 = Eq(&d);\n  Matcher<Derived*> m2 = SafeMatcherCast<Derived*>(m1);\n  EXPECT_TRUE(m2.Matches(&d));\n  EXPECT_FALSE(m2.Matches(&d2));\n\n  Matcher<Base&> m3 = Ref(d);\n  Matcher<Derived&> m4 = SafeMatcherCast<Derived&>(m3);\n  EXPECT_TRUE(m4.Matches(d));\n  EXPECT_FALSE(m4.Matches(d2));\n}\n\n// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<const T&>.\nTEST(SafeMatcherCastTest, FromConstReferenceToReference) {\n  int n = 0;\n  Matcher<const int&> m1 = Ref(n);\n  Matcher<int&> m2 = SafeMatcherCast<int&>(m1);\n  int n1 = 0;\n  EXPECT_TRUE(m2.Matches(n));\n  EXPECT_FALSE(m2.Matches(n1));\n}\n\n// Tests that MatcherCast<const T&>(m) works when m is a Matcher<T>.\nTEST(SafeMatcherCastTest, FromNonReferenceToConstReference) {\n  Matcher<std::unique_ptr<int>> m1 = IsNull();\n  Matcher<const std::unique_ptr<int>&> m2 =\n      SafeMatcherCast<const std::unique_ptr<int>&>(m1);\n  EXPECT_TRUE(m2.Matches(std::unique_ptr<int>()));\n  EXPECT_FALSE(m2.Matches(std::unique_ptr<int>(new int)));\n}\n\n// Tests that SafeMatcherCast<T&>(m) works when m is a Matcher<T>.\nTEST(SafeMatcherCastTest, FromNonReferenceToReference) {\n  Matcher<int> m1 = Eq(0);\n  Matcher<int&> m2 = SafeMatcherCast<int&>(m1);\n  int n = 0;\n  EXPECT_TRUE(m2.Matches(n));\n  n = 1;\n  EXPECT_FALSE(m2.Matches(n));\n}\n\n// Tests that SafeMatcherCast<T>(m) works when m is a Matcher<T>.\nTEST(SafeMatcherCastTest, FromSameType) {\n  Matcher<int> m1 = Eq(0);\n  Matcher<int> m2 = SafeMatcherCast<int>(m1);\n  EXPECT_TRUE(m2.Matches(0));\n  EXPECT_FALSE(m2.Matches(1));\n}\n\n#if !defined _MSC_VER\n\nnamespace convertible_from_any {\nTEST(SafeMatcherCastTest, ConversionConstructorIsUsed) {\n  Matcher<ConvertibleFromAny> m = SafeMatcherCast<ConvertibleFromAny>(1);\n  EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));\n  EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));\n}\n\nTEST(SafeMatcherCastTest, FromConvertibleFromAny) {\n  Matcher<ConvertibleFromAny> m =\n      SafeMatcherCast<ConvertibleFromAny>(Eq(ConvertibleFromAny(1)));\n  EXPECT_TRUE(m.Matches(ConvertibleFromAny(1)));\n  EXPECT_FALSE(m.Matches(ConvertibleFromAny(2)));\n}\n}  // namespace convertible_from_any\n\n#endif  // !defined _MSC_VER\n\nTEST(SafeMatcherCastTest, ValueIsNotCopied) {\n  int n = 42;\n  Matcher<IntReferenceWrapper> m = SafeMatcherCast<IntReferenceWrapper>(n);\n  // Verify that the matcher holds a reference to n, not to its temporary copy.\n  EXPECT_TRUE(m.Matches(n));\n}\n\nTEST(ExpectThat, TakesLiterals) {\n  EXPECT_THAT(1, 1);\n  EXPECT_THAT(1.0, 1.0);\n  EXPECT_THAT(std::string(), \"\");\n}\n\nTEST(ExpectThat, TakesFunctions) {\n  struct Helper {\n    static void Func() {}\n  };\n  void (*func)() = Helper::Func;\n  EXPECT_THAT(func, Helper::Func);\n  EXPECT_THAT(func, &Helper::Func);\n}\n\n// Tests that A<T>() matches any value of type T.\nTEST(ATest, MatchesAnyValue) {\n  // Tests a matcher for a value type.\n  Matcher<double> m1 = A<double>();\n  EXPECT_TRUE(m1.Matches(91.43));\n  EXPECT_TRUE(m1.Matches(-15.32));\n\n  // Tests a matcher for a reference type.\n  int a = 2;\n  int b = -6;\n  Matcher<int&> m2 = A<int&>();\n  EXPECT_TRUE(m2.Matches(a));\n  EXPECT_TRUE(m2.Matches(b));\n}\n\nTEST(ATest, WorksForDerivedClass) {\n  Base base;\n  Derived derived;\n  EXPECT_THAT(&base, A<Base*>());\n  // This shouldn't compile: EXPECT_THAT(&base, A<Derived*>());\n  EXPECT_THAT(&derived, A<Base*>());\n  EXPECT_THAT(&derived, A<Derived*>());\n}\n\n// Tests that A<T>() describes itself properly.\nTEST(ATest, CanDescribeSelf) { EXPECT_EQ(\"is anything\", Describe(A<bool>())); }\n\n// Tests that An<T>() matches any value of type T.\nTEST(AnTest, MatchesAnyValue) {\n  // Tests a matcher for a value type.\n  Matcher<int> m1 = An<int>();\n  EXPECT_TRUE(m1.Matches(9143));\n  EXPECT_TRUE(m1.Matches(-1532));\n\n  // Tests a matcher for a reference type.\n  int a = 2;\n  int b = -6;\n  Matcher<int&> m2 = An<int&>();\n  EXPECT_TRUE(m2.Matches(a));\n  EXPECT_TRUE(m2.Matches(b));\n}\n\n// Tests that An<T>() describes itself properly.\nTEST(AnTest, CanDescribeSelf) { EXPECT_EQ(\"is anything\", Describe(An<int>())); }\n\n// Tests that _ can be used as a matcher for any type and matches any\n// value of that type.\nTEST(UnderscoreTest, MatchesAnyValue) {\n  // Uses _ as a matcher for a value type.\n  Matcher<int> m1 = _;\n  EXPECT_TRUE(m1.Matches(123));\n  EXPECT_TRUE(m1.Matches(-242));\n\n  // Uses _ as a matcher for a reference type.\n  bool a = false;\n  const bool b = true;\n  Matcher<const bool&> m2 = _;\n  EXPECT_TRUE(m2.Matches(a));\n  EXPECT_TRUE(m2.Matches(b));\n}\n\n// Tests that _ describes itself properly.\nTEST(UnderscoreTest, CanDescribeSelf) {\n  Matcher<int> m = _;\n  EXPECT_EQ(\"is anything\", Describe(m));\n}\n\n// Tests that Eq(x) matches any value equal to x.\nTEST(EqTest, MatchesEqualValue) {\n  // 2 C-strings with same content but different addresses.\n  const char a1[] = \"hi\";\n  const char a2[] = \"hi\";\n\n  Matcher<const char*> m1 = Eq(a1);\n  EXPECT_TRUE(m1.Matches(a1));\n  EXPECT_FALSE(m1.Matches(a2));\n}\n\n// Tests that Eq(v) describes itself properly.\n\nclass Unprintable {\n public:\n  Unprintable() : c_('a') {}\n\n  bool operator==(const Unprintable& /* rhs */) const { return true; }\n  // -Wunused-private-field: dummy accessor for `c_`.\n  char dummy_c() { return c_; }\n\n private:\n  char c_;\n};\n\nTEST(EqTest, CanDescribeSelf) {\n  Matcher<Unprintable> m = Eq(Unprintable());\n  EXPECT_EQ(\"is equal to 1-byte object <61>\", Describe(m));\n}\n\n// Tests that Eq(v) can be used to match any type that supports\n// comparing with type T, where T is v's type.\nTEST(EqTest, IsPolymorphic) {\n  Matcher<int> m1 = Eq(1);\n  EXPECT_TRUE(m1.Matches(1));\n  EXPECT_FALSE(m1.Matches(2));\n\n  Matcher<char> m2 = Eq(1);\n  EXPECT_TRUE(m2.Matches('\\1'));\n  EXPECT_FALSE(m2.Matches('a'));\n}\n\n// Tests that TypedEq<T>(v) matches values of type T that's equal to v.\nTEST(TypedEqTest, ChecksEqualityForGivenType) {\n  Matcher<char> m1 = TypedEq<char>('a');\n  EXPECT_TRUE(m1.Matches('a'));\n  EXPECT_FALSE(m1.Matches('b'));\n\n  Matcher<int> m2 = TypedEq<int>(6);\n  EXPECT_TRUE(m2.Matches(6));\n  EXPECT_FALSE(m2.Matches(7));\n}\n\n// Tests that TypedEq(v) describes itself properly.\nTEST(TypedEqTest, CanDescribeSelf) {\n  EXPECT_EQ(\"is equal to 2\", Describe(TypedEq<int>(2)));\n}\n\n// Tests that TypedEq<T>(v) has type Matcher<T>.\n\n// Type<T>::IsTypeOf(v) compiles if and only if the type of value v is T, where\n// T is a \"bare\" type (i.e. not in the form of const U or U&).  If v's type is\n// not T, the compiler will generate a message about \"undefined reference\".\ntemplate <typename T>\nstruct Type {\n  static bool IsTypeOf(const T& /* v */) { return true; }\n\n  template <typename T2>\n  static void IsTypeOf(T2 v);\n};\n\nTEST(TypedEqTest, HasSpecifiedType) {\n  // Verfies that the type of TypedEq<T>(v) is Matcher<T>.\n  Type<Matcher<int>>::IsTypeOf(TypedEq<int>(5));\n  Type<Matcher<double>>::IsTypeOf(TypedEq<double>(5));\n}\n\n// Tests that Ge(v) matches anything >= v.\nTEST(GeTest, ImplementsGreaterThanOrEqual) {\n  Matcher<int> m1 = Ge(0);\n  EXPECT_TRUE(m1.Matches(1));\n  EXPECT_TRUE(m1.Matches(0));\n  EXPECT_FALSE(m1.Matches(-1));\n}\n\n// Tests that Ge(v) describes itself properly.\nTEST(GeTest, CanDescribeSelf) {\n  Matcher<int> m = Ge(5);\n  EXPECT_EQ(\"is >= 5\", Describe(m));\n}\n\n// Tests that Gt(v) matches anything > v.\nTEST(GtTest, ImplementsGreaterThan) {\n  Matcher<double> m1 = Gt(0);\n  EXPECT_TRUE(m1.Matches(1.0));\n  EXPECT_FALSE(m1.Matches(0.0));\n  EXPECT_FALSE(m1.Matches(-1.0));\n}\n\n// Tests that Gt(v) describes itself properly.\nTEST(GtTest, CanDescribeSelf) {\n  Matcher<int> m = Gt(5);\n  EXPECT_EQ(\"is > 5\", Describe(m));\n}\n\n// Tests that Le(v) matches anything <= v.\nTEST(LeTest, ImplementsLessThanOrEqual) {\n  Matcher<char> m1 = Le('b');\n  EXPECT_TRUE(m1.Matches('a'));\n  EXPECT_TRUE(m1.Matches('b'));\n  EXPECT_FALSE(m1.Matches('c'));\n}\n\n// Tests that Le(v) describes itself properly.\nTEST(LeTest, CanDescribeSelf) {\n  Matcher<int> m = Le(5);\n  EXPECT_EQ(\"is <= 5\", Describe(m));\n}\n\n// Tests that Lt(v) matches anything < v.\nTEST(LtTest, ImplementsLessThan) {\n  Matcher<const std::string&> m1 = Lt(\"Hello\");\n  EXPECT_TRUE(m1.Matches(\"Abc\"));\n  EXPECT_FALSE(m1.Matches(\"Hello\"));\n  EXPECT_FALSE(m1.Matches(\"Hello, world!\"));\n}\n\n// Tests that Lt(v) describes itself properly.\nTEST(LtTest, CanDescribeSelf) {\n  Matcher<int> m = Lt(5);\n  EXPECT_EQ(\"is < 5\", Describe(m));\n}\n\n// Tests that Ne(v) matches anything != v.\nTEST(NeTest, ImplementsNotEqual) {\n  Matcher<int> m1 = Ne(0);\n  EXPECT_TRUE(m1.Matches(1));\n  EXPECT_TRUE(m1.Matches(-1));\n  EXPECT_FALSE(m1.Matches(0));\n}\n\n// Tests that Ne(v) describes itself properly.\nTEST(NeTest, CanDescribeSelf) {\n  Matcher<int> m = Ne(5);\n  EXPECT_EQ(\"isn't equal to 5\", Describe(m));\n}\n\nclass MoveOnly {\n public:\n  explicit MoveOnly(int i) : i_(i) {}\n  MoveOnly(const MoveOnly&) = delete;\n  MoveOnly(MoveOnly&&) = default;\n  MoveOnly& operator=(const MoveOnly&) = delete;\n  MoveOnly& operator=(MoveOnly&&) = default;\n\n  bool operator==(const MoveOnly& other) const { return i_ == other.i_; }\n  bool operator!=(const MoveOnly& other) const { return i_ != other.i_; }\n  bool operator<(const MoveOnly& other) const { return i_ < other.i_; }\n  bool operator<=(const MoveOnly& other) const { return i_ <= other.i_; }\n  bool operator>(const MoveOnly& other) const { return i_ > other.i_; }\n  bool operator>=(const MoveOnly& other) const { return i_ >= other.i_; }\n\n private:\n  int i_;\n};\n\nstruct MoveHelper {\n  MOCK_METHOD1(Call, void(MoveOnly));\n};\n\n// Disable this test in VS 2015 (version 14), where it fails when SEH is enabled\n#if defined(_MSC_VER) && (_MSC_VER < 1910)\nTEST(ComparisonBaseTest, DISABLED_WorksWithMoveOnly) {\n#else\nTEST(ComparisonBaseTest, WorksWithMoveOnly) {\n#endif\n  MoveOnly m{0};\n  MoveHelper helper;\n\n  EXPECT_CALL(helper, Call(Eq(ByRef(m))));\n  helper.Call(MoveOnly(0));\n  EXPECT_CALL(helper, Call(Ne(ByRef(m))));\n  helper.Call(MoveOnly(1));\n  EXPECT_CALL(helper, Call(Le(ByRef(m))));\n  helper.Call(MoveOnly(0));\n  EXPECT_CALL(helper, Call(Lt(ByRef(m))));\n  helper.Call(MoveOnly(-1));\n  EXPECT_CALL(helper, Call(Ge(ByRef(m))));\n  helper.Call(MoveOnly(0));\n  EXPECT_CALL(helper, Call(Gt(ByRef(m))));\n  helper.Call(MoveOnly(1));\n}\n\n// Tests that IsNull() matches any NULL pointer of any type.\nTEST(IsNullTest, MatchesNullPointer) {\n  Matcher<int*> m1 = IsNull();\n  int* p1 = nullptr;\n  int n = 0;\n  EXPECT_TRUE(m1.Matches(p1));\n  EXPECT_FALSE(m1.Matches(&n));\n\n  Matcher<const char*> m2 = IsNull();\n  const char* p2 = nullptr;\n  EXPECT_TRUE(m2.Matches(p2));\n  EXPECT_FALSE(m2.Matches(\"hi\"));\n\n  Matcher<void*> m3 = IsNull();\n  void* p3 = nullptr;\n  EXPECT_TRUE(m3.Matches(p3));\n  EXPECT_FALSE(m3.Matches(reinterpret_cast<void*>(0xbeef)));\n}\n\nTEST(IsNullTest, StdFunction) {\n  const Matcher<std::function<void()>> m = IsNull();\n\n  EXPECT_TRUE(m.Matches(std::function<void()>()));\n  EXPECT_FALSE(m.Matches([] {}));\n}\n\n// Tests that IsNull() describes itself properly.\nTEST(IsNullTest, CanDescribeSelf) {\n  Matcher<int*> m = IsNull();\n  EXPECT_EQ(\"is NULL\", Describe(m));\n  EXPECT_EQ(\"isn't NULL\", DescribeNegation(m));\n}\n\n// Tests that NotNull() matches any non-NULL pointer of any type.\nTEST(NotNullTest, MatchesNonNullPointer) {\n  Matcher<int*> m1 = NotNull();\n  int* p1 = nullptr;\n  int n = 0;\n  EXPECT_FALSE(m1.Matches(p1));\n  EXPECT_TRUE(m1.Matches(&n));\n\n  Matcher<const char*> m2 = NotNull();\n  const char* p2 = nullptr;\n  EXPECT_FALSE(m2.Matches(p2));\n  EXPECT_TRUE(m2.Matches(\"hi\"));\n}\n\nTEST(NotNullTest, LinkedPtr) {\n  const Matcher<std::shared_ptr<int>> m = NotNull();\n  const std::shared_ptr<int> null_p;\n  const std::shared_ptr<int> non_null_p(new int);\n\n  EXPECT_FALSE(m.Matches(null_p));\n  EXPECT_TRUE(m.Matches(non_null_p));\n}\n\nTEST(NotNullTest, ReferenceToConstLinkedPtr) {\n  const Matcher<const std::shared_ptr<double>&> m = NotNull();\n  const std::shared_ptr<double> null_p;\n  const std::shared_ptr<double> non_null_p(new double);\n\n  EXPECT_FALSE(m.Matches(null_p));\n  EXPECT_TRUE(m.Matches(non_null_p));\n}\n\nTEST(NotNullTest, StdFunction) {\n  const Matcher<std::function<void()>> m = NotNull();\n\n  EXPECT_TRUE(m.Matches([] {}));\n  EXPECT_FALSE(m.Matches(std::function<void()>()));\n}\n\n// Tests that NotNull() describes itself properly.\nTEST(NotNullTest, CanDescribeSelf) {\n  Matcher<int*> m = NotNull();\n  EXPECT_EQ(\"isn't NULL\", Describe(m));\n}\n\n// Tests that Ref(variable) matches an argument that references\n// 'variable'.\nTEST(RefTest, MatchesSameVariable) {\n  int a = 0;\n  int b = 0;\n  Matcher<int&> m = Ref(a);\n  EXPECT_TRUE(m.Matches(a));\n  EXPECT_FALSE(m.Matches(b));\n}\n\n// Tests that Ref(variable) describes itself properly.\nTEST(RefTest, CanDescribeSelf) {\n  int n = 5;\n  Matcher<int&> m = Ref(n);\n  stringstream ss;\n  ss << \"references the variable @\" << &n << \" 5\";\n  EXPECT_EQ(ss.str(), Describe(m));\n}\n\n// Test that Ref(non_const_varialbe) can be used as a matcher for a\n// const reference.\nTEST(RefTest, CanBeUsedAsMatcherForConstReference) {\n  int a = 0;\n  int b = 0;\n  Matcher<const int&> m = Ref(a);\n  EXPECT_TRUE(m.Matches(a));\n  EXPECT_FALSE(m.Matches(b));\n}\n\n// Tests that Ref(variable) is covariant, i.e. Ref(derived) can be\n// used wherever Ref(base) can be used (Ref(derived) is a sub-type\n// of Ref(base), but not vice versa.\n\nTEST(RefTest, IsCovariant) {\n  Base base, base2;\n  Derived derived;\n  Matcher<const Base&> m1 = Ref(base);\n  EXPECT_TRUE(m1.Matches(base));\n  EXPECT_FALSE(m1.Matches(base2));\n  EXPECT_FALSE(m1.Matches(derived));\n\n  m1 = Ref(derived);\n  EXPECT_TRUE(m1.Matches(derived));\n  EXPECT_FALSE(m1.Matches(base));\n  EXPECT_FALSE(m1.Matches(base2));\n}\n\nTEST(RefTest, ExplainsResult) {\n  int n = 0;\n  EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), n),\n              StartsWith(\"which is located @\"));\n\n  int m = 0;\n  EXPECT_THAT(Explain(Matcher<const int&>(Ref(n)), m),\n              StartsWith(\"which is located @\"));\n}\n\n// Tests string comparison matchers.\n\ntemplate <typename T = std::string>\nstd::string FromStringLike(internal::StringLike<T> str) {\n  return std::string(str);\n}\n\nTEST(StringLike, TestConversions) {\n  EXPECT_EQ(\"foo\", FromStringLike(\"foo\"));\n  EXPECT_EQ(\"foo\", FromStringLike(std::string(\"foo\")));\n#if GTEST_INTERNAL_HAS_STRING_VIEW\n  EXPECT_EQ(\"foo\", FromStringLike(internal::StringView(\"foo\")));\n#endif  // GTEST_INTERNAL_HAS_STRING_VIEW\n\n  // Non deducible types.\n  EXPECT_EQ(\"\", FromStringLike({}));\n  EXPECT_EQ(\"foo\", FromStringLike({'f', 'o', 'o'}));\n  const char buf[] = \"foo\";\n  EXPECT_EQ(\"foo\", FromStringLike({buf, buf + 3}));\n}\n\nTEST(StrEqTest, MatchesEqualString) {\n  Matcher<const char*> m = StrEq(std::string(\"Hello\"));\n  EXPECT_TRUE(m.Matches(\"Hello\"));\n  EXPECT_FALSE(m.Matches(\"hello\"));\n  EXPECT_FALSE(m.Matches(nullptr));\n\n  Matcher<const std::string&> m2 = StrEq(\"Hello\");\n  EXPECT_TRUE(m2.Matches(\"Hello\"));\n  EXPECT_FALSE(m2.Matches(\"Hi\"));\n\n#if GTEST_INTERNAL_HAS_STRING_VIEW\n  Matcher<const internal::StringView&> m3 =\n      StrEq(internal::StringView(\"Hello\"));\n  EXPECT_TRUE(m3.Matches(internal::StringView(\"Hello\")));\n  EXPECT_FALSE(m3.Matches(internal::StringView(\"hello\")));\n  EXPECT_FALSE(m3.Matches(internal::StringView()));\n\n  Matcher<const internal::StringView&> m_empty = StrEq(\"\");\n  EXPECT_TRUE(m_empty.Matches(internal::StringView(\"\")));\n  EXPECT_TRUE(m_empty.Matches(internal::StringView()));\n  EXPECT_FALSE(m_empty.Matches(internal::StringView(\"hello\")));\n#endif  // GTEST_INTERNAL_HAS_STRING_VIEW\n}\n\nTEST(StrEqTest, CanDescribeSelf) {\n  Matcher<std::string> m = StrEq(\"Hi-\\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\xD3\");\n  EXPECT_EQ(\"is equal to \\\"Hi-\\'\\\\\\\"?\\\\\\\\\\\\a\\\\b\\\\f\\\\n\\\\r\\\\t\\\\v\\\\xD3\\\"\",\n            Describe(m));\n\n  std::string str(\"01204500800\");\n  str[3] = '\\0';\n  Matcher<std::string> m2 = StrEq(str);\n  EXPECT_EQ(\"is equal to \\\"012\\\\04500800\\\"\", Describe(m2));\n  str[0] = str[6] = str[7] = str[9] = str[10] = '\\0';\n  Matcher<std::string> m3 = StrEq(str);\n  EXPECT_EQ(\"is equal to \\\"\\\\012\\\\045\\\\0\\\\08\\\\0\\\\0\\\"\", Describe(m3));\n}\n\nTEST(StrNeTest, MatchesUnequalString) {\n  Matcher<const char*> m = StrNe(\"Hello\");\n  EXPECT_TRUE(m.Matches(\"\"));\n  EXPECT_TRUE(m.Matches(nullptr));\n  EXPECT_FALSE(m.Matches(\"Hello\"));\n\n  Matcher<std::string> m2 = StrNe(std::string(\"Hello\"));\n  EXPECT_TRUE(m2.Matches(\"hello\"));\n  EXPECT_FALSE(m2.Matches(\"Hello\"));\n\n#if GTEST_INTERNAL_HAS_STRING_VIEW\n  Matcher<const internal::StringView> m3 = StrNe(internal::StringView(\"Hello\"));\n  EXPECT_TRUE(m3.Matches(internal::StringView(\"\")));\n  EXPECT_TRUE(m3.Matches(internal::StringView()));\n  EXPECT_FALSE(m3.Matches(internal::StringView(\"Hello\")));\n#endif  // GTEST_INTERNAL_HAS_STRING_VIEW\n}\n\nTEST(StrNeTest, CanDescribeSelf) {\n  Matcher<const char*> m = StrNe(\"Hi\");\n  EXPECT_EQ(\"isn't equal to \\\"Hi\\\"\", Describe(m));\n}\n\nTEST(StrCaseEqTest, MatchesEqualStringIgnoringCase) {\n  Matcher<const char*> m = StrCaseEq(std::string(\"Hello\"));\n  EXPECT_TRUE(m.Matches(\"Hello\"));\n  EXPECT_TRUE(m.Matches(\"hello\"));\n  EXPECT_FALSE(m.Matches(\"Hi\"));\n  EXPECT_FALSE(m.Matches(nullptr));\n\n  Matcher<const std::string&> m2 = StrCaseEq(\"Hello\");\n  EXPECT_TRUE(m2.Matches(\"hello\"));\n  EXPECT_FALSE(m2.Matches(\"Hi\"));\n\n#if GTEST_INTERNAL_HAS_STRING_VIEW\n  Matcher<const internal::StringView&> m3 =\n      StrCaseEq(internal::StringView(\"Hello\"));\n  EXPECT_TRUE(m3.Matches(internal::StringView(\"Hello\")));\n  EXPECT_TRUE(m3.Matches(internal::StringView(\"hello\")));\n  EXPECT_FALSE(m3.Matches(internal::StringView(\"Hi\")));\n  EXPECT_FALSE(m3.Matches(internal::StringView()));\n#endif  // GTEST_INTERNAL_HAS_STRING_VIEW\n}\n\nTEST(StrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {\n  std::string str1(\"oabocdooeoo\");\n  std::string str2(\"OABOCDOOEOO\");\n  Matcher<const std::string&> m0 = StrCaseEq(str1);\n  EXPECT_FALSE(m0.Matches(str2 + std::string(1, '\\0')));\n\n  str1[3] = str2[3] = '\\0';\n  Matcher<const std::string&> m1 = StrCaseEq(str1);\n  EXPECT_TRUE(m1.Matches(str2));\n\n  str1[0] = str1[6] = str1[7] = str1[10] = '\\0';\n  str2[0] = str2[6] = str2[7] = str2[10] = '\\0';\n  Matcher<const std::string&> m2 = StrCaseEq(str1);\n  str1[9] = str2[9] = '\\0';\n  EXPECT_FALSE(m2.Matches(str2));\n\n  Matcher<const std::string&> m3 = StrCaseEq(str1);\n  EXPECT_TRUE(m3.Matches(str2));\n\n  EXPECT_FALSE(m3.Matches(str2 + \"x\"));\n  str2.append(1, '\\0');\n  EXPECT_FALSE(m3.Matches(str2));\n  EXPECT_FALSE(m3.Matches(std::string(str2, 0, 9)));\n}\n\nTEST(StrCaseEqTest, CanDescribeSelf) {\n  Matcher<std::string> m = StrCaseEq(\"Hi\");\n  EXPECT_EQ(\"is equal to (ignoring case) \\\"Hi\\\"\", Describe(m));\n}\n\nTEST(StrCaseNeTest, MatchesUnequalStringIgnoringCase) {\n  Matcher<const char*> m = StrCaseNe(\"Hello\");\n  EXPECT_TRUE(m.Matches(\"Hi\"));\n  EXPECT_TRUE(m.Matches(nullptr));\n  EXPECT_FALSE(m.Matches(\"Hello\"));\n  EXPECT_FALSE(m.Matches(\"hello\"));\n\n  Matcher<std::string> m2 = StrCaseNe(std::string(\"Hello\"));\n  EXPECT_TRUE(m2.Matches(\"\"));\n  EXPECT_FALSE(m2.Matches(\"Hello\"));\n\n#if GTEST_INTERNAL_HAS_STRING_VIEW\n  Matcher<const internal::StringView> m3 =\n      StrCaseNe(internal::StringView(\"Hello\"));\n  EXPECT_TRUE(m3.Matches(internal::StringView(\"Hi\")));\n  EXPECT_TRUE(m3.Matches(internal::StringView()));\n  EXPECT_FALSE(m3.Matches(internal::StringView(\"Hello\")));\n  EXPECT_FALSE(m3.Matches(internal::StringView(\"hello\")));\n#endif  // GTEST_INTERNAL_HAS_STRING_VIEW\n}\n\nTEST(StrCaseNeTest, CanDescribeSelf) {\n  Matcher<const char*> m = StrCaseNe(\"Hi\");\n  EXPECT_EQ(\"isn't equal to (ignoring case) \\\"Hi\\\"\", Describe(m));\n}\n\n// Tests that HasSubstr() works for matching string-typed values.\nTEST(HasSubstrTest, WorksForStringClasses) {\n  const Matcher<std::string> m1 = HasSubstr(\"foo\");\n  EXPECT_TRUE(m1.Matches(std::string(\"I love food.\")));\n  EXPECT_FALSE(m1.Matches(std::string(\"tofo\")));\n\n  const Matcher<const std::string&> m2 = HasSubstr(\"foo\");\n  EXPECT_TRUE(m2.Matches(std::string(\"I love food.\")));\n  EXPECT_FALSE(m2.Matches(std::string(\"tofo\")));\n\n  const Matcher<std::string> m_empty = HasSubstr(\"\");\n  EXPECT_TRUE(m_empty.Matches(std::string()));\n  EXPECT_TRUE(m_empty.Matches(std::string(\"not empty\")));\n}\n\n// Tests that HasSubstr() works for matching C-string-typed values.\nTEST(HasSubstrTest, WorksForCStrings) {\n  const Matcher<char*> m1 = HasSubstr(\"foo\");\n  EXPECT_TRUE(m1.Matches(const_cast<char*>(\"I love food.\")));\n  EXPECT_FALSE(m1.Matches(const_cast<char*>(\"tofo\")));\n  EXPECT_FALSE(m1.Matches(nullptr));\n\n  const Matcher<const char*> m2 = HasSubstr(\"foo\");\n  EXPECT_TRUE(m2.Matches(\"I love food.\"));\n  EXPECT_FALSE(m2.Matches(\"tofo\"));\n  EXPECT_FALSE(m2.Matches(nullptr));\n\n  const Matcher<const char*> m_empty = HasSubstr(\"\");\n  EXPECT_TRUE(m_empty.Matches(\"not empty\"));\n  EXPECT_TRUE(m_empty.Matches(\"\"));\n  EXPECT_FALSE(m_empty.Matches(nullptr));\n}\n\n#if GTEST_INTERNAL_HAS_STRING_VIEW\n// Tests that HasSubstr() works for matching StringView-typed values.\nTEST(HasSubstrTest, WorksForStringViewClasses) {\n  const Matcher<internal::StringView> m1 =\n      HasSubstr(internal::StringView(\"foo\"));\n  EXPECT_TRUE(m1.Matches(internal::StringView(\"I love food.\")));\n  EXPECT_FALSE(m1.Matches(internal::StringView(\"tofo\")));\n  EXPECT_FALSE(m1.Matches(internal::StringView()));\n\n  const Matcher<const internal::StringView&> m2 = HasSubstr(\"foo\");\n  EXPECT_TRUE(m2.Matches(internal::StringView(\"I love food.\")));\n  EXPECT_FALSE(m2.Matches(internal::StringView(\"tofo\")));\n  EXPECT_FALSE(m2.Matches(internal::StringView()));\n\n  const Matcher<const internal::StringView&> m3 = HasSubstr(\"\");\n  EXPECT_TRUE(m3.Matches(internal::StringView(\"foo\")));\n  EXPECT_TRUE(m3.Matches(internal::StringView(\"\")));\n  EXPECT_TRUE(m3.Matches(internal::StringView()));\n}\n#endif  // GTEST_INTERNAL_HAS_STRING_VIEW\n\n// Tests that HasSubstr(s) describes itself properly.\nTEST(HasSubstrTest, CanDescribeSelf) {\n  Matcher<std::string> m = HasSubstr(\"foo\\n\\\"\");\n  EXPECT_EQ(\"has substring \\\"foo\\\\n\\\\\\\"\\\"\", Describe(m));\n}\n\nINSTANTIATE_GTEST_MATCHER_TEST_P(KeyTest);\n\nTEST(KeyTest, CanDescribeSelf) {\n  Matcher<const pair<std::string, int>&> m = Key(\"foo\");\n  EXPECT_EQ(\"has a key that is equal to \\\"foo\\\"\", Describe(m));\n  EXPECT_EQ(\"doesn't have a key that is equal to \\\"foo\\\"\", DescribeNegation(m));\n}\n\nTEST_P(KeyTestP, ExplainsResult) {\n  Matcher<pair<int, bool>> m = Key(GreaterThan(10));\n  EXPECT_EQ(\"whose first field is a value which is 5 less than 10\",\n            Explain(m, make_pair(5, true)));\n  EXPECT_EQ(\"whose first field is a value which is 5 more than 10\",\n            Explain(m, make_pair(15, true)));\n}\n\nTEST(KeyTest, MatchesCorrectly) {\n  pair<int, std::string> p(25, \"foo\");\n  EXPECT_THAT(p, Key(25));\n  EXPECT_THAT(p, Not(Key(42)));\n  EXPECT_THAT(p, Key(Ge(20)));\n  EXPECT_THAT(p, Not(Key(Lt(25))));\n}\n\nTEST(KeyTest, WorksWithMoveOnly) {\n  pair<std::unique_ptr<int>, std::unique_ptr<int>> p;\n  EXPECT_THAT(p, Key(Eq(nullptr)));\n}\n\nINSTANTIATE_GTEST_MATCHER_TEST_P(PairTest);\n\ntemplate <size_t I>\nstruct Tag {};\n\nstruct PairWithGet {\n  int member_1;\n  std::string member_2;\n  using first_type = int;\n  using second_type = std::string;\n\n  const int& GetImpl(Tag<0>) const { return member_1; }\n  const std::string& GetImpl(Tag<1>) const { return member_2; }\n};\ntemplate <size_t I>\nauto get(const PairWithGet& value) -> decltype(value.GetImpl(Tag<I>())) {\n  return value.GetImpl(Tag<I>());\n}\nTEST(PairTest, MatchesPairWithGetCorrectly) {\n  PairWithGet p{25, \"foo\"};\n  EXPECT_THAT(p, Key(25));\n  EXPECT_THAT(p, Not(Key(42)));\n  EXPECT_THAT(p, Key(Ge(20)));\n  EXPECT_THAT(p, Not(Key(Lt(25))));\n\n  std::vector<PairWithGet> v = {{11, \"Foo\"}, {29, \"gMockIsBestMock\"}};\n  EXPECT_THAT(v, Contains(Key(29)));\n}\n\nTEST(KeyTest, SafelyCastsInnerMatcher) {\n  Matcher<int> is_positive = Gt(0);\n  Matcher<int> is_negative = Lt(0);\n  pair<char, bool> p('a', true);\n  EXPECT_THAT(p, Key(is_positive));\n  EXPECT_THAT(p, Not(Key(is_negative)));\n}\n\nTEST(KeyTest, InsideContainsUsingMap) {\n  map<int, char> container;\n  container.insert(make_pair(1, 'a'));\n  container.insert(make_pair(2, 'b'));\n  container.insert(make_pair(4, 'c'));\n  EXPECT_THAT(container, Contains(Key(1)));\n  EXPECT_THAT(container, Not(Contains(Key(3))));\n}\n\nTEST(KeyTest, InsideContainsUsingMultimap) {\n  multimap<int, char> container;\n  container.insert(make_pair(1, 'a'));\n  container.insert(make_pair(2, 'b'));\n  container.insert(make_pair(4, 'c'));\n\n  EXPECT_THAT(container, Not(Contains(Key(25))));\n  container.insert(make_pair(25, 'd'));\n  EXPECT_THAT(container, Contains(Key(25)));\n  container.insert(make_pair(25, 'e'));\n  EXPECT_THAT(container, Contains(Key(25)));\n\n  EXPECT_THAT(container, Contains(Key(1)));\n  EXPECT_THAT(container, Not(Contains(Key(3))));\n}\n\nTEST(PairTest, Typing) {\n  // Test verifies the following type conversions can be compiled.\n  Matcher<const pair<const char*, int>&> m1 = Pair(\"foo\", 42);\n  Matcher<const pair<const char*, int>> m2 = Pair(\"foo\", 42);\n  Matcher<pair<const char*, int>> m3 = Pair(\"foo\", 42);\n\n  Matcher<pair<int, const std::string>> m4 = Pair(25, \"42\");\n  Matcher<pair<const std::string, int>> m5 = Pair(\"25\", 42);\n}\n\nTEST(PairTest, CanDescribeSelf) {\n  Matcher<const pair<std::string, int>&> m1 = Pair(\"foo\", 42);\n  EXPECT_EQ(\n      \"has a first field that is equal to \\\"foo\\\"\"\n      \", and has a second field that is equal to 42\",\n      Describe(m1));\n  EXPECT_EQ(\n      \"has a first field that isn't equal to \\\"foo\\\"\"\n      \", or has a second field that isn't equal to 42\",\n      DescribeNegation(m1));\n  // Double and triple negation (1 or 2 times not and description of negation).\n  Matcher<const pair<int, int>&> m2 = Not(Pair(Not(13), 42));\n  EXPECT_EQ(\n      \"has a first field that isn't equal to 13\"\n      \", and has a second field that is equal to 42\",\n      DescribeNegation(m2));\n}\n\nTEST_P(PairTestP, CanExplainMatchResultTo) {\n  // If neither field matches, Pair() should explain about the first\n  // field.\n  const Matcher<pair<int, int>> m = Pair(GreaterThan(0), GreaterThan(0));\n  EXPECT_EQ(\"whose first field does not match, which is 1 less than 0\",\n            Explain(m, make_pair(-1, -2)));\n\n  // If the first field matches but the second doesn't, Pair() should\n  // explain about the second field.\n  EXPECT_EQ(\"whose second field does not match, which is 2 less than 0\",\n            Explain(m, make_pair(1, -2)));\n\n  // If the first field doesn't match but the second does, Pair()\n  // should explain about the first field.\n  EXPECT_EQ(\"whose first field does not match, which is 1 less than 0\",\n            Explain(m, make_pair(-1, 2)));\n\n  // If both fields match, Pair() should explain about them both.\n  EXPECT_EQ(\n      \"whose both fields match, where the first field is a value \"\n      \"which is 1 more than 0, and the second field is a value \"\n      \"which is 2 more than 0\",\n      Explain(m, make_pair(1, 2)));\n\n  // If only the first match has an explanation, only this explanation should\n  // be printed.\n  const Matcher<pair<int, int>> explain_first = Pair(GreaterThan(0), 0);\n  EXPECT_EQ(\n      \"whose both fields match, where the first field is a value \"\n      \"which is 1 more than 0\",\n      Explain(explain_first, make_pair(1, 0)));\n\n  // If only the second match has an explanation, only this explanation should\n  // be printed.\n  const Matcher<pair<int, int>> explain_second = Pair(0, GreaterThan(0));\n  EXPECT_EQ(\n      \"whose both fields match, where the second field is a value \"\n      \"which is 1 more than 0\",\n      Explain(explain_second, make_pair(0, 1)));\n}\n\nTEST(PairTest, MatchesCorrectly) {\n  pair<int, std::string> p(25, \"foo\");\n\n  // Both fields match.\n  EXPECT_THAT(p, Pair(25, \"foo\"));\n  EXPECT_THAT(p, Pair(Ge(20), HasSubstr(\"o\")));\n\n  // 'first' doesnt' match, but 'second' matches.\n  EXPECT_THAT(p, Not(Pair(42, \"foo\")));\n  EXPECT_THAT(p, Not(Pair(Lt(25), \"foo\")));\n\n  // 'first' matches, but 'second' doesn't match.\n  EXPECT_THAT(p, Not(Pair(25, \"bar\")));\n  EXPECT_THAT(p, Not(Pair(25, Not(\"foo\"))));\n\n  // Neither field matches.\n  EXPECT_THAT(p, Not(Pair(13, \"bar\")));\n  EXPECT_THAT(p, Not(Pair(Lt(13), HasSubstr(\"a\"))));\n}\n\nTEST(PairTest, WorksWithMoveOnly) {\n  pair<std::unique_ptr<int>, std::unique_ptr<int>> p;\n  p.second.reset(new int(7));\n  EXPECT_THAT(p, Pair(Eq(nullptr), Ne(nullptr)));\n}\n\nTEST(PairTest, SafelyCastsInnerMatchers) {\n  Matcher<int> is_positive = Gt(0);\n  Matcher<int> is_negative = Lt(0);\n  pair<char, bool> p('a', true);\n  EXPECT_THAT(p, Pair(is_positive, _));\n  EXPECT_THAT(p, Not(Pair(is_negative, _)));\n  EXPECT_THAT(p, Pair(_, is_positive));\n  EXPECT_THAT(p, Not(Pair(_, is_negative)));\n}\n\nTEST(PairTest, InsideContainsUsingMap) {\n  map<int, char> container;\n  container.insert(make_pair(1, 'a'));\n  container.insert(make_pair(2, 'b'));\n  container.insert(make_pair(4, 'c'));\n  EXPECT_THAT(container, Contains(Pair(1, 'a')));\n  EXPECT_THAT(container, Contains(Pair(1, _)));\n  EXPECT_THAT(container, Contains(Pair(_, 'a')));\n  EXPECT_THAT(container, Not(Contains(Pair(3, _))));\n}\n\nINSTANTIATE_GTEST_MATCHER_TEST_P(FieldsAreTest);\n\nTEST(FieldsAreTest, MatchesCorrectly) {\n  std::tuple<int, std::string, double> p(25, \"foo\", .5);\n\n  // All fields match.\n  EXPECT_THAT(p, FieldsAre(25, \"foo\", .5));\n  EXPECT_THAT(p, FieldsAre(Ge(20), HasSubstr(\"o\"), DoubleEq(.5)));\n\n  // Some don't match.\n  EXPECT_THAT(p, Not(FieldsAre(26, \"foo\", .5)));\n  EXPECT_THAT(p, Not(FieldsAre(25, \"fo\", .5)));\n  EXPECT_THAT(p, Not(FieldsAre(25, \"foo\", .6)));\n}\n\nTEST(FieldsAreTest, CanDescribeSelf) {\n  Matcher<const pair<std::string, int>&> m1 = FieldsAre(\"foo\", 42);\n  EXPECT_EQ(\n      \"has field #0 that is equal to \\\"foo\\\"\"\n      \", and has field #1 that is equal to 42\",\n      Describe(m1));\n  EXPECT_EQ(\n      \"has field #0 that isn't equal to \\\"foo\\\"\"\n      \", or has field #1 that isn't equal to 42\",\n      DescribeNegation(m1));\n}\n\nTEST_P(FieldsAreTestP, CanExplainMatchResultTo) {\n  // The first one that fails is the one that gives the error.\n  Matcher<std::tuple<int, int, int>> m =\n      FieldsAre(GreaterThan(0), GreaterThan(0), GreaterThan(0));\n\n  EXPECT_EQ(\"whose field #0 does not match, which is 1 less than 0\",\n            Explain(m, std::make_tuple(-1, -2, -3)));\n  EXPECT_EQ(\"whose field #1 does not match, which is 2 less than 0\",\n            Explain(m, std::make_tuple(1, -2, -3)));\n  EXPECT_EQ(\"whose field #2 does not match, which is 3 less than 0\",\n            Explain(m, std::make_tuple(1, 2, -3)));\n\n  // If they all match, we get a long explanation of success.\n  EXPECT_EQ(\n      \"whose all elements match, \"\n      \"where field #0 is a value which is 1 more than 0\"\n      \", and field #1 is a value which is 2 more than 0\"\n      \", and field #2 is a value which is 3 more than 0\",\n      Explain(m, std::make_tuple(1, 2, 3)));\n\n  // Only print those that have an explanation.\n  m = FieldsAre(GreaterThan(0), 0, GreaterThan(0));\n  EXPECT_EQ(\n      \"whose all elements match, \"\n      \"where field #0 is a value which is 1 more than 0\"\n      \", and field #2 is a value which is 3 more than 0\",\n      Explain(m, std::make_tuple(1, 0, 3)));\n\n  // If only one has an explanation, then print that one.\n  m = FieldsAre(0, GreaterThan(0), 0);\n  EXPECT_EQ(\n      \"whose all elements match, \"\n      \"where field #1 is a value which is 1 more than 0\",\n      Explain(m, std::make_tuple(0, 1, 0)));\n}\n\n#if defined(__cpp_structured_bindings) && __cpp_structured_bindings >= 201606\nTEST(FieldsAreTest, StructuredBindings) {\n  // testing::FieldsAre can also match aggregates and such with C++17 and up.\n  struct MyType {\n    int i;\n    std::string str;\n  };\n  EXPECT_THAT((MyType{17, \"foo\"}), FieldsAre(Eq(17), HasSubstr(\"oo\")));\n\n  // Test all the supported arities.\n  struct MyVarType1 {\n    int a;\n  };\n  EXPECT_THAT(MyVarType1{}, FieldsAre(0));\n  struct MyVarType2 {\n    int a, b;\n  };\n  EXPECT_THAT(MyVarType2{}, FieldsAre(0, 0));\n  struct MyVarType3 {\n    int a, b, c;\n  };\n  EXPECT_THAT(MyVarType3{}, FieldsAre(0, 0, 0));\n  struct MyVarType4 {\n    int a, b, c, d;\n  };\n  EXPECT_THAT(MyVarType4{}, FieldsAre(0, 0, 0, 0));\n  struct MyVarType5 {\n    int a, b, c, d, e;\n  };\n  EXPECT_THAT(MyVarType5{}, FieldsAre(0, 0, 0, 0, 0));\n  struct MyVarType6 {\n    int a, b, c, d, e, f;\n  };\n  EXPECT_THAT(MyVarType6{}, FieldsAre(0, 0, 0, 0, 0, 0));\n  struct MyVarType7 {\n    int a, b, c, d, e, f, g;\n  };\n  EXPECT_THAT(MyVarType7{}, FieldsAre(0, 0, 0, 0, 0, 0, 0));\n  struct MyVarType8 {\n    int a, b, c, d, e, f, g, h;\n  };\n  EXPECT_THAT(MyVarType8{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0));\n  struct MyVarType9 {\n    int a, b, c, d, e, f, g, h, i;\n  };\n  EXPECT_THAT(MyVarType9{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0));\n  struct MyVarType10 {\n    int a, b, c, d, e, f, g, h, i, j;\n  };\n  EXPECT_THAT(MyVarType10{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0));\n  struct MyVarType11 {\n    int a, b, c, d, e, f, g, h, i, j, k;\n  };\n  EXPECT_THAT(MyVarType11{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));\n  struct MyVarType12 {\n    int a, b, c, d, e, f, g, h, i, j, k, l;\n  };\n  EXPECT_THAT(MyVarType12{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));\n  struct MyVarType13 {\n    int a, b, c, d, e, f, g, h, i, j, k, l, m;\n  };\n  EXPECT_THAT(MyVarType13{}, FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));\n  struct MyVarType14 {\n    int a, b, c, d, e, f, g, h, i, j, k, l, m, n;\n  };\n  EXPECT_THAT(MyVarType14{},\n              FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));\n  struct MyVarType15 {\n    int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o;\n  };\n  EXPECT_THAT(MyVarType15{},\n              FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));\n  struct MyVarType16 {\n    int a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p;\n  };\n  EXPECT_THAT(MyVarType16{},\n              FieldsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));\n}\n#endif\n\nTEST(PairTest, UseGetInsteadOfMembers) {\n  PairWithGet pair{7, \"ABC\"};\n  EXPECT_THAT(pair, Pair(7, \"ABC\"));\n  EXPECT_THAT(pair, Pair(Ge(7), HasSubstr(\"AB\")));\n  EXPECT_THAT(pair, Not(Pair(Lt(7), \"ABC\")));\n\n  std::vector<PairWithGet> v = {{11, \"Foo\"}, {29, \"gMockIsBestMock\"}};\n  EXPECT_THAT(v,\n              ElementsAre(Pair(11, std::string(\"Foo\")), Pair(Ge(10), Not(\"\"))));\n}\n\n// Tests StartsWith(s).\n\nTEST(StartsWithTest, MatchesStringWithGivenPrefix) {\n  const Matcher<const char*> m1 = StartsWith(std::string(\"\"));\n  EXPECT_TRUE(m1.Matches(\"Hi\"));\n  EXPECT_TRUE(m1.Matches(\"\"));\n  EXPECT_FALSE(m1.Matches(nullptr));\n\n  const Matcher<const std::string&> m2 = StartsWith(\"Hi\");\n  EXPECT_TRUE(m2.Matches(\"Hi\"));\n  EXPECT_TRUE(m2.Matches(\"Hi Hi!\"));\n  EXPECT_TRUE(m2.Matches(\"High\"));\n  EXPECT_FALSE(m2.Matches(\"H\"));\n  EXPECT_FALSE(m2.Matches(\" Hi\"));\n\n#if GTEST_INTERNAL_HAS_STRING_VIEW\n  const Matcher<internal::StringView> m_empty =\n      StartsWith(internal::StringView(\"\"));\n  EXPECT_TRUE(m_empty.Matches(internal::StringView()));\n  EXPECT_TRUE(m_empty.Matches(internal::StringView(\"\")));\n  EXPECT_TRUE(m_empty.Matches(internal::StringView(\"not empty\")));\n#endif  // GTEST_INTERNAL_HAS_STRING_VIEW\n}\n\nTEST(StartsWithTest, CanDescribeSelf) {\n  Matcher<const std::string> m = StartsWith(\"Hi\");\n  EXPECT_EQ(\"starts with \\\"Hi\\\"\", Describe(m));\n}\n\n// Tests EndsWith(s).\n\nTEST(EndsWithTest, MatchesStringWithGivenSuffix) {\n  const Matcher<const char*> m1 = EndsWith(\"\");\n  EXPECT_TRUE(m1.Matches(\"Hi\"));\n  EXPECT_TRUE(m1.Matches(\"\"));\n  EXPECT_FALSE(m1.Matches(nullptr));\n\n  const Matcher<const std::string&> m2 = EndsWith(std::string(\"Hi\"));\n  EXPECT_TRUE(m2.Matches(\"Hi\"));\n  EXPECT_TRUE(m2.Matches(\"Wow Hi Hi\"));\n  EXPECT_TRUE(m2.Matches(\"Super Hi\"));\n  EXPECT_FALSE(m2.Matches(\"i\"));\n  EXPECT_FALSE(m2.Matches(\"Hi \"));\n\n#if GTEST_INTERNAL_HAS_STRING_VIEW\n  const Matcher<const internal::StringView&> m4 =\n      EndsWith(internal::StringView(\"\"));\n  EXPECT_TRUE(m4.Matches(\"Hi\"));\n  EXPECT_TRUE(m4.Matches(\"\"));\n  EXPECT_TRUE(m4.Matches(internal::StringView()));\n  EXPECT_TRUE(m4.Matches(internal::StringView(\"\")));\n#endif  // GTEST_INTERNAL_HAS_STRING_VIEW\n}\n\nTEST(EndsWithTest, CanDescribeSelf) {\n  Matcher<const std::string> m = EndsWith(\"Hi\");\n  EXPECT_EQ(\"ends with \\\"Hi\\\"\", Describe(m));\n}\n\n// Tests WhenBase64Unescaped.\n\nTEST(WhenBase64UnescapedTest, MatchesUnescapedBase64Strings) {\n  const Matcher<const char*> m1 = WhenBase64Unescaped(EndsWith(\"!\"));\n  EXPECT_FALSE(m1.Matches(\"invalid base64\"));\n  EXPECT_FALSE(m1.Matches(\"aGVsbG8gd29ybGQ=\"));  // hello world\n  EXPECT_TRUE(m1.Matches(\"aGVsbG8gd29ybGQh\"));   // hello world!\n\n  const Matcher<const std::string&> m2 = WhenBase64Unescaped(EndsWith(\"!\"));\n  EXPECT_FALSE(m2.Matches(\"invalid base64\"));\n  EXPECT_FALSE(m2.Matches(\"aGVsbG8gd29ybGQ=\"));  // hello world\n  EXPECT_TRUE(m2.Matches(\"aGVsbG8gd29ybGQh\"));   // hello world!\n\n#if GTEST_INTERNAL_HAS_STRING_VIEW\n  const Matcher<const internal::StringView&> m3 =\n      WhenBase64Unescaped(EndsWith(\"!\"));\n  EXPECT_FALSE(m3.Matches(\"invalid base64\"));\n  EXPECT_FALSE(m3.Matches(\"aGVsbG8gd29ybGQ=\"));  // hello world\n  EXPECT_TRUE(m3.Matches(\"aGVsbG8gd29ybGQh\"));   // hello world!\n#endif  // GTEST_INTERNAL_HAS_STRING_VIEW\n}\n\nTEST(WhenBase64UnescapedTest, CanDescribeSelf) {\n  const Matcher<const char*> m = WhenBase64Unescaped(EndsWith(\"!\"));\n  EXPECT_EQ(\"matches after Base64Unescape ends with \\\"!\\\"\", Describe(m));\n}\n\n// Tests MatchesRegex().\n\nTEST(MatchesRegexTest, MatchesStringMatchingGivenRegex) {\n  const Matcher<const char*> m1 = MatchesRegex(\"a.*z\");\n  EXPECT_TRUE(m1.Matches(\"az\"));\n  EXPECT_TRUE(m1.Matches(\"abcz\"));\n  EXPECT_FALSE(m1.Matches(nullptr));\n\n  const Matcher<const std::string&> m2 = MatchesRegex(new RE(\"a.*z\"));\n  EXPECT_TRUE(m2.Matches(\"azbz\"));\n  EXPECT_FALSE(m2.Matches(\"az1\"));\n  EXPECT_FALSE(m2.Matches(\"1az\"));\n\n#if GTEST_INTERNAL_HAS_STRING_VIEW\n  const Matcher<const internal::StringView&> m3 = MatchesRegex(\"a.*z\");\n  EXPECT_TRUE(m3.Matches(internal::StringView(\"az\")));\n  EXPECT_TRUE(m3.Matches(internal::StringView(\"abcz\")));\n  EXPECT_FALSE(m3.Matches(internal::StringView(\"1az\")));\n  EXPECT_FALSE(m3.Matches(internal::StringView()));\n  const Matcher<const internal::StringView&> m4 =\n      MatchesRegex(internal::StringView(\"\"));\n  EXPECT_TRUE(m4.Matches(internal::StringView(\"\")));\n  EXPECT_TRUE(m4.Matches(internal::StringView()));\n#endif  // GTEST_INTERNAL_HAS_STRING_VIEW\n}\n\nTEST(MatchesRegexTest, CanDescribeSelf) {\n  Matcher<const std::string> m1 = MatchesRegex(std::string(\"Hi.*\"));\n  EXPECT_EQ(\"matches regular expression \\\"Hi.*\\\"\", Describe(m1));\n\n  Matcher<const char*> m2 = MatchesRegex(new RE(\"a.*\"));\n  EXPECT_EQ(\"matches regular expression \\\"a.*\\\"\", Describe(m2));\n\n#if GTEST_INTERNAL_HAS_STRING_VIEW\n  Matcher<const internal::StringView> m3 = MatchesRegex(new RE(\"0.*\"));\n  EXPECT_EQ(\"matches regular expression \\\"0.*\\\"\", Describe(m3));\n#endif  // GTEST_INTERNAL_HAS_STRING_VIEW\n}\n\n// Tests ContainsRegex().\n\nTEST(ContainsRegexTest, MatchesStringContainingGivenRegex) {\n  const Matcher<const char*> m1 = ContainsRegex(std::string(\"a.*z\"));\n  EXPECT_TRUE(m1.Matches(\"az\"));\n  EXPECT_TRUE(m1.Matches(\"0abcz1\"));\n  EXPECT_FALSE(m1.Matches(nullptr));\n\n  const Matcher<const std::string&> m2 = ContainsRegex(new RE(\"a.*z\"));\n  EXPECT_TRUE(m2.Matches(\"azbz\"));\n  EXPECT_TRUE(m2.Matches(\"az1\"));\n  EXPECT_FALSE(m2.Matches(\"1a\"));\n\n#if GTEST_INTERNAL_HAS_STRING_VIEW\n  const Matcher<const internal::StringView&> m3 = ContainsRegex(new RE(\"a.*z\"));\n  EXPECT_TRUE(m3.Matches(internal::StringView(\"azbz\")));\n  EXPECT_TRUE(m3.Matches(internal::StringView(\"az1\")));\n  EXPECT_FALSE(m3.Matches(internal::StringView(\"1a\")));\n  EXPECT_FALSE(m3.Matches(internal::StringView()));\n  const Matcher<const internal::StringView&> m4 =\n      ContainsRegex(internal::StringView(\"\"));\n  EXPECT_TRUE(m4.Matches(internal::StringView(\"\")));\n  EXPECT_TRUE(m4.Matches(internal::StringView()));\n#endif  // GTEST_INTERNAL_HAS_STRING_VIEW\n}\n\nTEST(ContainsRegexTest, CanDescribeSelf) {\n  Matcher<const std::string> m1 = ContainsRegex(\"Hi.*\");\n  EXPECT_EQ(\"contains regular expression \\\"Hi.*\\\"\", Describe(m1));\n\n  Matcher<const char*> m2 = ContainsRegex(new RE(\"a.*\"));\n  EXPECT_EQ(\"contains regular expression \\\"a.*\\\"\", Describe(m2));\n\n#if GTEST_INTERNAL_HAS_STRING_VIEW\n  Matcher<const internal::StringView> m3 = ContainsRegex(new RE(\"0.*\"));\n  EXPECT_EQ(\"contains regular expression \\\"0.*\\\"\", Describe(m3));\n#endif  // GTEST_INTERNAL_HAS_STRING_VIEW\n}\n\n// Tests for wide strings.\n#if GTEST_HAS_STD_WSTRING\nTEST(StdWideStrEqTest, MatchesEqual) {\n  Matcher<const wchar_t*> m = StrEq(::std::wstring(L\"Hello\"));\n  EXPECT_TRUE(m.Matches(L\"Hello\"));\n  EXPECT_FALSE(m.Matches(L\"hello\"));\n  EXPECT_FALSE(m.Matches(nullptr));\n\n  Matcher<const ::std::wstring&> m2 = StrEq(L\"Hello\");\n  EXPECT_TRUE(m2.Matches(L\"Hello\"));\n  EXPECT_FALSE(m2.Matches(L\"Hi\"));\n\n  Matcher<const ::std::wstring&> m3 = StrEq(L\"\\xD3\\x576\\x8D3\\xC74D\");\n  EXPECT_TRUE(m3.Matches(L\"\\xD3\\x576\\x8D3\\xC74D\"));\n  EXPECT_FALSE(m3.Matches(L\"\\xD3\\x576\\x8D3\\xC74E\"));\n\n  ::std::wstring str(L\"01204500800\");\n  str[3] = L'\\0';\n  Matcher<const ::std::wstring&> m4 = StrEq(str);\n  EXPECT_TRUE(m4.Matches(str));\n  str[0] = str[6] = str[7] = str[9] = str[10] = L'\\0';\n  Matcher<const ::std::wstring&> m5 = StrEq(str);\n  EXPECT_TRUE(m5.Matches(str));\n}\n\nTEST(StdWideStrEqTest, CanDescribeSelf) {\n  Matcher<::std::wstring> m = StrEq(L\"Hi-\\'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\");\n  EXPECT_EQ(\"is equal to L\\\"Hi-\\'\\\\\\\"?\\\\\\\\\\\\a\\\\b\\\\f\\\\n\\\\r\\\\t\\\\v\\\"\",\n            Describe(m));\n\n  Matcher<::std::wstring> m2 = StrEq(L\"\\xD3\\x576\\x8D3\\xC74D\");\n  EXPECT_EQ(\"is equal to L\\\"\\\\xD3\\\\x576\\\\x8D3\\\\xC74D\\\"\", Describe(m2));\n\n  ::std::wstring str(L\"01204500800\");\n  str[3] = L'\\0';\n  Matcher<const ::std::wstring&> m4 = StrEq(str);\n  EXPECT_EQ(\"is equal to L\\\"012\\\\04500800\\\"\", Describe(m4));\n  str[0] = str[6] = str[7] = str[9] = str[10] = L'\\0';\n  Matcher<const ::std::wstring&> m5 = StrEq(str);\n  EXPECT_EQ(\"is equal to L\\\"\\\\012\\\\045\\\\0\\\\08\\\\0\\\\0\\\"\", Describe(m5));\n}\n\nTEST(StdWideStrNeTest, MatchesUnequalString) {\n  Matcher<const wchar_t*> m = StrNe(L\"Hello\");\n  EXPECT_TRUE(m.Matches(L\"\"));\n  EXPECT_TRUE(m.Matches(nullptr));\n  EXPECT_FALSE(m.Matches(L\"Hello\"));\n\n  Matcher<::std::wstring> m2 = StrNe(::std::wstring(L\"Hello\"));\n  EXPECT_TRUE(m2.Matches(L\"hello\"));\n  EXPECT_FALSE(m2.Matches(L\"Hello\"));\n}\n\nTEST(StdWideStrNeTest, CanDescribeSelf) {\n  Matcher<const wchar_t*> m = StrNe(L\"Hi\");\n  EXPECT_EQ(\"isn't equal to L\\\"Hi\\\"\", Describe(m));\n}\n\nTEST(StdWideStrCaseEqTest, MatchesEqualStringIgnoringCase) {\n  Matcher<const wchar_t*> m = StrCaseEq(::std::wstring(L\"Hello\"));\n  EXPECT_TRUE(m.Matches(L\"Hello\"));\n  EXPECT_TRUE(m.Matches(L\"hello\"));\n  EXPECT_FALSE(m.Matches(L\"Hi\"));\n  EXPECT_FALSE(m.Matches(nullptr));\n\n  Matcher<const ::std::wstring&> m2 = StrCaseEq(L\"Hello\");\n  EXPECT_TRUE(m2.Matches(L\"hello\"));\n  EXPECT_FALSE(m2.Matches(L\"Hi\"));\n}\n\nTEST(StdWideStrCaseEqTest, MatchesEqualStringWith0IgnoringCase) {\n  ::std::wstring str1(L\"oabocdooeoo\");\n  ::std::wstring str2(L\"OABOCDOOEOO\");\n  Matcher<const ::std::wstring&> m0 = StrCaseEq(str1);\n  EXPECT_FALSE(m0.Matches(str2 + ::std::wstring(1, L'\\0')));\n\n  str1[3] = str2[3] = L'\\0';\n  Matcher<const ::std::wstring&> m1 = StrCaseEq(str1);\n  EXPECT_TRUE(m1.Matches(str2));\n\n  str1[0] = str1[6] = str1[7] = str1[10] = L'\\0';\n  str2[0] = str2[6] = str2[7] = str2[10] = L'\\0';\n  Matcher<const ::std::wstring&> m2 = StrCaseEq(str1);\n  str1[9] = str2[9] = L'\\0';\n  EXPECT_FALSE(m2.Matches(str2));\n\n  Matcher<const ::std::wstring&> m3 = StrCaseEq(str1);\n  EXPECT_TRUE(m3.Matches(str2));\n\n  EXPECT_FALSE(m3.Matches(str2 + L\"x\"));\n  str2.append(1, L'\\0');\n  EXPECT_FALSE(m3.Matches(str2));\n  EXPECT_FALSE(m3.Matches(::std::wstring(str2, 0, 9)));\n}\n\nTEST(StdWideStrCaseEqTest, CanDescribeSelf) {\n  Matcher<::std::wstring> m = StrCaseEq(L\"Hi\");\n  EXPECT_EQ(\"is equal to (ignoring case) L\\\"Hi\\\"\", Describe(m));\n}\n\nTEST(StdWideStrCaseNeTest, MatchesUnequalStringIgnoringCase) {\n  Matcher<const wchar_t*> m = StrCaseNe(L\"Hello\");\n  EXPECT_TRUE(m.Matches(L\"Hi\"));\n  EXPECT_TRUE(m.Matches(nullptr));\n  EXPECT_FALSE(m.Matches(L\"Hello\"));\n  EXPECT_FALSE(m.Matches(L\"hello\"));\n\n  Matcher<::std::wstring> m2 = StrCaseNe(::std::wstring(L\"Hello\"));\n  EXPECT_TRUE(m2.Matches(L\"\"));\n  EXPECT_FALSE(m2.Matches(L\"Hello\"));\n}\n\nTEST(StdWideStrCaseNeTest, CanDescribeSelf) {\n  Matcher<const wchar_t*> m = StrCaseNe(L\"Hi\");\n  EXPECT_EQ(\"isn't equal to (ignoring case) L\\\"Hi\\\"\", Describe(m));\n}\n\n// Tests that HasSubstr() works for matching wstring-typed values.\nTEST(StdWideHasSubstrTest, WorksForStringClasses) {\n  const Matcher<::std::wstring> m1 = HasSubstr(L\"foo\");\n  EXPECT_TRUE(m1.Matches(::std::wstring(L\"I love food.\")));\n  EXPECT_FALSE(m1.Matches(::std::wstring(L\"tofo\")));\n\n  const Matcher<const ::std::wstring&> m2 = HasSubstr(L\"foo\");\n  EXPECT_TRUE(m2.Matches(::std::wstring(L\"I love food.\")));\n  EXPECT_FALSE(m2.Matches(::std::wstring(L\"tofo\")));\n}\n\n// Tests that HasSubstr() works for matching C-wide-string-typed values.\nTEST(StdWideHasSubstrTest, WorksForCStrings) {\n  const Matcher<wchar_t*> m1 = HasSubstr(L\"foo\");\n  EXPECT_TRUE(m1.Matches(const_cast<wchar_t*>(L\"I love food.\")));\n  EXPECT_FALSE(m1.Matches(const_cast<wchar_t*>(L\"tofo\")));\n  EXPECT_FALSE(m1.Matches(nullptr));\n\n  const Matcher<const wchar_t*> m2 = HasSubstr(L\"foo\");\n  EXPECT_TRUE(m2.Matches(L\"I love food.\"));\n  EXPECT_FALSE(m2.Matches(L\"tofo\"));\n  EXPECT_FALSE(m2.Matches(nullptr));\n}\n\n// Tests that HasSubstr(s) describes itself properly.\nTEST(StdWideHasSubstrTest, CanDescribeSelf) {\n  Matcher<::std::wstring> m = HasSubstr(L\"foo\\n\\\"\");\n  EXPECT_EQ(\"has substring L\\\"foo\\\\n\\\\\\\"\\\"\", Describe(m));\n}\n\n// Tests StartsWith(s).\n\nTEST(StdWideStartsWithTest, MatchesStringWithGivenPrefix) {\n  const Matcher<const wchar_t*> m1 = StartsWith(::std::wstring(L\"\"));\n  EXPECT_TRUE(m1.Matches(L\"Hi\"));\n  EXPECT_TRUE(m1.Matches(L\"\"));\n  EXPECT_FALSE(m1.Matches(nullptr));\n\n  const Matcher<const ::std::wstring&> m2 = StartsWith(L\"Hi\");\n  EXPECT_TRUE(m2.Matches(L\"Hi\"));\n  EXPECT_TRUE(m2.Matches(L\"Hi Hi!\"));\n  EXPECT_TRUE(m2.Matches(L\"High\"));\n  EXPECT_FALSE(m2.Matches(L\"H\"));\n  EXPECT_FALSE(m2.Matches(L\" Hi\"));\n}\n\nTEST(StdWideStartsWithTest, CanDescribeSelf) {\n  Matcher<const ::std::wstring> m = StartsWith(L\"Hi\");\n  EXPECT_EQ(\"starts with L\\\"Hi\\\"\", Describe(m));\n}\n\n// Tests EndsWith(s).\n\nTEST(StdWideEndsWithTest, MatchesStringWithGivenSuffix) {\n  const Matcher<const wchar_t*> m1 = EndsWith(L\"\");\n  EXPECT_TRUE(m1.Matches(L\"Hi\"));\n  EXPECT_TRUE(m1.Matches(L\"\"));\n  EXPECT_FALSE(m1.Matches(nullptr));\n\n  const Matcher<const ::std::wstring&> m2 = EndsWith(::std::wstring(L\"Hi\"));\n  EXPECT_TRUE(m2.Matches(L\"Hi\"));\n  EXPECT_TRUE(m2.Matches(L\"Wow Hi Hi\"));\n  EXPECT_TRUE(m2.Matches(L\"Super Hi\"));\n  EXPECT_FALSE(m2.Matches(L\"i\"));\n  EXPECT_FALSE(m2.Matches(L\"Hi \"));\n}\n\nTEST(StdWideEndsWithTest, CanDescribeSelf) {\n  Matcher<const ::std::wstring> m = EndsWith(L\"Hi\");\n  EXPECT_EQ(\"ends with L\\\"Hi\\\"\", Describe(m));\n}\n\n#endif  // GTEST_HAS_STD_WSTRING\n\nTEST(ExplainMatchResultTest, WorksWithPolymorphicMatcher) {\n  StringMatchResultListener listener1;\n  EXPECT_TRUE(ExplainMatchResult(PolymorphicIsEven(), 42, &listener1));\n  EXPECT_EQ(\"% 2 == 0\", listener1.str());\n\n  StringMatchResultListener listener2;\n  EXPECT_FALSE(ExplainMatchResult(Ge(42), 1.5, &listener2));\n  EXPECT_EQ(\"\", listener2.str());\n}\n\nTEST(ExplainMatchResultTest, WorksWithMonomorphicMatcher) {\n  const Matcher<int> is_even = PolymorphicIsEven();\n  StringMatchResultListener listener1;\n  EXPECT_TRUE(ExplainMatchResult(is_even, 42, &listener1));\n  EXPECT_EQ(\"% 2 == 0\", listener1.str());\n\n  const Matcher<const double&> is_zero = Eq(0);\n  StringMatchResultListener listener2;\n  EXPECT_FALSE(ExplainMatchResult(is_zero, 1.5, &listener2));\n  EXPECT_EQ(\"\", listener2.str());\n}\n\nMATCHER(ConstructNoArg, \"\") { return true; }\nMATCHER_P(Construct1Arg, arg1, \"\") { return true; }\nMATCHER_P2(Construct2Args, arg1, arg2, \"\") { return true; }\n\nTEST(MatcherConstruct, ExplicitVsImplicit) {\n  {\n    // No arg constructor can be constructed with empty brace.\n    ConstructNoArgMatcher m = {};\n    (void)m;\n    // And with no args\n    ConstructNoArgMatcher m2;\n    (void)m2;\n  }\n  {\n    // The one arg constructor has an explicit constructor.\n    // This is to prevent the implicit conversion.\n    using M = Construct1ArgMatcherP<int>;\n    EXPECT_TRUE((std::is_constructible<M, int>::value));\n    EXPECT_FALSE((std::is_convertible<int, M>::value));\n  }\n  {\n    // Multiple arg matchers can be constructed with an implicit construction.\n    Construct2ArgsMatcherP2<int, double> m = {1, 2.2};\n    (void)m;\n  }\n}\n\nMATCHER_P(Really, inner_matcher, \"\") {\n  return ExplainMatchResult(inner_matcher, arg, result_listener);\n}\n\nTEST(ExplainMatchResultTest, WorksInsideMATCHER) {\n  EXPECT_THAT(0, Really(Eq(0)));\n}\n\nTEST(DescribeMatcherTest, WorksWithValue) {\n  EXPECT_EQ(\"is equal to 42\", DescribeMatcher<int>(42));\n  EXPECT_EQ(\"isn't equal to 42\", DescribeMatcher<int>(42, true));\n}\n\nTEST(DescribeMatcherTest, WorksWithMonomorphicMatcher) {\n  const Matcher<int> monomorphic = Le(0);\n  EXPECT_EQ(\"is <= 0\", DescribeMatcher<int>(monomorphic));\n  EXPECT_EQ(\"isn't <= 0\", DescribeMatcher<int>(monomorphic, true));\n}\n\nTEST(DescribeMatcherTest, WorksWithPolymorphicMatcher) {\n  EXPECT_EQ(\"is even\", DescribeMatcher<int>(PolymorphicIsEven()));\n  EXPECT_EQ(\"is odd\", DescribeMatcher<int>(PolymorphicIsEven(), true));\n}\n\nMATCHER_P(FieldIIs, inner_matcher, \"\") {\n  return ExplainMatchResult(inner_matcher, arg.i, result_listener);\n}\n\n#if GTEST_HAS_RTTI\nTEST(WhenDynamicCastToTest, SameType) {\n  Derived derived;\n  derived.i = 4;\n\n  // Right type. A pointer is passed down.\n  Base* as_base_ptr = &derived;\n  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Not(IsNull())));\n  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(4))));\n  EXPECT_THAT(as_base_ptr,\n              Not(WhenDynamicCastTo<Derived*>(Pointee(FieldIIs(5)))));\n}\n\nTEST(WhenDynamicCastToTest, WrongTypes) {\n  Base base;\n  Derived derived;\n  OtherDerived other_derived;\n\n  // Wrong types. NULL is passed.\n  EXPECT_THAT(&base, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));\n  EXPECT_THAT(&base, WhenDynamicCastTo<Derived*>(IsNull()));\n  Base* as_base_ptr = &derived;\n  EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<OtherDerived*>(Pointee(_))));\n  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<OtherDerived*>(IsNull()));\n  as_base_ptr = &other_derived;\n  EXPECT_THAT(as_base_ptr, Not(WhenDynamicCastTo<Derived*>(Pointee(_))));\n  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));\n}\n\nTEST(WhenDynamicCastToTest, AlreadyNull) {\n  // Already NULL.\n  Base* as_base_ptr = nullptr;\n  EXPECT_THAT(as_base_ptr, WhenDynamicCastTo<Derived*>(IsNull()));\n}\n\nstruct AmbiguousCastTypes {\n  class VirtualDerived : public virtual Base {};\n  class DerivedSub1 : public VirtualDerived {};\n  class DerivedSub2 : public VirtualDerived {};\n  class ManyDerivedInHierarchy : public DerivedSub1, public DerivedSub2 {};\n};\n\nTEST(WhenDynamicCastToTest, AmbiguousCast) {\n  AmbiguousCastTypes::DerivedSub1 sub1;\n  AmbiguousCastTypes::ManyDerivedInHierarchy many_derived;\n  // Multiply derived from Base. dynamic_cast<> returns NULL.\n  Base* as_base_ptr =\n      static_cast<AmbiguousCastTypes::DerivedSub1*>(&many_derived);\n  EXPECT_THAT(as_base_ptr,\n              WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(IsNull()));\n  as_base_ptr = &sub1;\n  EXPECT_THAT(\n      as_base_ptr,\n      WhenDynamicCastTo<AmbiguousCastTypes::VirtualDerived*>(Not(IsNull())));\n}\n\nTEST(WhenDynamicCastToTest, Describe) {\n  Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));\n  const std::string prefix =\n      \"when dynamic_cast to \" + internal::GetTypeName<Derived*>() + \", \";\n  EXPECT_EQ(prefix + \"points to a value that is anything\", Describe(matcher));\n  EXPECT_EQ(prefix + \"does not point to a value that is anything\",\n            DescribeNegation(matcher));\n}\n\nTEST(WhenDynamicCastToTest, Explain) {\n  Matcher<Base*> matcher = WhenDynamicCastTo<Derived*>(Pointee(_));\n  Base* null = nullptr;\n  EXPECT_THAT(Explain(matcher, null), HasSubstr(\"NULL\"));\n  Derived derived;\n  EXPECT_TRUE(matcher.Matches(&derived));\n  EXPECT_THAT(Explain(matcher, &derived), HasSubstr(\"which points to \"));\n\n  // With references, the matcher itself can fail. Test for that one.\n  Matcher<const Base&> ref_matcher = WhenDynamicCastTo<const OtherDerived&>(_);\n  EXPECT_THAT(Explain(ref_matcher, derived),\n              HasSubstr(\"which cannot be dynamic_cast\"));\n}\n\nTEST(WhenDynamicCastToTest, GoodReference) {\n  Derived derived;\n  derived.i = 4;\n  Base& as_base_ref = derived;\n  EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(FieldIIs(4)));\n  EXPECT_THAT(as_base_ref, WhenDynamicCastTo<const Derived&>(Not(FieldIIs(5))));\n}\n\nTEST(WhenDynamicCastToTest, BadReference) {\n  Derived derived;\n  Base& as_base_ref = derived;\n  EXPECT_THAT(as_base_ref, Not(WhenDynamicCastTo<const OtherDerived&>(_)));\n}\n#endif  // GTEST_HAS_RTTI\n\nclass DivisibleByImpl {\n public:\n  explicit DivisibleByImpl(int a_divider) : divider_(a_divider) {}\n\n  // For testing using ExplainMatchResultTo() with polymorphic matchers.\n  template <typename T>\n  bool MatchAndExplain(const T& n, MatchResultListener* listener) const {\n    *listener << \"which is \" << (n % divider_) << \" modulo \" << divider_;\n    return (n % divider_) == 0;\n  }\n\n  void DescribeTo(ostream* os) const { *os << \"is divisible by \" << divider_; }\n\n  void DescribeNegationTo(ostream* os) const {\n    *os << \"is not divisible by \" << divider_;\n  }\n\n  void set_divider(int a_divider) { divider_ = a_divider; }\n  int divider() const { return divider_; }\n\n private:\n  int divider_;\n};\n\nPolymorphicMatcher<DivisibleByImpl> DivisibleBy(int n) {\n  return MakePolymorphicMatcher(DivisibleByImpl(n));\n}\n\n// Tests that when AllOf() fails, only the first failing matcher is\n// asked to explain why.\nTEST(ExplainMatchResultTest, AllOf_False_False) {\n  const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));\n  EXPECT_EQ(\"which is 1 modulo 4\", Explain(m, 5));\n}\n\n// Tests that when AllOf() fails, only the first failing matcher is\n// asked to explain why.\nTEST(ExplainMatchResultTest, AllOf_False_True) {\n  const Matcher<int> m = AllOf(DivisibleBy(4), DivisibleBy(3));\n  EXPECT_EQ(\"which is 2 modulo 4\", Explain(m, 6));\n}\n\n// Tests that when AllOf() fails, only the first failing matcher is\n// asked to explain why.\nTEST(ExplainMatchResultTest, AllOf_True_False) {\n  const Matcher<int> m = AllOf(Ge(1), DivisibleBy(3));\n  EXPECT_EQ(\"which is 2 modulo 3\", Explain(m, 5));\n}\n\n// Tests that when AllOf() succeeds, all matchers are asked to explain\n// why.\nTEST(ExplainMatchResultTest, AllOf_True_True) {\n  const Matcher<int> m = AllOf(DivisibleBy(2), DivisibleBy(3));\n  EXPECT_EQ(\"which is 0 modulo 2, and which is 0 modulo 3\", Explain(m, 6));\n}\n\nTEST(ExplainMatchResultTest, AllOf_True_True_2) {\n  const Matcher<int> m = AllOf(Ge(2), Le(3));\n  EXPECT_EQ(\"\", Explain(m, 2));\n}\n\nINSTANTIATE_GTEST_MATCHER_TEST_P(ExplainmatcherResultTest);\n\nTEST_P(ExplainmatcherResultTestP, MonomorphicMatcher) {\n  const Matcher<int> m = GreaterThan(5);\n  EXPECT_EQ(\"which is 1 more than 5\", Explain(m, 6));\n}\n\n// Tests PolymorphicMatcher::mutable_impl().\nTEST(PolymorphicMatcherTest, CanAccessMutableImpl) {\n  PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));\n  DivisibleByImpl& impl = m.mutable_impl();\n  EXPECT_EQ(42, impl.divider());\n\n  impl.set_divider(0);\n  EXPECT_EQ(0, m.mutable_impl().divider());\n}\n\n// Tests PolymorphicMatcher::impl().\nTEST(PolymorphicMatcherTest, CanAccessImpl) {\n  const PolymorphicMatcher<DivisibleByImpl> m(DivisibleByImpl(42));\n  const DivisibleByImpl& impl = m.impl();\n  EXPECT_EQ(42, impl.divider());\n}\n\n}  // namespace\n}  // namespace gmock_matchers_test\n}  // namespace testing\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock-matchers-containers_test.cc",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file tests some commonly used argument matchers.\n\n// Silence warning C4244: 'initializing': conversion from 'int' to 'short',\n// possible loss of data and C4100, unreferenced local parameter\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#pragma warning(disable : 4100)\n#endif\n\n#include \"test/gmock-matchers_test.h\"\n\nnamespace testing {\nnamespace gmock_matchers_test {\nnamespace {\n\nstd::vector<std::unique_ptr<int>> MakeUniquePtrs(const std::vector<int>& ints) {\n  std::vector<std::unique_ptr<int>> pointers;\n  for (int i : ints) pointers.emplace_back(new int(i));\n  return pointers;\n}\n\nstd::string OfType(const std::string& type_name) {\n#if GTEST_HAS_RTTI\n  return IsReadableTypeName(type_name) ? \" (of type \" + type_name + \")\" : \"\";\n#else\n  return \"\";\n#endif\n}\n\nTEST(ContainsTest, WorksWithMoveOnly) {\n  ContainerHelper helper;\n  EXPECT_CALL(helper, Call(Contains(Pointee(2))));\n  helper.Call(MakeUniquePtrs({1, 2}));\n}\n\nINSTANTIATE_GTEST_MATCHER_TEST_P(ElementsAreTest);\n\n// Tests the variadic version of the ElementsAreMatcher\nTEST(ElementsAreTest, HugeMatcher) {\n  vector<int> test_vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};\n\n  EXPECT_THAT(test_vector,\n              ElementsAre(Eq(1), Eq(2), Lt(13), Eq(4), Eq(5), Eq(6), Eq(7),\n                          Eq(8), Eq(9), Eq(10), Gt(1), Eq(12)));\n}\n\n// Tests the variadic version of the UnorderedElementsAreMatcher\nTEST(ElementsAreTest, HugeMatcherStr) {\n  vector<std::string> test_vector{\n      \"literal_string\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"};\n\n  EXPECT_THAT(test_vector, UnorderedElementsAre(\"literal_string\", _, _, _, _, _,\n                                                _, _, _, _, _, _));\n}\n\n// Tests the variadic version of the UnorderedElementsAreMatcher\nTEST(ElementsAreTest, HugeMatcherUnordered) {\n  vector<int> test_vector{2, 1, 8, 5, 4, 6, 7, 3, 9, 12, 11, 10};\n\n  EXPECT_THAT(test_vector, UnorderedElementsAre(\n                               Eq(2), Eq(1), Gt(7), Eq(5), Eq(4), Eq(6), Eq(7),\n                               Eq(3), Eq(9), Eq(12), Eq(11), Ne(122)));\n}\n\n// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value\n// matches the matcher.\nTEST(MatcherAssertionTest, WorksWhenMatcherIsSatisfied) {\n  ASSERT_THAT(5, Ge(2)) << \"This should succeed.\";\n  ASSERT_THAT(\"Foo\", EndsWith(\"oo\"));\n  EXPECT_THAT(2, AllOf(Le(7), Ge(0))) << \"This should succeed too.\";\n  EXPECT_THAT(\"Hello\", StartsWith(\"Hell\"));\n}\n\n// Tests that ASSERT_THAT() and EXPECT_THAT() work when the value\n// doesn't match the matcher.\nTEST(MatcherAssertionTest, WorksWhenMatcherIsNotSatisfied) {\n  // 'n' must be static as it is used in an EXPECT_FATAL_FAILURE(),\n  // which cannot reference auto variables.\n  static unsigned short n;  // NOLINT\n  n = 5;\n\n  EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Gt(10)),\n                       \"Value of: n\\n\"\n                       \"Expected: is > 10\\n\"\n                       \"  Actual: 5\" +\n                           OfType(\"unsigned short\"));\n  n = 0;\n  EXPECT_NONFATAL_FAILURE(EXPECT_THAT(n, AllOf(Le(7), Ge(5))),\n                          \"Value of: n\\n\"\n                          \"Expected: (is <= 7) and (is >= 5)\\n\"\n                          \"  Actual: 0\" +\n                              OfType(\"unsigned short\"));\n}\n\n// Tests that ASSERT_THAT() and EXPECT_THAT() work when the argument\n// has a reference type.\nTEST(MatcherAssertionTest, WorksForByRefArguments) {\n  // We use a static variable here as EXPECT_FATAL_FAILURE() cannot\n  // reference auto variables.\n  static int n;\n  n = 0;\n  EXPECT_THAT(n, AllOf(Le(7), Ref(n)));\n  EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),\n                       \"Value of: n\\n\"\n                       \"Expected: does not reference the variable @\");\n  // Tests the \"Actual\" part.\n  EXPECT_FATAL_FAILURE(ASSERT_THAT(n, Not(Ref(n))),\n                       \"Actual: 0\" + OfType(\"int\") + \", which is located @\");\n}\n\n// Tests that ASSERT_THAT() and EXPECT_THAT() work when the matcher is\n// monomorphic.\nTEST(MatcherAssertionTest, WorksForMonomorphicMatcher) {\n  Matcher<const char*> starts_with_he = StartsWith(\"he\");\n  ASSERT_THAT(\"hello\", starts_with_he);\n\n  Matcher<const std::string&> ends_with_ok = EndsWith(\"ok\");\n  ASSERT_THAT(\"book\", ends_with_ok);\n  const std::string bad = \"bad\";\n  EXPECT_NONFATAL_FAILURE(EXPECT_THAT(bad, ends_with_ok),\n                          \"Value of: bad\\n\"\n                          \"Expected: ends with \\\"ok\\\"\\n\"\n                          \"  Actual: \\\"bad\\\"\");\n  Matcher<int> is_greater_than_5 = Gt(5);\n  EXPECT_NONFATAL_FAILURE(EXPECT_THAT(5, is_greater_than_5),\n                          \"Value of: 5\\n\"\n                          \"Expected: is > 5\\n\"\n                          \"  Actual: 5\" +\n                              OfType(\"int\"));\n}\n\nTEST(PointeeTest, RawPointer) {\n  const Matcher<int*> m = Pointee(Ge(0));\n\n  int n = 1;\n  EXPECT_TRUE(m.Matches(&n));\n  n = -1;\n  EXPECT_FALSE(m.Matches(&n));\n  EXPECT_FALSE(m.Matches(nullptr));\n}\n\nTEST(PointeeTest, RawPointerToConst) {\n  const Matcher<const double*> m = Pointee(Ge(0));\n\n  double x = 1;\n  EXPECT_TRUE(m.Matches(&x));\n  x = -1;\n  EXPECT_FALSE(m.Matches(&x));\n  EXPECT_FALSE(m.Matches(nullptr));\n}\n\nTEST(PointeeTest, ReferenceToConstRawPointer) {\n  const Matcher<int* const&> m = Pointee(Ge(0));\n\n  int n = 1;\n  EXPECT_TRUE(m.Matches(&n));\n  n = -1;\n  EXPECT_FALSE(m.Matches(&n));\n  EXPECT_FALSE(m.Matches(nullptr));\n}\n\nTEST(PointeeTest, ReferenceToNonConstRawPointer) {\n  const Matcher<double*&> m = Pointee(Ge(0));\n\n  double x = 1.0;\n  double* p = &x;\n  EXPECT_TRUE(m.Matches(p));\n  x = -1;\n  EXPECT_FALSE(m.Matches(p));\n  p = nullptr;\n  EXPECT_FALSE(m.Matches(p));\n}\n\nTEST(PointeeTest, SmartPointer) {\n  const Matcher<std::unique_ptr<int>> m = Pointee(Ge(0));\n\n  std::unique_ptr<int> n(new int(1));\n  EXPECT_TRUE(m.Matches(n));\n}\n\nTEST(PointeeTest, SmartPointerToConst) {\n  const Matcher<std::unique_ptr<const int>> m = Pointee(Ge(0));\n\n  // There's no implicit conversion from unique_ptr<int> to const\n  // unique_ptr<const int>, so we must pass a unique_ptr<const int> into the\n  // matcher.\n  std::unique_ptr<const int> n(new int(1));\n  EXPECT_TRUE(m.Matches(n));\n}\n\nTEST(PointerTest, RawPointer) {\n  int n = 1;\n  const Matcher<int*> m = Pointer(Eq(&n));\n\n  EXPECT_TRUE(m.Matches(&n));\n\n  int* p = nullptr;\n  EXPECT_FALSE(m.Matches(p));\n  EXPECT_FALSE(m.Matches(nullptr));\n}\n\nTEST(PointerTest, RawPointerToConst) {\n  int n = 1;\n  const Matcher<const int*> m = Pointer(Eq(&n));\n\n  EXPECT_TRUE(m.Matches(&n));\n\n  int* p = nullptr;\n  EXPECT_FALSE(m.Matches(p));\n  EXPECT_FALSE(m.Matches(nullptr));\n}\n\nTEST(PointerTest, SmartPointer) {\n  std::unique_ptr<int> n(new int(10));\n  int* raw_n = n.get();\n  const Matcher<std::unique_ptr<int>> m = Pointer(Eq(raw_n));\n\n  EXPECT_TRUE(m.Matches(n));\n}\n\nTEST(PointerTest, SmartPointerToConst) {\n  std::unique_ptr<const int> n(new int(10));\n  const int* raw_n = n.get();\n  const Matcher<std::unique_ptr<const int>> m = Pointer(Eq(raw_n));\n\n  // There's no implicit conversion from unique_ptr<int> to const\n  // unique_ptr<const int>, so we must pass a unique_ptr<const int> into the\n  // matcher.\n  std::unique_ptr<const int> p(new int(10));\n  EXPECT_FALSE(m.Matches(p));\n}\n\n// Minimal const-propagating pointer.\ntemplate <typename T>\nclass ConstPropagatingPtr {\n public:\n  typedef T element_type;\n\n  ConstPropagatingPtr() : val_() {}\n  explicit ConstPropagatingPtr(T* t) : val_(t) {}\n  ConstPropagatingPtr(const ConstPropagatingPtr& other) : val_(other.val_) {}\n\n  T* get() { return val_; }\n  T& operator*() { return *val_; }\n  // Most smart pointers return non-const T* and T& from the next methods.\n  const T* get() const { return val_; }\n  const T& operator*() const { return *val_; }\n\n private:\n  T* val_;\n};\n\nINSTANTIATE_GTEST_MATCHER_TEST_P(PointeeTest);\n\nTEST(PointeeTest, WorksWithConstPropagatingPointers) {\n  const Matcher<ConstPropagatingPtr<int>> m = Pointee(Lt(5));\n  int three = 3;\n  const ConstPropagatingPtr<int> co(&three);\n  ConstPropagatingPtr<int> o(&three);\n  EXPECT_TRUE(m.Matches(o));\n  EXPECT_TRUE(m.Matches(co));\n  *o = 6;\n  EXPECT_FALSE(m.Matches(o));\n  EXPECT_FALSE(m.Matches(ConstPropagatingPtr<int>()));\n}\n\nTEST(PointeeTest, NeverMatchesNull) {\n  const Matcher<const char*> m = Pointee(_);\n  EXPECT_FALSE(m.Matches(nullptr));\n}\n\n// Tests that we can write Pointee(value) instead of Pointee(Eq(value)).\nTEST(PointeeTest, MatchesAgainstAValue) {\n  const Matcher<int*> m = Pointee(5);\n\n  int n = 5;\n  EXPECT_TRUE(m.Matches(&n));\n  n = -1;\n  EXPECT_FALSE(m.Matches(&n));\n  EXPECT_FALSE(m.Matches(nullptr));\n}\n\nTEST(PointeeTest, CanDescribeSelf) {\n  const Matcher<int*> m = Pointee(Gt(3));\n  EXPECT_EQ(\"points to a value that is > 3\", Describe(m));\n  EXPECT_EQ(\"does not point to a value that is > 3\", DescribeNegation(m));\n}\n\nTEST_P(PointeeTestP, CanExplainMatchResult) {\n  const Matcher<const std::string*> m = Pointee(StartsWith(\"Hi\"));\n\n  EXPECT_EQ(\"\", Explain(m, static_cast<const std::string*>(nullptr)));\n\n  const Matcher<long*> m2 = Pointee(GreaterThan(1));  // NOLINT\n  long n = 3;                                         // NOLINT\n  EXPECT_EQ(\"which points to 3\" + OfType(\"long\") + \", which is 2 more than 1\",\n            Explain(m2, &n));\n}\n\nTEST(PointeeTest, AlwaysExplainsPointee) {\n  const Matcher<int*> m = Pointee(0);\n  int n = 42;\n  EXPECT_EQ(\"which points to 42\" + OfType(\"int\"), Explain(m, &n));\n}\n\n// An uncopyable class.\nclass Uncopyable {\n public:\n  Uncopyable() : value_(-1) {}\n  explicit Uncopyable(int a_value) : value_(a_value) {}\n\n  int value() const { return value_; }\n  void set_value(int i) { value_ = i; }\n\n private:\n  int value_;\n  Uncopyable(const Uncopyable&) = delete;\n  Uncopyable& operator=(const Uncopyable&) = delete;\n};\n\n// Returns true if and only if x.value() is positive.\nbool ValueIsPositive(const Uncopyable& x) { return x.value() > 0; }\n\nMATCHER_P(UncopyableIs, inner_matcher, \"\") {\n  return ExplainMatchResult(inner_matcher, arg.value(), result_listener);\n}\n\n// A user-defined struct for testing Field().\nstruct AStruct {\n  AStruct() : x(0), y(1.0), z(5), p(nullptr) {}\n  AStruct(const AStruct& rhs)\n      : x(rhs.x), y(rhs.y), z(rhs.z.value()), p(rhs.p) {}\n\n  int x;           // A non-const field.\n  const double y;  // A const field.\n  Uncopyable z;    // An uncopyable field.\n  const char* p;   // A pointer field.\n};\n\n// A derived struct for testing Field().\nstruct DerivedStruct : public AStruct {\n  char ch;\n};\n\nINSTANTIATE_GTEST_MATCHER_TEST_P(FieldTest);\n\n// Tests that Field(&Foo::field, ...) works when field is non-const.\nTEST(FieldTest, WorksForNonConstField) {\n  Matcher<AStruct> m = Field(&AStruct::x, Ge(0));\n  Matcher<AStruct> m_with_name = Field(\"x\", &AStruct::x, Ge(0));\n\n  AStruct a;\n  EXPECT_TRUE(m.Matches(a));\n  EXPECT_TRUE(m_with_name.Matches(a));\n  a.x = -1;\n  EXPECT_FALSE(m.Matches(a));\n  EXPECT_FALSE(m_with_name.Matches(a));\n}\n\n// Tests that Field(&Foo::field, ...) works when field is const.\nTEST(FieldTest, WorksForConstField) {\n  AStruct a;\n\n  Matcher<AStruct> m = Field(&AStruct::y, Ge(0.0));\n  Matcher<AStruct> m_with_name = Field(\"y\", &AStruct::y, Ge(0.0));\n  EXPECT_TRUE(m.Matches(a));\n  EXPECT_TRUE(m_with_name.Matches(a));\n  m = Field(&AStruct::y, Le(0.0));\n  m_with_name = Field(\"y\", &AStruct::y, Le(0.0));\n  EXPECT_FALSE(m.Matches(a));\n  EXPECT_FALSE(m_with_name.Matches(a));\n}\n\n// Tests that Field(&Foo::field, ...) works when field is not copyable.\nTEST(FieldTest, WorksForUncopyableField) {\n  AStruct a;\n\n  Matcher<AStruct> m = Field(&AStruct::z, Truly(ValueIsPositive));\n  EXPECT_TRUE(m.Matches(a));\n  m = Field(&AStruct::z, Not(Truly(ValueIsPositive)));\n  EXPECT_FALSE(m.Matches(a));\n}\n\n// Tests that Field(&Foo::field, ...) works when field is a pointer.\nTEST(FieldTest, WorksForPointerField) {\n  // Matching against NULL.\n  Matcher<AStruct> m = Field(&AStruct::p, static_cast<const char*>(nullptr));\n  AStruct a;\n  EXPECT_TRUE(m.Matches(a));\n  a.p = \"hi\";\n  EXPECT_FALSE(m.Matches(a));\n\n  // Matching a pointer that is not NULL.\n  m = Field(&AStruct::p, StartsWith(\"hi\"));\n  a.p = \"hill\";\n  EXPECT_TRUE(m.Matches(a));\n  a.p = \"hole\";\n  EXPECT_FALSE(m.Matches(a));\n}\n\n// Tests that Field() works when the object is passed by reference.\nTEST(FieldTest, WorksForByRefArgument) {\n  Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));\n\n  AStruct a;\n  EXPECT_TRUE(m.Matches(a));\n  a.x = -1;\n  EXPECT_FALSE(m.Matches(a));\n}\n\n// Tests that Field(&Foo::field, ...) works when the argument's type\n// is a sub-type of Foo.\nTEST(FieldTest, WorksForArgumentOfSubType) {\n  // Note that the matcher expects DerivedStruct but we say AStruct\n  // inside Field().\n  Matcher<const DerivedStruct&> m = Field(&AStruct::x, Ge(0));\n\n  DerivedStruct d;\n  EXPECT_TRUE(m.Matches(d));\n  d.x = -1;\n  EXPECT_FALSE(m.Matches(d));\n}\n\n// Tests that Field(&Foo::field, m) works when field's type and m's\n// argument type are compatible but not the same.\nTEST(FieldTest, WorksForCompatibleMatcherType) {\n  // The field is an int, but the inner matcher expects a signed char.\n  Matcher<const AStruct&> m = Field(&AStruct::x, Matcher<signed char>(Ge(0)));\n\n  AStruct a;\n  EXPECT_TRUE(m.Matches(a));\n  a.x = -1;\n  EXPECT_FALSE(m.Matches(a));\n}\n\n// Tests that Field() can describe itself.\nTEST(FieldTest, CanDescribeSelf) {\n  Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));\n\n  EXPECT_EQ(\"is an object whose given field is >= 0\", Describe(m));\n  EXPECT_EQ(\"is an object whose given field isn't >= 0\", DescribeNegation(m));\n}\n\nTEST(FieldTest, CanDescribeSelfWithFieldName) {\n  Matcher<const AStruct&> m = Field(\"field_name\", &AStruct::x, Ge(0));\n\n  EXPECT_EQ(\"is an object whose field `field_name` is >= 0\", Describe(m));\n  EXPECT_EQ(\"is an object whose field `field_name` isn't >= 0\",\n            DescribeNegation(m));\n}\n\n// Tests that Field() can explain the match result.\nTEST_P(FieldTestP, CanExplainMatchResult) {\n  Matcher<const AStruct&> m = Field(&AStruct::x, Ge(0));\n\n  AStruct a;\n  a.x = 1;\n  EXPECT_EQ(\"whose given field is 1\" + OfType(\"int\"), Explain(m, a));\n\n  m = Field(&AStruct::x, GreaterThan(0));\n  EXPECT_EQ(\n      \"whose given field is 1\" + OfType(\"int\") + \", which is 1 more than 0\",\n      Explain(m, a));\n}\n\nTEST_P(FieldTestP, CanExplainMatchResultWithFieldName) {\n  Matcher<const AStruct&> m = Field(\"field_name\", &AStruct::x, Ge(0));\n\n  AStruct a;\n  a.x = 1;\n  EXPECT_EQ(\"whose field `field_name` is 1\" + OfType(\"int\"), Explain(m, a));\n\n  m = Field(\"field_name\", &AStruct::x, GreaterThan(0));\n  EXPECT_EQ(\"whose field `field_name` is 1\" + OfType(\"int\") +\n                \", which is 1 more than 0\",\n            Explain(m, a));\n}\n\nINSTANTIATE_GTEST_MATCHER_TEST_P(FieldForPointerTest);\n\n// Tests that Field() works when the argument is a pointer to const.\nTEST(FieldForPointerTest, WorksForPointerToConst) {\n  Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));\n\n  AStruct a;\n  EXPECT_TRUE(m.Matches(&a));\n  a.x = -1;\n  EXPECT_FALSE(m.Matches(&a));\n}\n\n// Tests that Field() works when the argument is a pointer to non-const.\nTEST(FieldForPointerTest, WorksForPointerToNonConst) {\n  Matcher<AStruct*> m = Field(&AStruct::x, Ge(0));\n\n  AStruct a;\n  EXPECT_TRUE(m.Matches(&a));\n  a.x = -1;\n  EXPECT_FALSE(m.Matches(&a));\n}\n\n// Tests that Field() works when the argument is a reference to a const pointer.\nTEST(FieldForPointerTest, WorksForReferenceToConstPointer) {\n  Matcher<AStruct* const&> m = Field(&AStruct::x, Ge(0));\n\n  AStruct a;\n  EXPECT_TRUE(m.Matches(&a));\n  a.x = -1;\n  EXPECT_FALSE(m.Matches(&a));\n}\n\n// Tests that Field() does not match the NULL pointer.\nTEST(FieldForPointerTest, DoesNotMatchNull) {\n  Matcher<const AStruct*> m = Field(&AStruct::x, _);\n  EXPECT_FALSE(m.Matches(nullptr));\n}\n\n// Tests that Field(&Foo::field, ...) works when the argument's type\n// is a sub-type of const Foo*.\nTEST(FieldForPointerTest, WorksForArgumentOfSubType) {\n  // Note that the matcher expects DerivedStruct but we say AStruct\n  // inside Field().\n  Matcher<DerivedStruct*> m = Field(&AStruct::x, Ge(0));\n\n  DerivedStruct d;\n  EXPECT_TRUE(m.Matches(&d));\n  d.x = -1;\n  EXPECT_FALSE(m.Matches(&d));\n}\n\n// Tests that Field() can describe itself when used to match a pointer.\nTEST(FieldForPointerTest, CanDescribeSelf) {\n  Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));\n\n  EXPECT_EQ(\"is an object whose given field is >= 0\", Describe(m));\n  EXPECT_EQ(\"is an object whose given field isn't >= 0\", DescribeNegation(m));\n}\n\nTEST(FieldForPointerTest, CanDescribeSelfWithFieldName) {\n  Matcher<const AStruct*> m = Field(\"field_name\", &AStruct::x, Ge(0));\n\n  EXPECT_EQ(\"is an object whose field `field_name` is >= 0\", Describe(m));\n  EXPECT_EQ(\"is an object whose field `field_name` isn't >= 0\",\n            DescribeNegation(m));\n}\n\n// Tests that Field() can explain the result of matching a pointer.\nTEST_P(FieldForPointerTestP, CanExplainMatchResult) {\n  Matcher<const AStruct*> m = Field(&AStruct::x, Ge(0));\n\n  AStruct a;\n  a.x = 1;\n  EXPECT_EQ(\"\", Explain(m, static_cast<const AStruct*>(nullptr)));\n  EXPECT_EQ(\"which points to an object whose given field is 1\" + OfType(\"int\"),\n            Explain(m, &a));\n\n  m = Field(&AStruct::x, GreaterThan(0));\n  EXPECT_EQ(\"which points to an object whose given field is 1\" + OfType(\"int\") +\n                \", which is 1 more than 0\",\n            Explain(m, &a));\n}\n\nTEST_P(FieldForPointerTestP, CanExplainMatchResultWithFieldName) {\n  Matcher<const AStruct*> m = Field(\"field_name\", &AStruct::x, Ge(0));\n\n  AStruct a;\n  a.x = 1;\n  EXPECT_EQ(\"\", Explain(m, static_cast<const AStruct*>(nullptr)));\n  EXPECT_EQ(\n      \"which points to an object whose field `field_name` is 1\" + OfType(\"int\"),\n      Explain(m, &a));\n\n  m = Field(\"field_name\", &AStruct::x, GreaterThan(0));\n  EXPECT_EQ(\"which points to an object whose field `field_name` is 1\" +\n                OfType(\"int\") + \", which is 1 more than 0\",\n            Explain(m, &a));\n}\n\n// A user-defined class for testing Property().\nclass AClass {\n public:\n  AClass() : n_(0) {}\n\n  // A getter that returns a non-reference.\n  int n() const { return n_; }\n\n  void set_n(int new_n) { n_ = new_n; }\n\n  // A getter that returns a reference to const.\n  const std::string& s() const { return s_; }\n\n  const std::string& s_ref() const& { return s_; }\n\n  void set_s(const std::string& new_s) { s_ = new_s; }\n\n  // A getter that returns a reference to non-const.\n  double& x() const { return x_; }\n\n private:\n  int n_;\n  std::string s_;\n\n  static double x_;\n};\n\ndouble AClass::x_ = 0.0;\n\n// A derived class for testing Property().\nclass DerivedClass : public AClass {\n public:\n  int k() const { return k_; }\n\n private:\n  int k_;\n};\n\nINSTANTIATE_GTEST_MATCHER_TEST_P(PropertyTest);\n\n// Tests that Property(&Foo::property, ...) works when property()\n// returns a non-reference.\nTEST(PropertyTest, WorksForNonReferenceProperty) {\n  Matcher<const AClass&> m = Property(&AClass::n, Ge(0));\n  Matcher<const AClass&> m_with_name = Property(\"n\", &AClass::n, Ge(0));\n\n  AClass a;\n  a.set_n(1);\n  EXPECT_TRUE(m.Matches(a));\n  EXPECT_TRUE(m_with_name.Matches(a));\n\n  a.set_n(-1);\n  EXPECT_FALSE(m.Matches(a));\n  EXPECT_FALSE(m_with_name.Matches(a));\n}\n\n// Tests that Property(&Foo::property, ...) works when property()\n// returns a reference to const.\nTEST(PropertyTest, WorksForReferenceToConstProperty) {\n  Matcher<const AClass&> m = Property(&AClass::s, StartsWith(\"hi\"));\n  Matcher<const AClass&> m_with_name =\n      Property(\"s\", &AClass::s, StartsWith(\"hi\"));\n\n  AClass a;\n  a.set_s(\"hill\");\n  EXPECT_TRUE(m.Matches(a));\n  EXPECT_TRUE(m_with_name.Matches(a));\n\n  a.set_s(\"hole\");\n  EXPECT_FALSE(m.Matches(a));\n  EXPECT_FALSE(m_with_name.Matches(a));\n}\n\n// Tests that Property(&Foo::property, ...) works when property() is\n// ref-qualified.\nTEST(PropertyTest, WorksForRefQualifiedProperty) {\n  Matcher<const AClass&> m = Property(&AClass::s_ref, StartsWith(\"hi\"));\n  Matcher<const AClass&> m_with_name =\n      Property(\"s\", &AClass::s_ref, StartsWith(\"hi\"));\n\n  AClass a;\n  a.set_s(\"hill\");\n  EXPECT_TRUE(m.Matches(a));\n  EXPECT_TRUE(m_with_name.Matches(a));\n\n  a.set_s(\"hole\");\n  EXPECT_FALSE(m.Matches(a));\n  EXPECT_FALSE(m_with_name.Matches(a));\n}\n\n// Tests that Property(&Foo::property, ...) works when property()\n// returns a reference to non-const.\nTEST(PropertyTest, WorksForReferenceToNonConstProperty) {\n  double x = 0.0;\n  AClass a;\n\n  Matcher<const AClass&> m = Property(&AClass::x, Ref(x));\n  EXPECT_FALSE(m.Matches(a));\n\n  m = Property(&AClass::x, Not(Ref(x)));\n  EXPECT_TRUE(m.Matches(a));\n}\n\n// Tests that Property(&Foo::property, ...) works when the argument is\n// passed by value.\nTEST(PropertyTest, WorksForByValueArgument) {\n  Matcher<AClass> m = Property(&AClass::s, StartsWith(\"hi\"));\n\n  AClass a;\n  a.set_s(\"hill\");\n  EXPECT_TRUE(m.Matches(a));\n\n  a.set_s(\"hole\");\n  EXPECT_FALSE(m.Matches(a));\n}\n\n// Tests that Property(&Foo::property, ...) works when the argument's\n// type is a sub-type of Foo.\nTEST(PropertyTest, WorksForArgumentOfSubType) {\n  // The matcher expects a DerivedClass, but inside the Property() we\n  // say AClass.\n  Matcher<const DerivedClass&> m = Property(&AClass::n, Ge(0));\n\n  DerivedClass d;\n  d.set_n(1);\n  EXPECT_TRUE(m.Matches(d));\n\n  d.set_n(-1);\n  EXPECT_FALSE(m.Matches(d));\n}\n\n// Tests that Property(&Foo::property, m) works when property()'s type\n// and m's argument type are compatible but different.\nTEST(PropertyTest, WorksForCompatibleMatcherType) {\n  // n() returns an int but the inner matcher expects a signed char.\n  Matcher<const AClass&> m = Property(&AClass::n, Matcher<signed char>(Ge(0)));\n\n  Matcher<const AClass&> m_with_name =\n      Property(\"n\", &AClass::n, Matcher<signed char>(Ge(0)));\n\n  AClass a;\n  EXPECT_TRUE(m.Matches(a));\n  EXPECT_TRUE(m_with_name.Matches(a));\n  a.set_n(-1);\n  EXPECT_FALSE(m.Matches(a));\n  EXPECT_FALSE(m_with_name.Matches(a));\n}\n\n// Tests that Property() can describe itself.\nTEST(PropertyTest, CanDescribeSelf) {\n  Matcher<const AClass&> m = Property(&AClass::n, Ge(0));\n\n  EXPECT_EQ(\"is an object whose given property is >= 0\", Describe(m));\n  EXPECT_EQ(\"is an object whose given property isn't >= 0\",\n            DescribeNegation(m));\n}\n\nTEST(PropertyTest, CanDescribeSelfWithPropertyName) {\n  Matcher<const AClass&> m = Property(\"fancy_name\", &AClass::n, Ge(0));\n\n  EXPECT_EQ(\"is an object whose property `fancy_name` is >= 0\", Describe(m));\n  EXPECT_EQ(\"is an object whose property `fancy_name` isn't >= 0\",\n            DescribeNegation(m));\n}\n\n// Tests that Property() can explain the match result.\nTEST_P(PropertyTestP, CanExplainMatchResult) {\n  Matcher<const AClass&> m = Property(&AClass::n, Ge(0));\n\n  AClass a;\n  a.set_n(1);\n  EXPECT_EQ(\"whose given property is 1\" + OfType(\"int\"), Explain(m, a));\n\n  m = Property(&AClass::n, GreaterThan(0));\n  EXPECT_EQ(\n      \"whose given property is 1\" + OfType(\"int\") + \", which is 1 more than 0\",\n      Explain(m, a));\n}\n\nTEST_P(PropertyTestP, CanExplainMatchResultWithPropertyName) {\n  Matcher<const AClass&> m = Property(\"fancy_name\", &AClass::n, Ge(0));\n\n  AClass a;\n  a.set_n(1);\n  EXPECT_EQ(\"whose property `fancy_name` is 1\" + OfType(\"int\"), Explain(m, a));\n\n  m = Property(\"fancy_name\", &AClass::n, GreaterThan(0));\n  EXPECT_EQ(\"whose property `fancy_name` is 1\" + OfType(\"int\") +\n                \", which is 1 more than 0\",\n            Explain(m, a));\n}\n\nINSTANTIATE_GTEST_MATCHER_TEST_P(PropertyForPointerTest);\n\n// Tests that Property() works when the argument is a pointer to const.\nTEST(PropertyForPointerTest, WorksForPointerToConst) {\n  Matcher<const AClass*> m = Property(&AClass::n, Ge(0));\n\n  AClass a;\n  a.set_n(1);\n  EXPECT_TRUE(m.Matches(&a));\n\n  a.set_n(-1);\n  EXPECT_FALSE(m.Matches(&a));\n}\n\n// Tests that Property() works when the argument is a pointer to non-const.\nTEST(PropertyForPointerTest, WorksForPointerToNonConst) {\n  Matcher<AClass*> m = Property(&AClass::s, StartsWith(\"hi\"));\n\n  AClass a;\n  a.set_s(\"hill\");\n  EXPECT_TRUE(m.Matches(&a));\n\n  a.set_s(\"hole\");\n  EXPECT_FALSE(m.Matches(&a));\n}\n\n// Tests that Property() works when the argument is a reference to a\n// const pointer.\nTEST(PropertyForPointerTest, WorksForReferenceToConstPointer) {\n  Matcher<AClass* const&> m = Property(&AClass::s, StartsWith(\"hi\"));\n\n  AClass a;\n  a.set_s(\"hill\");\n  EXPECT_TRUE(m.Matches(&a));\n\n  a.set_s(\"hole\");\n  EXPECT_FALSE(m.Matches(&a));\n}\n\n// Tests that Property() does not match the NULL pointer.\nTEST(PropertyForPointerTest, WorksForReferenceToNonConstProperty) {\n  Matcher<const AClass*> m = Property(&AClass::x, _);\n  EXPECT_FALSE(m.Matches(nullptr));\n}\n\n// Tests that Property(&Foo::property, ...) works when the argument's\n// type is a sub-type of const Foo*.\nTEST(PropertyForPointerTest, WorksForArgumentOfSubType) {\n  // The matcher expects a DerivedClass, but inside the Property() we\n  // say AClass.\n  Matcher<const DerivedClass*> m = Property(&AClass::n, Ge(0));\n\n  DerivedClass d;\n  d.set_n(1);\n  EXPECT_TRUE(m.Matches(&d));\n\n  d.set_n(-1);\n  EXPECT_FALSE(m.Matches(&d));\n}\n\n// Tests that Property() can describe itself when used to match a pointer.\nTEST(PropertyForPointerTest, CanDescribeSelf) {\n  Matcher<const AClass*> m = Property(&AClass::n, Ge(0));\n\n  EXPECT_EQ(\"is an object whose given property is >= 0\", Describe(m));\n  EXPECT_EQ(\"is an object whose given property isn't >= 0\",\n            DescribeNegation(m));\n}\n\nTEST(PropertyForPointerTest, CanDescribeSelfWithPropertyDescription) {\n  Matcher<const AClass*> m = Property(\"fancy_name\", &AClass::n, Ge(0));\n\n  EXPECT_EQ(\"is an object whose property `fancy_name` is >= 0\", Describe(m));\n  EXPECT_EQ(\"is an object whose property `fancy_name` isn't >= 0\",\n            DescribeNegation(m));\n}\n\n// Tests that Property() can explain the result of matching a pointer.\nTEST_P(PropertyForPointerTestP, CanExplainMatchResult) {\n  Matcher<const AClass*> m = Property(&AClass::n, Ge(0));\n\n  AClass a;\n  a.set_n(1);\n  EXPECT_EQ(\"\", Explain(m, static_cast<const AClass*>(nullptr)));\n  EXPECT_EQ(\n      \"which points to an object whose given property is 1\" + OfType(\"int\"),\n      Explain(m, &a));\n\n  m = Property(&AClass::n, GreaterThan(0));\n  EXPECT_EQ(\"which points to an object whose given property is 1\" +\n                OfType(\"int\") + \", which is 1 more than 0\",\n            Explain(m, &a));\n}\n\nTEST_P(PropertyForPointerTestP, CanExplainMatchResultWithPropertyName) {\n  Matcher<const AClass*> m = Property(\"fancy_name\", &AClass::n, Ge(0));\n\n  AClass a;\n  a.set_n(1);\n  EXPECT_EQ(\"\", Explain(m, static_cast<const AClass*>(nullptr)));\n  EXPECT_EQ(\"which points to an object whose property `fancy_name` is 1\" +\n                OfType(\"int\"),\n            Explain(m, &a));\n\n  m = Property(\"fancy_name\", &AClass::n, GreaterThan(0));\n  EXPECT_EQ(\"which points to an object whose property `fancy_name` is 1\" +\n                OfType(\"int\") + \", which is 1 more than 0\",\n            Explain(m, &a));\n}\n\n// Tests ResultOf.\n\n// Tests that ResultOf(f, ...) compiles and works as expected when f is a\n// function pointer.\nstd::string IntToStringFunction(int input) {\n  return input == 1 ? \"foo\" : \"bar\";\n}\n\nINSTANTIATE_GTEST_MATCHER_TEST_P(ResultOfTest);\n\nTEST(ResultOfTest, WorksForFunctionPointers) {\n  Matcher<int> matcher = ResultOf(&IntToStringFunction, Eq(std::string(\"foo\")));\n\n  EXPECT_TRUE(matcher.Matches(1));\n  EXPECT_FALSE(matcher.Matches(2));\n}\n\n// Tests that ResultOf() can describe itself.\nTEST(ResultOfTest, CanDescribeItself) {\n  Matcher<int> matcher = ResultOf(&IntToStringFunction, StrEq(\"foo\"));\n\n  EXPECT_EQ(\n      \"is mapped by the given callable to a value that \"\n      \"is equal to \\\"foo\\\"\",\n      Describe(matcher));\n  EXPECT_EQ(\n      \"is mapped by the given callable to a value that \"\n      \"isn't equal to \\\"foo\\\"\",\n      DescribeNegation(matcher));\n}\n\n// Tests that ResultOf() can describe itself when provided a result description.\nTEST(ResultOfTest, CanDescribeItselfWithResultDescription) {\n  Matcher<int> matcher =\n      ResultOf(\"string conversion\", &IntToStringFunction, StrEq(\"foo\"));\n\n  EXPECT_EQ(\"whose string conversion is equal to \\\"foo\\\"\", Describe(matcher));\n  EXPECT_EQ(\"whose string conversion isn't equal to \\\"foo\\\"\",\n            DescribeNegation(matcher));\n}\n\n// Tests that ResultOf() can explain the match result.\nint IntFunction(int input) { return input == 42 ? 80 : 90; }\n\nTEST_P(ResultOfTestP, CanExplainMatchResult) {\n  Matcher<int> matcher = ResultOf(&IntFunction, Ge(85));\n  EXPECT_EQ(\"which is mapped by the given callable to 90\" + OfType(\"int\"),\n            Explain(matcher, 36));\n\n  matcher = ResultOf(&IntFunction, GreaterThan(85));\n  EXPECT_EQ(\"which is mapped by the given callable to 90\" + OfType(\"int\") +\n                \", which is 5 more than 85\",\n            Explain(matcher, 36));\n}\n\nTEST_P(ResultOfTestP, CanExplainMatchResultWithResultDescription) {\n  Matcher<int> matcher = ResultOf(\"magic int conversion\", &IntFunction, Ge(85));\n  EXPECT_EQ(\"whose magic int conversion is 90\" + OfType(\"int\"),\n            Explain(matcher, 36));\n\n  matcher = ResultOf(\"magic int conversion\", &IntFunction, GreaterThan(85));\n  EXPECT_EQ(\"whose magic int conversion is 90\" + OfType(\"int\") +\n                \", which is 5 more than 85\",\n            Explain(matcher, 36));\n}\n\n// Tests that ResultOf(f, ...) compiles and works as expected when f(x)\n// returns a non-reference.\nTEST(ResultOfTest, WorksForNonReferenceResults) {\n  Matcher<int> matcher = ResultOf(&IntFunction, Eq(80));\n\n  EXPECT_TRUE(matcher.Matches(42));\n  EXPECT_FALSE(matcher.Matches(36));\n}\n\n// Tests that ResultOf(f, ...) compiles and works as expected when f(x)\n// returns a reference to non-const.\ndouble& DoubleFunction(double& input) { return input; }  // NOLINT\n\nUncopyable& RefUncopyableFunction(Uncopyable& obj) {  // NOLINT\n  return obj;\n}\n\nTEST(ResultOfTest, WorksForReferenceToNonConstResults) {\n  double x = 3.14;\n  double x2 = x;\n  Matcher<double&> matcher = ResultOf(&DoubleFunction, Ref(x));\n\n  EXPECT_TRUE(matcher.Matches(x));\n  EXPECT_FALSE(matcher.Matches(x2));\n\n  // Test that ResultOf works with uncopyable objects\n  Uncopyable obj(0);\n  Uncopyable obj2(0);\n  Matcher<Uncopyable&> matcher2 = ResultOf(&RefUncopyableFunction, Ref(obj));\n\n  EXPECT_TRUE(matcher2.Matches(obj));\n  EXPECT_FALSE(matcher2.Matches(obj2));\n}\n\n// Tests that ResultOf(f, ...) compiles and works as expected when f(x)\n// returns a reference to const.\nconst std::string& StringFunction(const std::string& input) { return input; }\n\nTEST(ResultOfTest, WorksForReferenceToConstResults) {\n  std::string s = \"foo\";\n  std::string s2 = s;\n  Matcher<const std::string&> matcher = ResultOf(&StringFunction, Ref(s));\n\n  EXPECT_TRUE(matcher.Matches(s));\n  EXPECT_FALSE(matcher.Matches(s2));\n}\n\n// Tests that ResultOf(f, m) works when f(x) and m's\n// argument types are compatible but different.\nTEST(ResultOfTest, WorksForCompatibleMatcherTypes) {\n  // IntFunction() returns int but the inner matcher expects a signed char.\n  Matcher<int> matcher = ResultOf(IntFunction, Matcher<signed char>(Ge(85)));\n\n  EXPECT_TRUE(matcher.Matches(36));\n  EXPECT_FALSE(matcher.Matches(42));\n}\n\n// Tests that the program aborts when ResultOf is passed\n// a NULL function pointer.\nTEST(ResultOfDeathTest, DiesOnNullFunctionPointers) {\n  EXPECT_DEATH_IF_SUPPORTED(\n      ResultOf(static_cast<std::string (*)(int dummy)>(nullptr),\n               Eq(std::string(\"foo\"))),\n      \"NULL function pointer is passed into ResultOf\\\\(\\\\)\\\\.\");\n}\n\n// Tests that ResultOf(f, ...) compiles and works as expected when f is a\n// function reference.\nTEST(ResultOfTest, WorksForFunctionReferences) {\n  Matcher<int> matcher = ResultOf(IntToStringFunction, StrEq(\"foo\"));\n  EXPECT_TRUE(matcher.Matches(1));\n  EXPECT_FALSE(matcher.Matches(2));\n}\n\n// Tests that ResultOf(f, ...) compiles and works as expected when f is a\n// function object.\nstruct Functor {\n  std::string operator()(int input) const { return IntToStringFunction(input); }\n};\n\nTEST(ResultOfTest, WorksForFunctors) {\n  Matcher<int> matcher = ResultOf(Functor(), Eq(std::string(\"foo\")));\n\n  EXPECT_TRUE(matcher.Matches(1));\n  EXPECT_FALSE(matcher.Matches(2));\n}\n\n// Tests that ResultOf(f, ...) compiles and works as expected when f is a\n// functor with more than one operator() defined. ResultOf() must work\n// for each defined operator().\nstruct PolymorphicFunctor {\n  typedef int result_type;\n  int operator()(int n) { return n; }\n  int operator()(const char* s) { return static_cast<int>(strlen(s)); }\n  std::string operator()(int* p) { return p ? \"good ptr\" : \"null\"; }\n};\n\nTEST(ResultOfTest, WorksForPolymorphicFunctors) {\n  Matcher<int> matcher_int = ResultOf(PolymorphicFunctor(), Ge(5));\n\n  EXPECT_TRUE(matcher_int.Matches(10));\n  EXPECT_FALSE(matcher_int.Matches(2));\n\n  Matcher<const char*> matcher_string = ResultOf(PolymorphicFunctor(), Ge(5));\n\n  EXPECT_TRUE(matcher_string.Matches(\"long string\"));\n  EXPECT_FALSE(matcher_string.Matches(\"shrt\"));\n}\n\nTEST(ResultOfTest, WorksForPolymorphicFunctorsIgnoringResultType) {\n  Matcher<int*> matcher = ResultOf(PolymorphicFunctor(), \"good ptr\");\n\n  int n = 0;\n  EXPECT_TRUE(matcher.Matches(&n));\n  EXPECT_FALSE(matcher.Matches(nullptr));\n}\n\nTEST(ResultOfTest, WorksForLambdas) {\n  Matcher<int> matcher = ResultOf(\n      [](int str_len) {\n        return std::string(static_cast<size_t>(str_len), 'x');\n      },\n      \"xxx\");\n  EXPECT_TRUE(matcher.Matches(3));\n  EXPECT_FALSE(matcher.Matches(1));\n}\n\nTEST(ResultOfTest, WorksForNonCopyableArguments) {\n  Matcher<std::unique_ptr<int>> matcher = ResultOf(\n      [](const std::unique_ptr<int>& str_len) {\n        return std::string(static_cast<size_t>(*str_len), 'x');\n      },\n      \"xxx\");\n  EXPECT_TRUE(matcher.Matches(std::unique_ptr<int>(new int(3))));\n  EXPECT_FALSE(matcher.Matches(std::unique_ptr<int>(new int(1))));\n}\n\nconst int* ReferencingFunction(const int& n) { return &n; }\n\nstruct ReferencingFunctor {\n  typedef const int* result_type;\n  result_type operator()(const int& n) { return &n; }\n};\n\nTEST(ResultOfTest, WorksForReferencingCallables) {\n  const int n = 1;\n  const int n2 = 1;\n  Matcher<const int&> matcher2 = ResultOf(ReferencingFunction, Eq(&n));\n  EXPECT_TRUE(matcher2.Matches(n));\n  EXPECT_FALSE(matcher2.Matches(n2));\n\n  Matcher<const int&> matcher3 = ResultOf(ReferencingFunctor(), Eq(&n));\n  EXPECT_TRUE(matcher3.Matches(n));\n  EXPECT_FALSE(matcher3.Matches(n2));\n}\n\nTEST(SizeIsTest, ImplementsSizeIs) {\n  vector<int> container;\n  EXPECT_THAT(container, SizeIs(0));\n  EXPECT_THAT(container, Not(SizeIs(1)));\n  container.push_back(0);\n  EXPECT_THAT(container, Not(SizeIs(0)));\n  EXPECT_THAT(container, SizeIs(1));\n  container.push_back(0);\n  EXPECT_THAT(container, Not(SizeIs(0)));\n  EXPECT_THAT(container, SizeIs(2));\n}\n\nTEST(SizeIsTest, WorksWithMap) {\n  map<std::string, int> container;\n  EXPECT_THAT(container, SizeIs(0));\n  EXPECT_THAT(container, Not(SizeIs(1)));\n  container.insert(make_pair(\"foo\", 1));\n  EXPECT_THAT(container, Not(SizeIs(0)));\n  EXPECT_THAT(container, SizeIs(1));\n  container.insert(make_pair(\"bar\", 2));\n  EXPECT_THAT(container, Not(SizeIs(0)));\n  EXPECT_THAT(container, SizeIs(2));\n}\n\nTEST(SizeIsTest, WorksWithReferences) {\n  vector<int> container;\n  Matcher<const vector<int>&> m = SizeIs(1);\n  EXPECT_THAT(container, Not(m));\n  container.push_back(0);\n  EXPECT_THAT(container, m);\n}\n\nTEST(SizeIsTest, WorksWithMoveOnly) {\n  ContainerHelper helper;\n  EXPECT_CALL(helper, Call(SizeIs(3)));\n  helper.Call(MakeUniquePtrs({1, 2, 3}));\n}\n\n// SizeIs should work for any type that provides a size() member function.\n// For example, a size_type member type should not need to be provided.\nstruct MinimalistCustomType {\n  int size() const { return 1; }\n};\nTEST(SizeIsTest, WorksWithMinimalistCustomType) {\n  MinimalistCustomType container;\n  EXPECT_THAT(container, SizeIs(1));\n  EXPECT_THAT(container, Not(SizeIs(0)));\n}\n\nTEST(SizeIsTest, CanDescribeSelf) {\n  Matcher<vector<int>> m = SizeIs(2);\n  EXPECT_EQ(\"size is equal to 2\", Describe(m));\n  EXPECT_EQ(\"size isn't equal to 2\", DescribeNegation(m));\n}\n\nTEST(SizeIsTest, ExplainsResult) {\n  Matcher<vector<int>> m1 = SizeIs(2);\n  Matcher<vector<int>> m2 = SizeIs(Lt(2u));\n  Matcher<vector<int>> m3 = SizeIs(AnyOf(0, 3));\n  Matcher<vector<int>> m4 = SizeIs(Gt(1u));\n  vector<int> container;\n  EXPECT_EQ(\"whose size 0 doesn't match\", Explain(m1, container));\n  EXPECT_EQ(\"whose size 0 matches\", Explain(m2, container));\n  EXPECT_EQ(\"whose size 0 matches\", Explain(m3, container));\n  EXPECT_EQ(\"whose size 0 doesn't match\", Explain(m4, container));\n  container.push_back(0);\n  container.push_back(0);\n  EXPECT_EQ(\"whose size 2 matches\", Explain(m1, container));\n  EXPECT_EQ(\"whose size 2 doesn't match\", Explain(m2, container));\n  EXPECT_EQ(\"whose size 2 doesn't match\", Explain(m3, container));\n  EXPECT_EQ(\"whose size 2 matches\", Explain(m4, container));\n}\n\nTEST(WhenSortedByTest, WorksForEmptyContainer) {\n  const vector<int> numbers;\n  EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre()));\n  EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1))));\n}\n\nTEST(WhenSortedByTest, WorksForNonEmptyContainer) {\n  vector<unsigned> numbers;\n  numbers.push_back(3);\n  numbers.push_back(1);\n  numbers.push_back(2);\n  numbers.push_back(2);\n  EXPECT_THAT(numbers,\n              WhenSortedBy(greater<unsigned>(), ElementsAre(3, 2, 2, 1)));\n  EXPECT_THAT(numbers,\n              Not(WhenSortedBy(greater<unsigned>(), ElementsAre(1, 2, 2, 3))));\n}\n\nTEST(WhenSortedByTest, WorksForNonVectorContainer) {\n  list<std::string> words;\n  words.push_back(\"say\");\n  words.push_back(\"hello\");\n  words.push_back(\"world\");\n  EXPECT_THAT(words, WhenSortedBy(less<std::string>(),\n                                  ElementsAre(\"hello\", \"say\", \"world\")));\n  EXPECT_THAT(words, Not(WhenSortedBy(less<std::string>(),\n                                      ElementsAre(\"say\", \"hello\", \"world\"))));\n}\n\nTEST(WhenSortedByTest, WorksForNativeArray) {\n  const int numbers[] = {1, 3, 2, 4};\n  const int sorted_numbers[] = {1, 2, 3, 4};\n  EXPECT_THAT(numbers, WhenSortedBy(less<int>(), ElementsAre(1, 2, 3, 4)));\n  EXPECT_THAT(numbers,\n              WhenSortedBy(less<int>(), ElementsAreArray(sorted_numbers)));\n  EXPECT_THAT(numbers, Not(WhenSortedBy(less<int>(), ElementsAre(1, 3, 2, 4))));\n}\n\nTEST(WhenSortedByTest, CanDescribeSelf) {\n  const Matcher<vector<int>> m = WhenSortedBy(less<int>(), ElementsAre(1, 2));\n  EXPECT_EQ(\n      \"(when sorted) has 2 elements where\\n\"\n      \"element #0 is equal to 1,\\n\"\n      \"element #1 is equal to 2\",\n      Describe(m));\n  EXPECT_EQ(\n      \"(when sorted) doesn't have 2 elements, or\\n\"\n      \"element #0 isn't equal to 1, or\\n\"\n      \"element #1 isn't equal to 2\",\n      DescribeNegation(m));\n}\n\nTEST(WhenSortedByTest, ExplainsMatchResult) {\n  const int a[] = {2, 1};\n  EXPECT_EQ(\"which is { 1, 2 } when sorted, whose element #0 doesn't match\",\n            Explain(WhenSortedBy(less<int>(), ElementsAre(2, 3)), a));\n  EXPECT_EQ(\"which is { 1, 2 } when sorted\",\n            Explain(WhenSortedBy(less<int>(), ElementsAre(1, 2)), a));\n}\n\n// WhenSorted() is a simple wrapper on WhenSortedBy().  Hence we don't\n// need to test it as exhaustively as we test the latter.\n\nTEST(WhenSortedTest, WorksForEmptyContainer) {\n  const vector<int> numbers;\n  EXPECT_THAT(numbers, WhenSorted(ElementsAre()));\n  EXPECT_THAT(numbers, Not(WhenSorted(ElementsAre(1))));\n}\n\nTEST(WhenSortedTest, WorksForNonEmptyContainer) {\n  list<std::string> words;\n  words.push_back(\"3\");\n  words.push_back(\"1\");\n  words.push_back(\"2\");\n  words.push_back(\"2\");\n  EXPECT_THAT(words, WhenSorted(ElementsAre(\"1\", \"2\", \"2\", \"3\")));\n  EXPECT_THAT(words, Not(WhenSorted(ElementsAre(\"3\", \"1\", \"2\", \"2\"))));\n}\n\nTEST(WhenSortedTest, WorksForMapTypes) {\n  map<std::string, int> word_counts;\n  word_counts[\"and\"] = 1;\n  word_counts[\"the\"] = 1;\n  word_counts[\"buffalo\"] = 2;\n  EXPECT_THAT(word_counts,\n              WhenSorted(ElementsAre(Pair(\"and\", 1), Pair(\"buffalo\", 2),\n                                     Pair(\"the\", 1))));\n  EXPECT_THAT(word_counts,\n              Not(WhenSorted(ElementsAre(Pair(\"and\", 1), Pair(\"the\", 1),\n                                         Pair(\"buffalo\", 2)))));\n}\n\nTEST(WhenSortedTest, WorksForMultiMapTypes) {\n  multimap<int, int> ifib;\n  ifib.insert(make_pair(8, 6));\n  ifib.insert(make_pair(2, 3));\n  ifib.insert(make_pair(1, 1));\n  ifib.insert(make_pair(3, 4));\n  ifib.insert(make_pair(1, 2));\n  ifib.insert(make_pair(5, 5));\n  EXPECT_THAT(ifib,\n              WhenSorted(ElementsAre(Pair(1, 1), Pair(1, 2), Pair(2, 3),\n                                     Pair(3, 4), Pair(5, 5), Pair(8, 6))));\n  EXPECT_THAT(ifib,\n              Not(WhenSorted(ElementsAre(Pair(8, 6), Pair(2, 3), Pair(1, 1),\n                                         Pair(3, 4), Pair(1, 2), Pair(5, 5)))));\n}\n\nTEST(WhenSortedTest, WorksForPolymorphicMatcher) {\n  std::deque<int> d;\n  d.push_back(2);\n  d.push_back(1);\n  EXPECT_THAT(d, WhenSorted(ElementsAre(1, 2)));\n  EXPECT_THAT(d, Not(WhenSorted(ElementsAre(2, 1))));\n}\n\nTEST(WhenSortedTest, WorksForVectorConstRefMatcher) {\n  std::deque<int> d;\n  d.push_back(2);\n  d.push_back(1);\n  Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2);\n  EXPECT_THAT(d, WhenSorted(vector_match));\n  Matcher<const std::vector<int>&> not_vector_match = ElementsAre(2, 1);\n  EXPECT_THAT(d, Not(WhenSorted(not_vector_match)));\n}\n\n// Deliberately bare pseudo-container.\n// Offers only begin() and end() accessors, yielding InputIterator.\ntemplate <typename T>\nclass Streamlike {\n private:\n  class ConstIter;\n\n public:\n  typedef ConstIter const_iterator;\n  typedef T value_type;\n\n  template <typename InIter>\n  Streamlike(InIter first, InIter last) : remainder_(first, last) {}\n\n  const_iterator begin() const {\n    return const_iterator(this, remainder_.begin());\n  }\n  const_iterator end() const { return const_iterator(this, remainder_.end()); }\n\n private:\n  class ConstIter {\n   public:\n    using iterator_category = std::input_iterator_tag;\n    using value_type = T;\n    using difference_type = ptrdiff_t;\n    using pointer = const value_type*;\n    using reference = const value_type&;\n\n    ConstIter(const Streamlike* s, typename std::list<value_type>::iterator pos)\n        : s_(s), pos_(pos) {}\n\n    const value_type& operator*() const { return *pos_; }\n    const value_type* operator->() const { return &*pos_; }\n    ConstIter& operator++() {\n      s_->remainder_.erase(pos_++);\n      return *this;\n    }\n\n    // *iter++ is required to work (see std::istreambuf_iterator).\n    // (void)iter++ is also required to work.\n    class PostIncrProxy {\n     public:\n      explicit PostIncrProxy(const value_type& value) : value_(value) {}\n      value_type operator*() const { return value_; }\n\n     private:\n      value_type value_;\n    };\n    PostIncrProxy operator++(int) {\n      PostIncrProxy proxy(**this);\n      ++(*this);\n      return proxy;\n    }\n\n    friend bool operator==(const ConstIter& a, const ConstIter& b) {\n      return a.s_ == b.s_ && a.pos_ == b.pos_;\n    }\n    friend bool operator!=(const ConstIter& a, const ConstIter& b) {\n      return !(a == b);\n    }\n\n   private:\n    const Streamlike* s_;\n    typename std::list<value_type>::iterator pos_;\n  };\n\n  friend std::ostream& operator<<(std::ostream& os, const Streamlike& s) {\n    os << \"[\";\n    typedef typename std::list<value_type>::const_iterator Iter;\n    const char* sep = \"\";\n    for (Iter it = s.remainder_.begin(); it != s.remainder_.end(); ++it) {\n      os << sep << *it;\n      sep = \",\";\n    }\n    os << \"]\";\n    return os;\n  }\n\n  mutable std::list<value_type> remainder_;  // modified by iteration\n};\n\nTEST(StreamlikeTest, Iteration) {\n  const int a[5] = {2, 1, 4, 5, 3};\n  Streamlike<int> s(a, a + 5);\n  Streamlike<int>::const_iterator it = s.begin();\n  const int* ip = a;\n  while (it != s.end()) {\n    SCOPED_TRACE(ip - a);\n    EXPECT_EQ(*ip++, *it++);\n  }\n}\n\nINSTANTIATE_GTEST_MATCHER_TEST_P(BeginEndDistanceIsTest);\n\nTEST(BeginEndDistanceIsTest, WorksWithForwardList) {\n  std::forward_list<int> container;\n  EXPECT_THAT(container, BeginEndDistanceIs(0));\n  EXPECT_THAT(container, Not(BeginEndDistanceIs(1)));\n  container.push_front(0);\n  EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));\n  EXPECT_THAT(container, BeginEndDistanceIs(1));\n  container.push_front(0);\n  EXPECT_THAT(container, Not(BeginEndDistanceIs(0)));\n  EXPECT_THAT(container, BeginEndDistanceIs(2));\n}\n\nTEST(BeginEndDistanceIsTest, WorksWithNonStdList) {\n  const int a[5] = {1, 2, 3, 4, 5};\n  Streamlike<int> s(a, a + 5);\n  EXPECT_THAT(s, BeginEndDistanceIs(5));\n}\n\nTEST(BeginEndDistanceIsTest, CanDescribeSelf) {\n  Matcher<vector<int>> m = BeginEndDistanceIs(2);\n  EXPECT_EQ(\"distance between begin() and end() is equal to 2\", Describe(m));\n  EXPECT_EQ(\"distance between begin() and end() isn't equal to 2\",\n            DescribeNegation(m));\n}\n\nTEST(BeginEndDistanceIsTest, WorksWithMoveOnly) {\n  ContainerHelper helper;\n  EXPECT_CALL(helper, Call(BeginEndDistanceIs(2)));\n  helper.Call(MakeUniquePtrs({1, 2}));\n}\n\nTEST_P(BeginEndDistanceIsTestP, ExplainsResult) {\n  Matcher<vector<int>> m1 = BeginEndDistanceIs(2);\n  Matcher<vector<int>> m2 = BeginEndDistanceIs(Lt(2));\n  Matcher<vector<int>> m3 = BeginEndDistanceIs(AnyOf(0, 3));\n  Matcher<vector<int>> m4 = BeginEndDistanceIs(GreaterThan(1));\n  vector<int> container;\n  EXPECT_EQ(\"whose distance between begin() and end() 0 doesn't match\",\n            Explain(m1, container));\n  EXPECT_EQ(\"whose distance between begin() and end() 0 matches\",\n            Explain(m2, container));\n  EXPECT_EQ(\"whose distance between begin() and end() 0 matches\",\n            Explain(m3, container));\n  EXPECT_EQ(\n      \"whose distance between begin() and end() 0 doesn't match, which is 1 \"\n      \"less than 1\",\n      Explain(m4, container));\n  container.push_back(0);\n  container.push_back(0);\n  EXPECT_EQ(\"whose distance between begin() and end() 2 matches\",\n            Explain(m1, container));\n  EXPECT_EQ(\"whose distance between begin() and end() 2 doesn't match\",\n            Explain(m2, container));\n  EXPECT_EQ(\"whose distance between begin() and end() 2 doesn't match\",\n            Explain(m3, container));\n  EXPECT_EQ(\n      \"whose distance between begin() and end() 2 matches, which is 1 more \"\n      \"than 1\",\n      Explain(m4, container));\n}\n\nTEST(WhenSortedTest, WorksForStreamlike) {\n  // Streamlike 'container' provides only minimal iterator support.\n  // Its iterators are tagged with input_iterator_tag.\n  const int a[5] = {2, 1, 4, 5, 3};\n  Streamlike<int> s(std::begin(a), std::end(a));\n  EXPECT_THAT(s, WhenSorted(ElementsAre(1, 2, 3, 4, 5)));\n  EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));\n}\n\nTEST(WhenSortedTest, WorksForVectorConstRefMatcherOnStreamlike) {\n  const int a[] = {2, 1, 4, 5, 3};\n  Streamlike<int> s(std::begin(a), std::end(a));\n  Matcher<const std::vector<int>&> vector_match = ElementsAre(1, 2, 3, 4, 5);\n  EXPECT_THAT(s, WhenSorted(vector_match));\n  EXPECT_THAT(s, Not(WhenSorted(ElementsAre(2, 1, 4, 5, 3))));\n}\n\nTEST(IsSupersetOfTest, WorksForNativeArray) {\n  const int subset[] = {1, 4};\n  const int superset[] = {1, 2, 4};\n  const int disjoint[] = {1, 0, 3};\n  EXPECT_THAT(subset, IsSupersetOf(subset));\n  EXPECT_THAT(subset, Not(IsSupersetOf(superset)));\n  EXPECT_THAT(superset, IsSupersetOf(subset));\n  EXPECT_THAT(subset, Not(IsSupersetOf(disjoint)));\n  EXPECT_THAT(disjoint, Not(IsSupersetOf(subset)));\n}\n\nTEST(IsSupersetOfTest, WorksWithDuplicates) {\n  const int not_enough[] = {1, 2};\n  const int enough[] = {1, 1, 2};\n  const int expected[] = {1, 1};\n  EXPECT_THAT(not_enough, Not(IsSupersetOf(expected)));\n  EXPECT_THAT(enough, IsSupersetOf(expected));\n}\n\nTEST(IsSupersetOfTest, WorksForEmpty) {\n  vector<int> numbers;\n  vector<int> expected;\n  EXPECT_THAT(numbers, IsSupersetOf(expected));\n  expected.push_back(1);\n  EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));\n  expected.clear();\n  numbers.push_back(1);\n  numbers.push_back(2);\n  EXPECT_THAT(numbers, IsSupersetOf(expected));\n  expected.push_back(1);\n  EXPECT_THAT(numbers, IsSupersetOf(expected));\n  expected.push_back(2);\n  EXPECT_THAT(numbers, IsSupersetOf(expected));\n  expected.push_back(3);\n  EXPECT_THAT(numbers, Not(IsSupersetOf(expected)));\n}\n\nTEST(IsSupersetOfTest, WorksForStreamlike) {\n  const int a[5] = {1, 2, 3, 4, 5};\n  Streamlike<int> s(std::begin(a), std::end(a));\n\n  vector<int> expected;\n  expected.push_back(1);\n  expected.push_back(2);\n  expected.push_back(5);\n  EXPECT_THAT(s, IsSupersetOf(expected));\n\n  expected.push_back(0);\n  EXPECT_THAT(s, Not(IsSupersetOf(expected)));\n}\n\nTEST(IsSupersetOfTest, TakesStlContainer) {\n  const int actual[] = {3, 1, 2};\n\n  ::std::list<int> expected;\n  expected.push_back(1);\n  expected.push_back(3);\n  EXPECT_THAT(actual, IsSupersetOf(expected));\n\n  expected.push_back(4);\n  EXPECT_THAT(actual, Not(IsSupersetOf(expected)));\n}\n\nTEST(IsSupersetOfTest, Describe) {\n  typedef std::vector<int> IntVec;\n  IntVec expected;\n  expected.push_back(111);\n  expected.push_back(222);\n  expected.push_back(333);\n  EXPECT_THAT(\n      Describe<IntVec>(IsSupersetOf(expected)),\n      Eq(\"a surjection from elements to requirements exists such that:\\n\"\n         \" - an element is equal to 111\\n\"\n         \" - an element is equal to 222\\n\"\n         \" - an element is equal to 333\"));\n}\n\nTEST(IsSupersetOfTest, DescribeNegation) {\n  typedef std::vector<int> IntVec;\n  IntVec expected;\n  expected.push_back(111);\n  expected.push_back(222);\n  expected.push_back(333);\n  EXPECT_THAT(\n      DescribeNegation<IntVec>(IsSupersetOf(expected)),\n      Eq(\"no surjection from elements to requirements exists such that:\\n\"\n         \" - an element is equal to 111\\n\"\n         \" - an element is equal to 222\\n\"\n         \" - an element is equal to 333\"));\n}\n\nTEST(IsSupersetOfTest, MatchAndExplain) {\n  std::vector<int> v;\n  v.push_back(2);\n  v.push_back(3);\n  std::vector<int> expected;\n  expected.push_back(1);\n  expected.push_back(2);\n  StringMatchResultListener listener;\n  ASSERT_FALSE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))\n      << listener.str();\n  EXPECT_THAT(listener.str(),\n              Eq(\"where the following matchers don't match any elements:\\n\"\n                 \"matcher #0: is equal to 1\"));\n\n  v.push_back(1);\n  listener.Clear();\n  ASSERT_TRUE(ExplainMatchResult(IsSupersetOf(expected), v, &listener))\n      << listener.str();\n  EXPECT_THAT(listener.str(), Eq(\"where:\\n\"\n                                 \" - element #0 is matched by matcher #1,\\n\"\n                                 \" - element #2 is matched by matcher #0\"));\n}\n\nTEST(IsSupersetOfTest, WorksForRhsInitializerList) {\n  const int numbers[] = {1, 3, 6, 2, 4, 5};\n  EXPECT_THAT(numbers, IsSupersetOf({1, 2}));\n  EXPECT_THAT(numbers, Not(IsSupersetOf({3, 0})));\n}\n\nTEST(IsSupersetOfTest, WorksWithMoveOnly) {\n  ContainerHelper helper;\n  EXPECT_CALL(helper, Call(IsSupersetOf({Pointee(1)})));\n  helper.Call(MakeUniquePtrs({1, 2}));\n  EXPECT_CALL(helper, Call(Not(IsSupersetOf({Pointee(1), Pointee(2)}))));\n  helper.Call(MakeUniquePtrs({2}));\n}\n\nTEST(IsSubsetOfTest, WorksForNativeArray) {\n  const int subset[] = {1, 4};\n  const int superset[] = {1, 2, 4};\n  const int disjoint[] = {1, 0, 3};\n  EXPECT_THAT(subset, IsSubsetOf(subset));\n  EXPECT_THAT(subset, IsSubsetOf(superset));\n  EXPECT_THAT(superset, Not(IsSubsetOf(subset)));\n  EXPECT_THAT(subset, Not(IsSubsetOf(disjoint)));\n  EXPECT_THAT(disjoint, Not(IsSubsetOf(subset)));\n}\n\nTEST(IsSubsetOfTest, WorksWithDuplicates) {\n  const int not_enough[] = {1, 2};\n  const int enough[] = {1, 1, 2};\n  const int actual[] = {1, 1};\n  EXPECT_THAT(actual, Not(IsSubsetOf(not_enough)));\n  EXPECT_THAT(actual, IsSubsetOf(enough));\n}\n\nTEST(IsSubsetOfTest, WorksForEmpty) {\n  vector<int> numbers;\n  vector<int> expected;\n  EXPECT_THAT(numbers, IsSubsetOf(expected));\n  expected.push_back(1);\n  EXPECT_THAT(numbers, IsSubsetOf(expected));\n  expected.clear();\n  numbers.push_back(1);\n  numbers.push_back(2);\n  EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));\n  expected.push_back(1);\n  EXPECT_THAT(numbers, Not(IsSubsetOf(expected)));\n  expected.push_back(2);\n  EXPECT_THAT(numbers, IsSubsetOf(expected));\n  expected.push_back(3);\n  EXPECT_THAT(numbers, IsSubsetOf(expected));\n}\n\nTEST(IsSubsetOfTest, WorksForStreamlike) {\n  const int a[5] = {1, 2};\n  Streamlike<int> s(std::begin(a), std::end(a));\n\n  vector<int> expected;\n  expected.push_back(1);\n  EXPECT_THAT(s, Not(IsSubsetOf(expected)));\n  expected.push_back(2);\n  expected.push_back(5);\n  EXPECT_THAT(s, IsSubsetOf(expected));\n}\n\nTEST(IsSubsetOfTest, TakesStlContainer) {\n  const int actual[] = {3, 1, 2};\n\n  ::std::list<int> expected;\n  expected.push_back(1);\n  expected.push_back(3);\n  EXPECT_THAT(actual, Not(IsSubsetOf(expected)));\n\n  expected.push_back(2);\n  expected.push_back(4);\n  EXPECT_THAT(actual, IsSubsetOf(expected));\n}\n\nTEST(IsSubsetOfTest, Describe) {\n  typedef std::vector<int> IntVec;\n  IntVec expected;\n  expected.push_back(111);\n  expected.push_back(222);\n  expected.push_back(333);\n\n  EXPECT_THAT(\n      Describe<IntVec>(IsSubsetOf(expected)),\n      Eq(\"an injection from elements to requirements exists such that:\\n\"\n         \" - an element is equal to 111\\n\"\n         \" - an element is equal to 222\\n\"\n         \" - an element is equal to 333\"));\n}\n\nTEST(IsSubsetOfTest, DescribeNegation) {\n  typedef std::vector<int> IntVec;\n  IntVec expected;\n  expected.push_back(111);\n  expected.push_back(222);\n  expected.push_back(333);\n  EXPECT_THAT(\n      DescribeNegation<IntVec>(IsSubsetOf(expected)),\n      Eq(\"no injection from elements to requirements exists such that:\\n\"\n         \" - an element is equal to 111\\n\"\n         \" - an element is equal to 222\\n\"\n         \" - an element is equal to 333\"));\n}\n\nTEST(IsSubsetOfTest, MatchAndExplain) {\n  std::vector<int> v;\n  v.push_back(2);\n  v.push_back(3);\n  std::vector<int> expected;\n  expected.push_back(1);\n  expected.push_back(2);\n  StringMatchResultListener listener;\n  ASSERT_FALSE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))\n      << listener.str();\n  EXPECT_THAT(listener.str(),\n              Eq(\"where the following elements don't match any matchers:\\n\"\n                 \"element #1: 3\"));\n\n  expected.push_back(3);\n  listener.Clear();\n  ASSERT_TRUE(ExplainMatchResult(IsSubsetOf(expected), v, &listener))\n      << listener.str();\n  EXPECT_THAT(listener.str(), Eq(\"where:\\n\"\n                                 \" - element #0 is matched by matcher #1,\\n\"\n                                 \" - element #1 is matched by matcher #2\"));\n}\n\nTEST(IsSubsetOfTest, WorksForRhsInitializerList) {\n  const int numbers[] = {1, 2, 3};\n  EXPECT_THAT(numbers, IsSubsetOf({1, 2, 3, 4}));\n  EXPECT_THAT(numbers, Not(IsSubsetOf({1, 2})));\n}\n\nTEST(IsSubsetOfTest, WorksWithMoveOnly) {\n  ContainerHelper helper;\n  EXPECT_CALL(helper, Call(IsSubsetOf({Pointee(1), Pointee(2)})));\n  helper.Call(MakeUniquePtrs({1}));\n  EXPECT_CALL(helper, Call(Not(IsSubsetOf({Pointee(1)}))));\n  helper.Call(MakeUniquePtrs({2}));\n}\n\n// Tests using ElementsAre() and ElementsAreArray() with stream-like\n// \"containers\".\n\nTEST(ElemensAreStreamTest, WorksForStreamlike) {\n  const int a[5] = {1, 2, 3, 4, 5};\n  Streamlike<int> s(std::begin(a), std::end(a));\n  EXPECT_THAT(s, ElementsAre(1, 2, 3, 4, 5));\n  EXPECT_THAT(s, Not(ElementsAre(2, 1, 4, 5, 3)));\n}\n\nTEST(ElemensAreArrayStreamTest, WorksForStreamlike) {\n  const int a[5] = {1, 2, 3, 4, 5};\n  Streamlike<int> s(std::begin(a), std::end(a));\n\n  vector<int> expected;\n  expected.push_back(1);\n  expected.push_back(2);\n  expected.push_back(3);\n  expected.push_back(4);\n  expected.push_back(5);\n  EXPECT_THAT(s, ElementsAreArray(expected));\n\n  expected[3] = 0;\n  EXPECT_THAT(s, Not(ElementsAreArray(expected)));\n}\n\nTEST(ElementsAreTest, WorksWithUncopyable) {\n  Uncopyable objs[2];\n  objs[0].set_value(-3);\n  objs[1].set_value(1);\n  EXPECT_THAT(objs, ElementsAre(UncopyableIs(-3), Truly(ValueIsPositive)));\n}\n\nTEST(ElementsAreTest, WorksWithMoveOnly) {\n  ContainerHelper helper;\n  EXPECT_CALL(helper, Call(ElementsAre(Pointee(1), Pointee(2))));\n  helper.Call(MakeUniquePtrs({1, 2}));\n\n  EXPECT_CALL(helper, Call(ElementsAreArray({Pointee(3), Pointee(4)})));\n  helper.Call(MakeUniquePtrs({3, 4}));\n}\n\nTEST(ElementsAreTest, TakesStlContainer) {\n  const int actual[] = {3, 1, 2};\n\n  ::std::list<int> expected;\n  expected.push_back(3);\n  expected.push_back(1);\n  expected.push_back(2);\n  EXPECT_THAT(actual, ElementsAreArray(expected));\n\n  expected.push_back(4);\n  EXPECT_THAT(actual, Not(ElementsAreArray(expected)));\n}\n\n// Tests for UnorderedElementsAreArray()\n\nTEST(UnorderedElementsAreArrayTest, SucceedsWhenExpected) {\n  const int a[] = {0, 1, 2, 3, 4};\n  std::vector<int> s(std::begin(a), std::end(a));\n  do {\n    StringMatchResultListener listener;\n    EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(a), s, &listener))\n        << listener.str();\n  } while (std::next_permutation(s.begin(), s.end()));\n}\n\nTEST(UnorderedElementsAreArrayTest, VectorBool) {\n  const bool a[] = {0, 1, 0, 1, 1};\n  const bool b[] = {1, 0, 1, 1, 0};\n  std::vector<bool> expected(std::begin(a), std::end(a));\n  std::vector<bool> actual(std::begin(b), std::end(b));\n  StringMatchResultListener listener;\n  EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(expected), actual,\n                                 &listener))\n      << listener.str();\n}\n\nTEST(UnorderedElementsAreArrayTest, WorksForStreamlike) {\n  // Streamlike 'container' provides only minimal iterator support.\n  // Its iterators are tagged with input_iterator_tag, and it has no\n  // size() or empty() methods.\n  const int a[5] = {2, 1, 4, 5, 3};\n  Streamlike<int> s(std::begin(a), std::end(a));\n\n  ::std::vector<int> expected;\n  expected.push_back(1);\n  expected.push_back(2);\n  expected.push_back(3);\n  expected.push_back(4);\n  expected.push_back(5);\n  EXPECT_THAT(s, UnorderedElementsAreArray(expected));\n\n  expected.push_back(6);\n  EXPECT_THAT(s, Not(UnorderedElementsAreArray(expected)));\n}\n\nTEST(UnorderedElementsAreArrayTest, TakesStlContainer) {\n  const int actual[] = {3, 1, 2};\n\n  ::std::list<int> expected;\n  expected.push_back(1);\n  expected.push_back(2);\n  expected.push_back(3);\n  EXPECT_THAT(actual, UnorderedElementsAreArray(expected));\n\n  expected.push_back(4);\n  EXPECT_THAT(actual, Not(UnorderedElementsAreArray(expected)));\n}\n\nTEST(UnorderedElementsAreArrayTest, TakesInitializerList) {\n  const int a[5] = {2, 1, 4, 5, 3};\n  EXPECT_THAT(a, UnorderedElementsAreArray({1, 2, 3, 4, 5}));\n  EXPECT_THAT(a, Not(UnorderedElementsAreArray({1, 2, 3, 4, 6})));\n}\n\nTEST(UnorderedElementsAreArrayTest, TakesInitializerListOfCStrings) {\n  const std::string a[5] = {\"a\", \"b\", \"c\", \"d\", \"e\"};\n  EXPECT_THAT(a, UnorderedElementsAreArray({\"a\", \"b\", \"c\", \"d\", \"e\"}));\n  EXPECT_THAT(a, Not(UnorderedElementsAreArray({\"a\", \"b\", \"c\", \"d\", \"ef\"})));\n}\n\nTEST(UnorderedElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {\n  const int a[5] = {2, 1, 4, 5, 3};\n  EXPECT_THAT(a,\n              UnorderedElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));\n  EXPECT_THAT(\n      a, Not(UnorderedElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));\n}\n\nTEST(UnorderedElementsAreArrayTest,\n     TakesInitializerListOfDifferentTypedMatchers) {\n  const int a[5] = {2, 1, 4, 5, 3};\n  // The compiler cannot infer the type of the initializer list if its\n  // elements have different types.  We must explicitly specify the\n  // unified element type in this case.\n  EXPECT_THAT(a, UnorderedElementsAreArray<Matcher<int>>(\n                     {Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));\n  EXPECT_THAT(a, Not(UnorderedElementsAreArray<Matcher<int>>(\n                     {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));\n}\n\nTEST(UnorderedElementsAreArrayTest, WorksWithMoveOnly) {\n  ContainerHelper helper;\n  EXPECT_CALL(helper,\n              Call(UnorderedElementsAreArray({Pointee(1), Pointee(2)})));\n  helper.Call(MakeUniquePtrs({2, 1}));\n}\n\nclass UnorderedElementsAreTest : public testing::Test {\n protected:\n  typedef std::vector<int> IntVec;\n};\n\nTEST_F(UnorderedElementsAreTest, WorksWithUncopyable) {\n  Uncopyable objs[2];\n  objs[0].set_value(-3);\n  objs[1].set_value(1);\n  EXPECT_THAT(objs,\n              UnorderedElementsAre(Truly(ValueIsPositive), UncopyableIs(-3)));\n}\n\nTEST_F(UnorderedElementsAreTest, SucceedsWhenExpected) {\n  const int a[] = {1, 2, 3};\n  std::vector<int> s(std::begin(a), std::end(a));\n  do {\n    StringMatchResultListener listener;\n    EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), s, &listener))\n        << listener.str();\n  } while (std::next_permutation(s.begin(), s.end()));\n}\n\nTEST_F(UnorderedElementsAreTest, FailsWhenAnElementMatchesNoMatcher) {\n  const int a[] = {1, 2, 3};\n  std::vector<int> s(std::begin(a), std::end(a));\n  std::vector<Matcher<int>> mv;\n  mv.push_back(1);\n  mv.push_back(2);\n  mv.push_back(2);\n  // The element with value '3' matches nothing: fail fast.\n  StringMatchResultListener listener;\n  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener))\n      << listener.str();\n}\n\nTEST_F(UnorderedElementsAreTest, WorksForStreamlike) {\n  // Streamlike 'container' provides only minimal iterator support.\n  // Its iterators are tagged with input_iterator_tag, and it has no\n  // size() or empty() methods.\n  const int a[5] = {2, 1, 4, 5, 3};\n  Streamlike<int> s(std::begin(a), std::end(a));\n\n  EXPECT_THAT(s, UnorderedElementsAre(1, 2, 3, 4, 5));\n  EXPECT_THAT(s, Not(UnorderedElementsAre(2, 2, 3, 4, 5)));\n}\n\nTEST_F(UnorderedElementsAreTest, WorksWithMoveOnly) {\n  ContainerHelper helper;\n  EXPECT_CALL(helper, Call(UnorderedElementsAre(Pointee(1), Pointee(2))));\n  helper.Call(MakeUniquePtrs({2, 1}));\n}\n\n// One naive implementation of the matcher runs in O(N!) time, which is too\n// slow for many real-world inputs. This test shows that our matcher can match\n// 100 inputs very quickly (a few milliseconds).  An O(100!) is 10^158\n// iterations and obviously effectively incomputable.\n// [ RUN      ] UnorderedElementsAreTest.Performance\n// [       OK ] UnorderedElementsAreTest.Performance (4 ms)\nTEST_F(UnorderedElementsAreTest, Performance) {\n  std::vector<int> s;\n  std::vector<Matcher<int>> mv;\n  for (int i = 0; i < 100; ++i) {\n    s.push_back(i);\n    mv.push_back(_);\n  }\n  mv[50] = Eq(0);\n  StringMatchResultListener listener;\n  EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener))\n      << listener.str();\n}\n\n// Another variant of 'Performance' with similar expectations.\n// [ RUN      ] UnorderedElementsAreTest.PerformanceHalfStrict\n// [       OK ] UnorderedElementsAreTest.PerformanceHalfStrict (4 ms)\nTEST_F(UnorderedElementsAreTest, PerformanceHalfStrict) {\n  std::vector<int> s;\n  std::vector<Matcher<int>> mv;\n  for (int i = 0; i < 100; ++i) {\n    s.push_back(i);\n    if (i & 1) {\n      mv.push_back(_);\n    } else {\n      mv.push_back(i);\n    }\n  }\n  StringMatchResultListener listener;\n  EXPECT_TRUE(ExplainMatchResult(UnorderedElementsAreArray(mv), s, &listener))\n      << listener.str();\n}\n\nTEST_F(UnorderedElementsAreTest, FailMessageCountWrong) {\n  std::vector<int> v;\n  v.push_back(4);\n  StringMatchResultListener listener;\n  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener))\n      << listener.str();\n  EXPECT_THAT(listener.str(), Eq(\"which has 1 element\"));\n}\n\nTEST_F(UnorderedElementsAreTest, FailMessageCountWrongZero) {\n  std::vector<int> v;\n  StringMatchResultListener listener;\n  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2, 3), v, &listener))\n      << listener.str();\n  EXPECT_THAT(listener.str(), Eq(\"\"));\n}\n\nTEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatchers) {\n  std::vector<int> v;\n  v.push_back(1);\n  v.push_back(1);\n  StringMatchResultListener listener;\n  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), v, &listener))\n      << listener.str();\n  EXPECT_THAT(listener.str(),\n              Eq(\"where the following matchers don't match any elements:\\n\"\n                 \"matcher #1: is equal to 2\"));\n}\n\nTEST_F(UnorderedElementsAreTest, FailMessageUnmatchedElements) {\n  std::vector<int> v;\n  v.push_back(1);\n  v.push_back(2);\n  StringMatchResultListener listener;\n  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 1), v, &listener))\n      << listener.str();\n  EXPECT_THAT(listener.str(),\n              Eq(\"where the following elements don't match any matchers:\\n\"\n                 \"element #1: 2\"));\n}\n\nTEST_F(UnorderedElementsAreTest, FailMessageUnmatchedMatcherAndElement) {\n  std::vector<int> v;\n  v.push_back(2);\n  v.push_back(3);\n  StringMatchResultListener listener;\n  EXPECT_FALSE(ExplainMatchResult(UnorderedElementsAre(1, 2), v, &listener))\n      << listener.str();\n  EXPECT_THAT(listener.str(),\n              Eq(\"where\"\n                 \" the following matchers don't match any elements:\\n\"\n                 \"matcher #0: is equal to 1\\n\"\n                 \"and\"\n                 \" where\"\n                 \" the following elements don't match any matchers:\\n\"\n                 \"element #1: 3\"));\n}\n\n// Test helper for formatting element, matcher index pairs in expectations.\nstatic std::string EMString(int element, int matcher) {\n  stringstream ss;\n  ss << \"(element #\" << element << \", matcher #\" << matcher << \")\";\n  return ss.str();\n}\n\nTEST_F(UnorderedElementsAreTest, FailMessageImperfectMatchOnly) {\n  // A situation where all elements and matchers have a match\n  // associated with them, but the max matching is not perfect.\n  std::vector<std::string> v;\n  v.push_back(\"a\");\n  v.push_back(\"b\");\n  v.push_back(\"c\");\n  StringMatchResultListener listener;\n  EXPECT_FALSE(ExplainMatchResult(\n      UnorderedElementsAre(\"a\", \"a\", AnyOf(\"b\", \"c\")), v, &listener))\n      << listener.str();\n\n  std::string prefix =\n      \"where no permutation of the elements can satisfy all matchers, \"\n      \"and the closest match is 2 of 3 matchers with the \"\n      \"pairings:\\n\";\n\n  // We have to be a bit loose here, because there are 4 valid max matches.\n  EXPECT_THAT(\n      listener.str(),\n      AnyOf(\n          prefix + \"{\\n  \" + EMString(0, 0) + \",\\n  \" + EMString(1, 2) + \"\\n}\",\n          prefix + \"{\\n  \" + EMString(0, 1) + \",\\n  \" + EMString(1, 2) + \"\\n}\",\n          prefix + \"{\\n  \" + EMString(0, 0) + \",\\n  \" + EMString(2, 2) + \"\\n}\",\n          prefix + \"{\\n  \" + EMString(0, 1) + \",\\n  \" + EMString(2, 2) +\n              \"\\n}\"));\n}\n\nTEST_F(UnorderedElementsAreTest, Describe) {\n  EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre()), Eq(\"is empty\"));\n  EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre(345)),\n              Eq(\"has 1 element and that element is equal to 345\"));\n  EXPECT_THAT(Describe<IntVec>(UnorderedElementsAre(111, 222, 333)),\n              Eq(\"has 3 elements and there exists some permutation \"\n                 \"of elements such that:\\n\"\n                 \" - element #0 is equal to 111, and\\n\"\n                 \" - element #1 is equal to 222, and\\n\"\n                 \" - element #2 is equal to 333\"));\n}\n\nTEST_F(UnorderedElementsAreTest, DescribeNegation) {\n  EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre()),\n              Eq(\"isn't empty\"));\n  EXPECT_THAT(\n      DescribeNegation<IntVec>(UnorderedElementsAre(345)),\n      Eq(\"doesn't have 1 element, or has 1 element that isn't equal to 345\"));\n  EXPECT_THAT(DescribeNegation<IntVec>(UnorderedElementsAre(123, 234, 345)),\n              Eq(\"doesn't have 3 elements, or there exists no permutation \"\n                 \"of elements such that:\\n\"\n                 \" - element #0 is equal to 123, and\\n\"\n                 \" - element #1 is equal to 234, and\\n\"\n                 \" - element #2 is equal to 345\"));\n}\n\n// Tests Each().\n\nINSTANTIATE_GTEST_MATCHER_TEST_P(EachTest);\n\nTEST_P(EachTestP, ExplainsMatchResultCorrectly) {\n  set<int> a;  // empty\n\n  Matcher<set<int>> m = Each(2);\n  EXPECT_EQ(\"\", Explain(m, a));\n\n  Matcher<const int(&)[1]> n = Each(1);  // NOLINT\n\n  const int b[1] = {1};\n  EXPECT_EQ(\"\", Explain(n, b));\n\n  n = Each(3);\n  EXPECT_EQ(\"whose element #0 doesn't match\", Explain(n, b));\n\n  a.insert(1);\n  a.insert(2);\n  a.insert(3);\n  m = Each(GreaterThan(0));\n  EXPECT_EQ(\"\", Explain(m, a));\n\n  m = Each(GreaterThan(10));\n  EXPECT_EQ(\"whose element #0 doesn't match, which is 9 less than 10\",\n            Explain(m, a));\n}\n\nTEST(EachTest, DescribesItselfCorrectly) {\n  Matcher<vector<int>> m = Each(1);\n  EXPECT_EQ(\"only contains elements that is equal to 1\", Describe(m));\n\n  Matcher<vector<int>> m2 = Not(m);\n  EXPECT_EQ(\"contains some element that isn't equal to 1\", Describe(m2));\n}\n\nTEST(EachTest, MatchesVectorWhenAllElementsMatch) {\n  vector<int> some_vector;\n  EXPECT_THAT(some_vector, Each(1));\n  some_vector.push_back(3);\n  EXPECT_THAT(some_vector, Not(Each(1)));\n  EXPECT_THAT(some_vector, Each(3));\n  some_vector.push_back(1);\n  some_vector.push_back(2);\n  EXPECT_THAT(some_vector, Not(Each(3)));\n  EXPECT_THAT(some_vector, Each(Lt(3.5)));\n\n  vector<std::string> another_vector;\n  another_vector.push_back(\"fee\");\n  EXPECT_THAT(another_vector, Each(std::string(\"fee\")));\n  another_vector.push_back(\"fie\");\n  another_vector.push_back(\"foe\");\n  another_vector.push_back(\"fum\");\n  EXPECT_THAT(another_vector, Not(Each(std::string(\"fee\"))));\n}\n\nTEST(EachTest, MatchesMapWhenAllElementsMatch) {\n  map<const char*, int> my_map;\n  const char* bar = \"a string\";\n  my_map[bar] = 2;\n  EXPECT_THAT(my_map, Each(make_pair(bar, 2)));\n\n  map<std::string, int> another_map;\n  EXPECT_THAT(another_map, Each(make_pair(std::string(\"fee\"), 1)));\n  another_map[\"fee\"] = 1;\n  EXPECT_THAT(another_map, Each(make_pair(std::string(\"fee\"), 1)));\n  another_map[\"fie\"] = 2;\n  another_map[\"foe\"] = 3;\n  another_map[\"fum\"] = 4;\n  EXPECT_THAT(another_map, Not(Each(make_pair(std::string(\"fee\"), 1))));\n  EXPECT_THAT(another_map, Not(Each(make_pair(std::string(\"fum\"), 1))));\n  EXPECT_THAT(another_map, Each(Pair(_, Gt(0))));\n}\n\nTEST(EachTest, AcceptsMatcher) {\n  const int a[] = {1, 2, 3};\n  EXPECT_THAT(a, Each(Gt(0)));\n  EXPECT_THAT(a, Not(Each(Gt(1))));\n}\n\nTEST(EachTest, WorksForNativeArrayAsTuple) {\n  const int a[] = {1, 2};\n  const int* const pointer = a;\n  EXPECT_THAT(std::make_tuple(pointer, 2), Each(Gt(0)));\n  EXPECT_THAT(std::make_tuple(pointer, 2), Not(Each(Gt(1))));\n}\n\nTEST(EachTest, WorksWithMoveOnly) {\n  ContainerHelper helper;\n  EXPECT_CALL(helper, Call(Each(Pointee(Gt(0)))));\n  helper.Call(MakeUniquePtrs({1, 2}));\n}\n\n// For testing Pointwise().\nclass IsHalfOfMatcher {\n public:\n  template <typename T1, typename T2>\n  bool MatchAndExplain(const std::tuple<T1, T2>& a_pair,\n                       MatchResultListener* listener) const {\n    if (std::get<0>(a_pair) == std::get<1>(a_pair) / 2) {\n      *listener << \"where the second is \" << std::get<1>(a_pair);\n      return true;\n    } else {\n      *listener << \"where the second/2 is \" << std::get<1>(a_pair) / 2;\n      return false;\n    }\n  }\n\n  void DescribeTo(ostream* os) const {\n    *os << \"are a pair where the first is half of the second\";\n  }\n\n  void DescribeNegationTo(ostream* os) const {\n    *os << \"are a pair where the first isn't half of the second\";\n  }\n};\n\nPolymorphicMatcher<IsHalfOfMatcher> IsHalfOf() {\n  return MakePolymorphicMatcher(IsHalfOfMatcher());\n}\n\nTEST(PointwiseTest, DescribesSelf) {\n  vector<int> rhs;\n  rhs.push_back(1);\n  rhs.push_back(2);\n  rhs.push_back(3);\n  const Matcher<const vector<int>&> m = Pointwise(IsHalfOf(), rhs);\n  EXPECT_EQ(\n      \"contains 3 values, where each value and its corresponding value \"\n      \"in { 1, 2, 3 } are a pair where the first is half of the second\",\n      Describe(m));\n  EXPECT_EQ(\n      \"doesn't contain exactly 3 values, or contains a value x at some \"\n      \"index i where x and the i-th value of { 1, 2, 3 } are a pair \"\n      \"where the first isn't half of the second\",\n      DescribeNegation(m));\n}\n\nTEST(PointwiseTest, MakesCopyOfRhs) {\n  list<signed char> rhs;\n  rhs.push_back(2);\n  rhs.push_back(4);\n\n  int lhs[] = {1, 2};\n  const Matcher<const int(&)[2]> m = Pointwise(IsHalfOf(), rhs);\n  EXPECT_THAT(lhs, m);\n\n  // Changing rhs now shouldn't affect m, which made a copy of rhs.\n  rhs.push_back(6);\n  EXPECT_THAT(lhs, m);\n}\n\nTEST(PointwiseTest, WorksForLhsNativeArray) {\n  const int lhs[] = {1, 2, 3};\n  vector<int> rhs;\n  rhs.push_back(2);\n  rhs.push_back(4);\n  rhs.push_back(6);\n  EXPECT_THAT(lhs, Pointwise(Lt(), rhs));\n  EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));\n}\n\nTEST(PointwiseTest, WorksForRhsNativeArray) {\n  const int rhs[] = {1, 2, 3};\n  vector<int> lhs;\n  lhs.push_back(2);\n  lhs.push_back(4);\n  lhs.push_back(6);\n  EXPECT_THAT(lhs, Pointwise(Gt(), rhs));\n  EXPECT_THAT(lhs, Not(Pointwise(Lt(), rhs)));\n}\n\n// Test is effective only with sanitizers.\nTEST(PointwiseTest, WorksForVectorOfBool) {\n  vector<bool> rhs(3, false);\n  rhs[1] = true;\n  vector<bool> lhs = rhs;\n  EXPECT_THAT(lhs, Pointwise(Eq(), rhs));\n  rhs[0] = true;\n  EXPECT_THAT(lhs, Not(Pointwise(Eq(), rhs)));\n}\n\nTEST(PointwiseTest, WorksForRhsInitializerList) {\n  const vector<int> lhs{2, 4, 6};\n  EXPECT_THAT(lhs, Pointwise(Gt(), {1, 2, 3}));\n  EXPECT_THAT(lhs, Not(Pointwise(Lt(), {3, 3, 7})));\n}\n\nTEST(PointwiseTest, RejectsWrongSize) {\n  const double lhs[2] = {1, 2};\n  const int rhs[1] = {0};\n  EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs)));\n  EXPECT_EQ(\"which contains 2 values\", Explain(Pointwise(Gt(), rhs), lhs));\n\n  const int rhs2[3] = {0, 1, 2};\n  EXPECT_THAT(lhs, Not(Pointwise(Gt(), rhs2)));\n}\n\nTEST(PointwiseTest, RejectsWrongContent) {\n  const double lhs[3] = {1, 2, 3};\n  const int rhs[3] = {2, 6, 4};\n  EXPECT_THAT(lhs, Not(Pointwise(IsHalfOf(), rhs)));\n  EXPECT_EQ(\n      \"where the value pair (2, 6) at index #1 don't match, \"\n      \"where the second/2 is 3\",\n      Explain(Pointwise(IsHalfOf(), rhs), lhs));\n}\n\nTEST(PointwiseTest, AcceptsCorrectContent) {\n  const double lhs[3] = {1, 2, 3};\n  const int rhs[3] = {2, 4, 6};\n  EXPECT_THAT(lhs, Pointwise(IsHalfOf(), rhs));\n  EXPECT_EQ(\"\", Explain(Pointwise(IsHalfOf(), rhs), lhs));\n}\n\nTEST(PointwiseTest, AllowsMonomorphicInnerMatcher) {\n  const double lhs[3] = {1, 2, 3};\n  const int rhs[3] = {2, 4, 6};\n  const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();\n  EXPECT_THAT(lhs, Pointwise(m1, rhs));\n  EXPECT_EQ(\"\", Explain(Pointwise(m1, rhs), lhs));\n\n  // This type works as a std::tuple<const double&, const int&> can be\n  // implicitly cast to std::tuple<double, int>.\n  const Matcher<std::tuple<double, int>> m2 = IsHalfOf();\n  EXPECT_THAT(lhs, Pointwise(m2, rhs));\n  EXPECT_EQ(\"\", Explain(Pointwise(m2, rhs), lhs));\n}\n\nMATCHER(PointeeEquals, \"Points to an equal value\") {\n  return ExplainMatchResult(::testing::Pointee(::testing::get<1>(arg)),\n                            ::testing::get<0>(arg), result_listener);\n}\n\nTEST(PointwiseTest, WorksWithMoveOnly) {\n  ContainerHelper helper;\n  EXPECT_CALL(helper, Call(Pointwise(PointeeEquals(), std::vector<int>{1, 2})));\n  helper.Call(MakeUniquePtrs({1, 2}));\n}\n\nTEST(UnorderedPointwiseTest, DescribesSelf) {\n  vector<int> rhs;\n  rhs.push_back(1);\n  rhs.push_back(2);\n  rhs.push_back(3);\n  const Matcher<const vector<int>&> m = UnorderedPointwise(IsHalfOf(), rhs);\n  EXPECT_EQ(\n      \"has 3 elements and there exists some permutation of elements such \"\n      \"that:\\n\"\n      \" - element #0 and 1 are a pair where the first is half of the second, \"\n      \"and\\n\"\n      \" - element #1 and 2 are a pair where the first is half of the second, \"\n      \"and\\n\"\n      \" - element #2 and 3 are a pair where the first is half of the second\",\n      Describe(m));\n  EXPECT_EQ(\n      \"doesn't have 3 elements, or there exists no permutation of elements \"\n      \"such that:\\n\"\n      \" - element #0 and 1 are a pair where the first is half of the second, \"\n      \"and\\n\"\n      \" - element #1 and 2 are a pair where the first is half of the second, \"\n      \"and\\n\"\n      \" - element #2 and 3 are a pair where the first is half of the second\",\n      DescribeNegation(m));\n}\n\nTEST(UnorderedPointwiseTest, MakesCopyOfRhs) {\n  list<signed char> rhs;\n  rhs.push_back(2);\n  rhs.push_back(4);\n\n  int lhs[] = {2, 1};\n  const Matcher<const int(&)[2]> m = UnorderedPointwise(IsHalfOf(), rhs);\n  EXPECT_THAT(lhs, m);\n\n  // Changing rhs now shouldn't affect m, which made a copy of rhs.\n  rhs.push_back(6);\n  EXPECT_THAT(lhs, m);\n}\n\nTEST(UnorderedPointwiseTest, WorksForLhsNativeArray) {\n  const int lhs[] = {1, 2, 3};\n  vector<int> rhs;\n  rhs.push_back(4);\n  rhs.push_back(6);\n  rhs.push_back(2);\n  EXPECT_THAT(lhs, UnorderedPointwise(Lt(), rhs));\n  EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));\n}\n\nTEST(UnorderedPointwiseTest, WorksForRhsNativeArray) {\n  const int rhs[] = {1, 2, 3};\n  vector<int> lhs;\n  lhs.push_back(4);\n  lhs.push_back(2);\n  lhs.push_back(6);\n  EXPECT_THAT(lhs, UnorderedPointwise(Gt(), rhs));\n  EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), rhs)));\n}\n\nTEST(UnorderedPointwiseTest, WorksForRhsInitializerList) {\n  const vector<int> lhs{2, 4, 6};\n  EXPECT_THAT(lhs, UnorderedPointwise(Gt(), {5, 1, 3}));\n  EXPECT_THAT(lhs, Not(UnorderedPointwise(Lt(), {1, 1, 7})));\n}\n\nTEST(UnorderedPointwiseTest, RejectsWrongSize) {\n  const double lhs[2] = {1, 2};\n  const int rhs[1] = {0};\n  EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs)));\n  EXPECT_EQ(\"which has 2 elements\",\n            Explain(UnorderedPointwise(Gt(), rhs), lhs));\n\n  const int rhs2[3] = {0, 1, 2};\n  EXPECT_THAT(lhs, Not(UnorderedPointwise(Gt(), rhs2)));\n}\n\nTEST(UnorderedPointwiseTest, RejectsWrongContent) {\n  const double lhs[3] = {1, 2, 3};\n  const int rhs[3] = {2, 6, 6};\n  EXPECT_THAT(lhs, Not(UnorderedPointwise(IsHalfOf(), rhs)));\n  EXPECT_EQ(\n      \"where the following elements don't match any matchers:\\n\"\n      \"element #1: 2\",\n      Explain(UnorderedPointwise(IsHalfOf(), rhs), lhs));\n}\n\nTEST(UnorderedPointwiseTest, AcceptsCorrectContentInSameOrder) {\n  const double lhs[3] = {1, 2, 3};\n  const int rhs[3] = {2, 4, 6};\n  EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));\n}\n\nTEST(UnorderedPointwiseTest, AcceptsCorrectContentInDifferentOrder) {\n  const double lhs[3] = {1, 2, 3};\n  const int rhs[3] = {6, 4, 2};\n  EXPECT_THAT(lhs, UnorderedPointwise(IsHalfOf(), rhs));\n}\n\nTEST(UnorderedPointwiseTest, AllowsMonomorphicInnerMatcher) {\n  const double lhs[3] = {1, 2, 3};\n  const int rhs[3] = {4, 6, 2};\n  const Matcher<std::tuple<const double&, const int&>> m1 = IsHalfOf();\n  EXPECT_THAT(lhs, UnorderedPointwise(m1, rhs));\n\n  // This type works as a std::tuple<const double&, const int&> can be\n  // implicitly cast to std::tuple<double, int>.\n  const Matcher<std::tuple<double, int>> m2 = IsHalfOf();\n  EXPECT_THAT(lhs, UnorderedPointwise(m2, rhs));\n}\n\nTEST(UnorderedPointwiseTest, WorksWithMoveOnly) {\n  ContainerHelper helper;\n  EXPECT_CALL(helper, Call(UnorderedPointwise(PointeeEquals(),\n                                              std::vector<int>{1, 2})));\n  helper.Call(MakeUniquePtrs({2, 1}));\n}\n\nTEST(PointeeTest, WorksOnMoveOnlyType) {\n  std::unique_ptr<int> p(new int(3));\n  EXPECT_THAT(p, Pointee(Eq(3)));\n  EXPECT_THAT(p, Not(Pointee(Eq(2))));\n}\n\nclass PredicateFormatterFromMatcherTest : public ::testing::Test {\n protected:\n  enum Behavior { kInitialSuccess, kAlwaysFail, kFlaky };\n\n  // A matcher that can return different results when used multiple times on the\n  // same input. No real matcher should do this; but this lets us test that we\n  // detect such behavior and fail appropriately.\n  class MockMatcher : public MatcherInterface<Behavior> {\n   public:\n    bool MatchAndExplain(Behavior behavior,\n                         MatchResultListener* listener) const override {\n      *listener << \"[MatchAndExplain]\";\n      switch (behavior) {\n        case kInitialSuccess:\n          // The first call to MatchAndExplain should use a \"not interested\"\n          // listener; so this is expected to return |true|. There should be no\n          // subsequent calls.\n          return !listener->IsInterested();\n\n        case kAlwaysFail:\n          return false;\n\n        case kFlaky:\n          // The first call to MatchAndExplain should use a \"not interested\"\n          // listener; so this will return |false|. Subsequent calls should have\n          // an \"interested\" listener; so this will return |true|, thus\n          // simulating a flaky matcher.\n          return listener->IsInterested();\n      }\n\n      GTEST_LOG_(FATAL) << \"This should never be reached\";\n      return false;\n    }\n\n    void DescribeTo(ostream* os) const override { *os << \"[DescribeTo]\"; }\n\n    void DescribeNegationTo(ostream* os) const override {\n      *os << \"[DescribeNegationTo]\";\n    }\n  };\n\n  AssertionResult RunPredicateFormatter(Behavior behavior) {\n    auto matcher = MakeMatcher(new MockMatcher);\n    PredicateFormatterFromMatcher<Matcher<Behavior>> predicate_formatter(\n        matcher);\n    return predicate_formatter(\"dummy-name\", behavior);\n  }\n};\n\nTEST_F(PredicateFormatterFromMatcherTest, ShortCircuitOnSuccess) {\n  AssertionResult result = RunPredicateFormatter(kInitialSuccess);\n  EXPECT_TRUE(result);  // Implicit cast to bool.\n  std::string expect;\n  EXPECT_EQ(expect, result.message());\n}\n\nTEST_F(PredicateFormatterFromMatcherTest, NoShortCircuitOnFailure) {\n  AssertionResult result = RunPredicateFormatter(kAlwaysFail);\n  EXPECT_FALSE(result);  // Implicit cast to bool.\n  std::string expect =\n      \"Value of: dummy-name\\nExpected: [DescribeTo]\\n\"\n      \"  Actual: 1\" +\n      OfType(internal::GetTypeName<Behavior>()) + \", [MatchAndExplain]\";\n  EXPECT_EQ(expect, result.message());\n}\n\nTEST_F(PredicateFormatterFromMatcherTest, DetectsFlakyShortCircuit) {\n  AssertionResult result = RunPredicateFormatter(kFlaky);\n  EXPECT_FALSE(result);  // Implicit cast to bool.\n  std::string expect =\n      \"Value of: dummy-name\\nExpected: [DescribeTo]\\n\"\n      \"  The matcher failed on the initial attempt; but passed when rerun to \"\n      \"generate the explanation.\\n\"\n      \"  Actual: 2\" +\n      OfType(internal::GetTypeName<Behavior>()) + \", [MatchAndExplain]\";\n  EXPECT_EQ(expect, result.message());\n}\n\n// Tests for ElementsAre().\n\nTEST(ElementsAreTest, CanDescribeExpectingNoElement) {\n  Matcher<const vector<int>&> m = ElementsAre();\n  EXPECT_EQ(\"is empty\", Describe(m));\n}\n\nTEST(ElementsAreTest, CanDescribeExpectingOneElement) {\n  Matcher<vector<int>> m = ElementsAre(Gt(5));\n  EXPECT_EQ(\"has 1 element that is > 5\", Describe(m));\n}\n\nTEST(ElementsAreTest, CanDescribeExpectingManyElements) {\n  Matcher<list<std::string>> m = ElementsAre(StrEq(\"one\"), \"two\");\n  EXPECT_EQ(\n      \"has 2 elements where\\n\"\n      \"element #0 is equal to \\\"one\\\",\\n\"\n      \"element #1 is equal to \\\"two\\\"\",\n      Describe(m));\n}\n\nTEST(ElementsAreTest, CanDescribeNegationOfExpectingNoElement) {\n  Matcher<vector<int>> m = ElementsAre();\n  EXPECT_EQ(\"isn't empty\", DescribeNegation(m));\n}\n\nTEST(ElementsAreTest, CanDescribeNegationOfExpectingOneElement) {\n  Matcher<const list<int>&> m = ElementsAre(Gt(5));\n  EXPECT_EQ(\n      \"doesn't have 1 element, or\\n\"\n      \"element #0 isn't > 5\",\n      DescribeNegation(m));\n}\n\nTEST(ElementsAreTest, CanDescribeNegationOfExpectingManyElements) {\n  Matcher<const list<std::string>&> m = ElementsAre(\"one\", \"two\");\n  EXPECT_EQ(\n      \"doesn't have 2 elements, or\\n\"\n      \"element #0 isn't equal to \\\"one\\\", or\\n\"\n      \"element #1 isn't equal to \\\"two\\\"\",\n      DescribeNegation(m));\n}\n\nTEST(ElementsAreTest, DoesNotExplainTrivialMatch) {\n  Matcher<const list<int>&> m = ElementsAre(1, Ne(2));\n\n  list<int> test_list;\n  test_list.push_back(1);\n  test_list.push_back(3);\n  EXPECT_EQ(\"\", Explain(m, test_list));  // No need to explain anything.\n}\n\nTEST_P(ElementsAreTestP, ExplainsNonTrivialMatch) {\n  Matcher<const vector<int>&> m =\n      ElementsAre(GreaterThan(1), 0, GreaterThan(2));\n\n  const int a[] = {10, 0, 100};\n  vector<int> test_vector(std::begin(a), std::end(a));\n  EXPECT_EQ(\n      \"whose element #0 matches, which is 9 more than 1,\\n\"\n      \"and whose element #2 matches, which is 98 more than 2\",\n      Explain(m, test_vector));\n}\n\nTEST(ElementsAreTest, CanExplainMismatchWrongSize) {\n  Matcher<const list<int>&> m = ElementsAre(1, 3);\n\n  list<int> test_list;\n  // No need to explain when the container is empty.\n  EXPECT_EQ(\"\", Explain(m, test_list));\n\n  test_list.push_back(1);\n  EXPECT_EQ(\"which has 1 element\", Explain(m, test_list));\n}\n\nTEST_P(ElementsAreTestP, CanExplainMismatchRightSize) {\n  Matcher<const vector<int>&> m = ElementsAre(1, GreaterThan(5));\n\n  vector<int> v;\n  v.push_back(2);\n  v.push_back(1);\n  EXPECT_EQ(\"whose element #0 doesn't match\", Explain(m, v));\n\n  v[0] = 1;\n  EXPECT_EQ(\"whose element #1 doesn't match, which is 4 less than 5\",\n            Explain(m, v));\n}\n\nTEST(ElementsAreTest, MatchesOneElementVector) {\n  vector<std::string> test_vector;\n  test_vector.push_back(\"test string\");\n\n  EXPECT_THAT(test_vector, ElementsAre(StrEq(\"test string\")));\n}\n\nTEST(ElementsAreTest, MatchesOneElementList) {\n  list<std::string> test_list;\n  test_list.push_back(\"test string\");\n\n  EXPECT_THAT(test_list, ElementsAre(\"test string\"));\n}\n\nTEST(ElementsAreTest, MatchesThreeElementVector) {\n  vector<std::string> test_vector;\n  test_vector.push_back(\"one\");\n  test_vector.push_back(\"two\");\n  test_vector.push_back(\"three\");\n\n  EXPECT_THAT(test_vector, ElementsAre(\"one\", StrEq(\"two\"), _));\n}\n\nTEST(ElementsAreTest, MatchesOneElementEqMatcher) {\n  vector<int> test_vector;\n  test_vector.push_back(4);\n\n  EXPECT_THAT(test_vector, ElementsAre(Eq(4)));\n}\n\nTEST(ElementsAreTest, MatchesOneElementAnyMatcher) {\n  vector<int> test_vector;\n  test_vector.push_back(4);\n\n  EXPECT_THAT(test_vector, ElementsAre(_));\n}\n\nTEST(ElementsAreTest, MatchesOneElementValue) {\n  vector<int> test_vector;\n  test_vector.push_back(4);\n\n  EXPECT_THAT(test_vector, ElementsAre(4));\n}\n\nTEST(ElementsAreTest, MatchesThreeElementsMixedMatchers) {\n  vector<int> test_vector;\n  test_vector.push_back(1);\n  test_vector.push_back(2);\n  test_vector.push_back(3);\n\n  EXPECT_THAT(test_vector, ElementsAre(1, Eq(2), _));\n}\n\nTEST(ElementsAreTest, MatchesTenElementVector) {\n  const int a[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n  vector<int> test_vector(std::begin(a), std::end(a));\n\n  EXPECT_THAT(test_vector,\n              // The element list can contain values and/or matchers\n              // of different types.\n              ElementsAre(0, Ge(0), _, 3, 4, Ne(2), Eq(6), 7, 8, _));\n}\n\nTEST(ElementsAreTest, DoesNotMatchWrongSize) {\n  vector<std::string> test_vector;\n  test_vector.push_back(\"test string\");\n  test_vector.push_back(\"test string\");\n\n  Matcher<vector<std::string>> m = ElementsAre(StrEq(\"test string\"));\n  EXPECT_FALSE(m.Matches(test_vector));\n}\n\nTEST(ElementsAreTest, DoesNotMatchWrongValue) {\n  vector<std::string> test_vector;\n  test_vector.push_back(\"other string\");\n\n  Matcher<vector<std::string>> m = ElementsAre(StrEq(\"test string\"));\n  EXPECT_FALSE(m.Matches(test_vector));\n}\n\nTEST(ElementsAreTest, DoesNotMatchWrongOrder) {\n  vector<std::string> test_vector;\n  test_vector.push_back(\"one\");\n  test_vector.push_back(\"three\");\n  test_vector.push_back(\"two\");\n\n  Matcher<vector<std::string>> m =\n      ElementsAre(StrEq(\"one\"), StrEq(\"two\"), StrEq(\"three\"));\n  EXPECT_FALSE(m.Matches(test_vector));\n}\n\nTEST(ElementsAreTest, WorksForNestedContainer) {\n  constexpr std::array<const char*, 2> strings = {{\"Hi\", \"world\"}};\n\n  vector<list<char>> nested;\n  for (const auto& s : strings) {\n    nested.emplace_back(s, s + strlen(s));\n  }\n\n  EXPECT_THAT(nested, ElementsAre(ElementsAre('H', Ne('e')),\n                                  ElementsAre('w', 'o', _, _, 'd')));\n  EXPECT_THAT(nested, Not(ElementsAre(ElementsAre('H', 'e'),\n                                      ElementsAre('w', 'o', _, _, 'd'))));\n}\n\nTEST(ElementsAreTest, WorksWithByRefElementMatchers) {\n  int a[] = {0, 1, 2};\n  vector<int> v(std::begin(a), std::end(a));\n\n  EXPECT_THAT(v, ElementsAre(Ref(v[0]), Ref(v[1]), Ref(v[2])));\n  EXPECT_THAT(v, Not(ElementsAre(Ref(v[0]), Ref(v[1]), Ref(a[2]))));\n}\n\nTEST(ElementsAreTest, WorksWithContainerPointerUsingPointee) {\n  int a[] = {0, 1, 2};\n  vector<int> v(std::begin(a), std::end(a));\n\n  EXPECT_THAT(&v, Pointee(ElementsAre(0, 1, _)));\n  EXPECT_THAT(&v, Not(Pointee(ElementsAre(0, _, 3))));\n}\n\nTEST(ElementsAreTest, WorksWithNativeArrayPassedByReference) {\n  int array[] = {0, 1, 2};\n  EXPECT_THAT(array, ElementsAre(0, 1, _));\n  EXPECT_THAT(array, Not(ElementsAre(1, _, _)));\n  EXPECT_THAT(array, Not(ElementsAre(0, _)));\n}\n\nclass NativeArrayPassedAsPointerAndSize {\n public:\n  NativeArrayPassedAsPointerAndSize() {}\n\n  MOCK_METHOD(void, Helper, (int* array, int size));\n\n private:\n  NativeArrayPassedAsPointerAndSize(const NativeArrayPassedAsPointerAndSize&) =\n      delete;\n  NativeArrayPassedAsPointerAndSize& operator=(\n      const NativeArrayPassedAsPointerAndSize&) = delete;\n};\n\nTEST(ElementsAreTest, WorksWithNativeArrayPassedAsPointerAndSize) {\n  int array[] = {0, 1};\n  ::std::tuple<int*, size_t> array_as_tuple(array, 2);\n  EXPECT_THAT(array_as_tuple, ElementsAre(0, 1));\n  EXPECT_THAT(array_as_tuple, Not(ElementsAre(0)));\n\n  NativeArrayPassedAsPointerAndSize helper;\n  EXPECT_CALL(helper, Helper(_, _)).With(ElementsAre(0, 1));\n  helper.Helper(array, 2);\n}\n\nTEST(ElementsAreTest, WorksWithTwoDimensionalNativeArray) {\n  const char a2[][3] = {\"hi\", \"lo\"};\n  EXPECT_THAT(a2, ElementsAre(ElementsAre('h', 'i', '\\0'),\n                              ElementsAre('l', 'o', '\\0')));\n  EXPECT_THAT(a2, ElementsAre(StrEq(\"hi\"), StrEq(\"lo\")));\n  EXPECT_THAT(a2, ElementsAre(Not(ElementsAre('h', 'o', '\\0')),\n                              ElementsAre('l', 'o', '\\0')));\n}\n\nTEST(ElementsAreTest, AcceptsStringLiteral) {\n  std::string array[] = {\"hi\", \"one\", \"two\"};\n  EXPECT_THAT(array, ElementsAre(\"hi\", \"one\", \"two\"));\n  EXPECT_THAT(array, Not(ElementsAre(\"hi\", \"one\", \"too\")));\n}\n\n// Declared here with the size unknown.  Defined AFTER the following test.\nextern const char kHi[];\n\nTEST(ElementsAreTest, AcceptsArrayWithUnknownSize) {\n  // The size of kHi is not known in this test, but ElementsAre() should\n  // still accept it.\n\n  std::string array1[] = {\"hi\"};\n  EXPECT_THAT(array1, ElementsAre(kHi));\n\n  std::string array2[] = {\"ho\"};\n  EXPECT_THAT(array2, Not(ElementsAre(kHi)));\n}\n\nconst char kHi[] = \"hi\";\n\nTEST(ElementsAreTest, MakesCopyOfArguments) {\n  int x = 1;\n  int y = 2;\n  // This should make a copy of x and y.\n  ::testing::internal::ElementsAreMatcher<std::tuple<int, int>>\n      polymorphic_matcher = ElementsAre(x, y);\n  // Changing x and y now shouldn't affect the meaning of the above matcher.\n  x = y = 0;\n  const int array1[] = {1, 2};\n  EXPECT_THAT(array1, polymorphic_matcher);\n  const int array2[] = {0, 0};\n  EXPECT_THAT(array2, Not(polymorphic_matcher));\n}\n\n// Tests for ElementsAreArray().  Since ElementsAreArray() shares most\n// of the implementation with ElementsAre(), we don't test it as\n// thoroughly here.\n\nTEST(ElementsAreArrayTest, CanBeCreatedWithValueArray) {\n  const int a[] = {1, 2, 3};\n\n  vector<int> test_vector(std::begin(a), std::end(a));\n  EXPECT_THAT(test_vector, ElementsAreArray(a));\n\n  test_vector[2] = 0;\n  EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));\n}\n\nTEST(ElementsAreArrayTest, CanBeCreatedWithArraySize) {\n  std::array<const char*, 3> a = {{\"one\", \"two\", \"three\"}};\n\n  vector<std::string> test_vector(std::begin(a), std::end(a));\n  EXPECT_THAT(test_vector, ElementsAreArray(a.data(), a.size()));\n\n  const char** p = a.data();\n  test_vector[0] = \"1\";\n  EXPECT_THAT(test_vector, Not(ElementsAreArray(p, a.size())));\n}\n\nTEST(ElementsAreArrayTest, CanBeCreatedWithoutArraySize) {\n  const char* a[] = {\"one\", \"two\", \"three\"};\n\n  vector<std::string> test_vector(std::begin(a), std::end(a));\n  EXPECT_THAT(test_vector, ElementsAreArray(a));\n\n  test_vector[0] = \"1\";\n  EXPECT_THAT(test_vector, Not(ElementsAreArray(a)));\n}\n\nTEST(ElementsAreArrayTest, CanBeCreatedWithMatcherArray) {\n  const Matcher<std::string> kMatcherArray[] = {StrEq(\"one\"), StrEq(\"two\"),\n                                                StrEq(\"three\")};\n\n  vector<std::string> test_vector;\n  test_vector.push_back(\"one\");\n  test_vector.push_back(\"two\");\n  test_vector.push_back(\"three\");\n  EXPECT_THAT(test_vector, ElementsAreArray(kMatcherArray));\n\n  test_vector.push_back(\"three\");\n  EXPECT_THAT(test_vector, Not(ElementsAreArray(kMatcherArray)));\n}\n\nTEST(ElementsAreArrayTest, CanBeCreatedWithVector) {\n  const int a[] = {1, 2, 3};\n  vector<int> test_vector(std::begin(a), std::end(a));\n  const vector<int> expected(std::begin(a), std::end(a));\n  EXPECT_THAT(test_vector, ElementsAreArray(expected));\n  test_vector.push_back(4);\n  EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));\n}\n\nTEST(ElementsAreArrayTest, TakesInitializerList) {\n  const int a[5] = {1, 2, 3, 4, 5};\n  EXPECT_THAT(a, ElementsAreArray({1, 2, 3, 4, 5}));\n  EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 5, 4})));\n  EXPECT_THAT(a, Not(ElementsAreArray({1, 2, 3, 4, 6})));\n}\n\nTEST(ElementsAreArrayTest, TakesInitializerListOfCStrings) {\n  const std::string a[5] = {\"a\", \"b\", \"c\", \"d\", \"e\"};\n  EXPECT_THAT(a, ElementsAreArray({\"a\", \"b\", \"c\", \"d\", \"e\"}));\n  EXPECT_THAT(a, Not(ElementsAreArray({\"a\", \"b\", \"c\", \"e\", \"d\"})));\n  EXPECT_THAT(a, Not(ElementsAreArray({\"a\", \"b\", \"c\", \"d\", \"ef\"})));\n}\n\nTEST(ElementsAreArrayTest, TakesInitializerListOfSameTypedMatchers) {\n  const int a[5] = {1, 2, 3, 4, 5};\n  EXPECT_THAT(a, ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(5)}));\n  EXPECT_THAT(a, Not(ElementsAreArray({Eq(1), Eq(2), Eq(3), Eq(4), Eq(6)})));\n}\n\nTEST(ElementsAreArrayTest, TakesInitializerListOfDifferentTypedMatchers) {\n  const int a[5] = {1, 2, 3, 4, 5};\n  // The compiler cannot infer the type of the initializer list if its\n  // elements have different types.  We must explicitly specify the\n  // unified element type in this case.\n  EXPECT_THAT(\n      a, ElementsAreArray<Matcher<int>>({Eq(1), Ne(-2), Ge(3), Le(4), Eq(5)}));\n  EXPECT_THAT(a, Not(ElementsAreArray<Matcher<int>>(\n                     {Eq(1), Ne(-2), Ge(3), Le(4), Eq(6)})));\n}\n\nTEST(ElementsAreArrayTest, CanBeCreatedWithMatcherVector) {\n  const int a[] = {1, 2, 3};\n  const Matcher<int> kMatchers[] = {Eq(1), Eq(2), Eq(3)};\n  vector<int> test_vector(std::begin(a), std::end(a));\n  const vector<Matcher<int>> expected(std::begin(kMatchers),\n                                      std::end(kMatchers));\n  EXPECT_THAT(test_vector, ElementsAreArray(expected));\n  test_vector.push_back(4);\n  EXPECT_THAT(test_vector, Not(ElementsAreArray(expected)));\n}\n\nTEST(ElementsAreArrayTest, CanBeCreatedWithIteratorRange) {\n  const int a[] = {1, 2, 3};\n  const vector<int> test_vector(std::begin(a), std::end(a));\n  const vector<int> expected(std::begin(a), std::end(a));\n  EXPECT_THAT(test_vector, ElementsAreArray(expected.begin(), expected.end()));\n  // Pointers are iterators, too.\n  EXPECT_THAT(test_vector, ElementsAreArray(std::begin(a), std::end(a)));\n  // The empty range of NULL pointers should also be okay.\n  int* const null_int = nullptr;\n  EXPECT_THAT(test_vector, Not(ElementsAreArray(null_int, null_int)));\n  EXPECT_THAT((vector<int>()), ElementsAreArray(null_int, null_int));\n}\n\n// Since ElementsAre() and ElementsAreArray() share much of the\n// implementation, we only do a test for native arrays here.\nTEST(ElementsAreArrayTest, WorksWithNativeArray) {\n  ::std::string a[] = {\"hi\", \"ho\"};\n  ::std::string b[] = {\"hi\", \"ho\"};\n\n  EXPECT_THAT(a, ElementsAreArray(b));\n  EXPECT_THAT(a, ElementsAreArray(b, 2));\n  EXPECT_THAT(a, Not(ElementsAreArray(b, 1)));\n}\n\nTEST(ElementsAreArrayTest, SourceLifeSpan) {\n  const int a[] = {1, 2, 3};\n  vector<int> test_vector(std::begin(a), std::end(a));\n  vector<int> expect(std::begin(a), std::end(a));\n  ElementsAreArrayMatcher<int> matcher_maker =\n      ElementsAreArray(expect.begin(), expect.end());\n  EXPECT_THAT(test_vector, matcher_maker);\n  // Changing in place the values that initialized matcher_maker should not\n  // affect matcher_maker anymore. It should have made its own copy of them.\n  for (int& i : expect) {\n    i += 10;\n  }\n  EXPECT_THAT(test_vector, matcher_maker);\n  test_vector.push_back(3);\n  EXPECT_THAT(test_vector, Not(matcher_maker));\n}\n\n// Tests Contains().\n\nINSTANTIATE_GTEST_MATCHER_TEST_P(ContainsTest);\n\nTEST(ContainsTest, ListMatchesWhenElementIsInContainer) {\n  list<int> some_list;\n  some_list.push_back(3);\n  some_list.push_back(1);\n  some_list.push_back(2);\n  some_list.push_back(3);\n  EXPECT_THAT(some_list, Contains(1));\n  EXPECT_THAT(some_list, Contains(Gt(2.5)));\n  EXPECT_THAT(some_list, Contains(Eq(2.0f)));\n\n  list<std::string> another_list;\n  another_list.push_back(\"fee\");\n  another_list.push_back(\"fie\");\n  another_list.push_back(\"foe\");\n  another_list.push_back(\"fum\");\n  EXPECT_THAT(another_list, Contains(std::string(\"fee\")));\n}\n\nTEST(ContainsTest, ListDoesNotMatchWhenElementIsNotInContainer) {\n  list<int> some_list;\n  some_list.push_back(3);\n  some_list.push_back(1);\n  EXPECT_THAT(some_list, Not(Contains(4)));\n}\n\nTEST(ContainsTest, SetMatchesWhenElementIsInContainer) {\n  set<int> some_set;\n  some_set.insert(3);\n  some_set.insert(1);\n  some_set.insert(2);\n  EXPECT_THAT(some_set, Contains(Eq(1.0)));\n  EXPECT_THAT(some_set, Contains(Eq(3.0f)));\n  EXPECT_THAT(some_set, Contains(2));\n\n  set<std::string> another_set;\n  another_set.insert(\"fee\");\n  another_set.insert(\"fie\");\n  another_set.insert(\"foe\");\n  another_set.insert(\"fum\");\n  EXPECT_THAT(another_set, Contains(Eq(std::string(\"fum\"))));\n}\n\nTEST(ContainsTest, SetDoesNotMatchWhenElementIsNotInContainer) {\n  set<int> some_set;\n  some_set.insert(3);\n  some_set.insert(1);\n  EXPECT_THAT(some_set, Not(Contains(4)));\n\n  set<std::string> c_string_set;\n  c_string_set.insert(\"hello\");\n  EXPECT_THAT(c_string_set, Not(Contains(std::string(\"goodbye\"))));\n}\n\nTEST_P(ContainsTestP, ExplainsMatchResultCorrectly) {\n  const int a[2] = {1, 2};\n  Matcher<const int(&)[2]> m = Contains(2);\n  EXPECT_EQ(\"whose element #1 matches\", Explain(m, a));\n\n  m = Contains(3);\n  EXPECT_EQ(\"\", Explain(m, a));\n\n  m = Contains(GreaterThan(0));\n  EXPECT_EQ(\"whose element #0 matches, which is 1 more than 0\", Explain(m, a));\n\n  m = Contains(GreaterThan(10));\n  EXPECT_EQ(\"\", Explain(m, a));\n}\n\nTEST(ContainsTest, DescribesItselfCorrectly) {\n  Matcher<vector<int>> m = Contains(1);\n  EXPECT_EQ(\"contains at least one element that is equal to 1\", Describe(m));\n\n  Matcher<vector<int>> m2 = Not(m);\n  EXPECT_EQ(\"doesn't contain any element that is equal to 1\", Describe(m2));\n}\n\nTEST(ContainsTest, MapMatchesWhenElementIsInContainer) {\n  map<std::string, int> my_map;\n  const char* bar = \"a string\";\n  my_map[bar] = 2;\n  EXPECT_THAT(my_map, Contains(pair<const char* const, int>(bar, 2)));\n\n  map<std::string, int> another_map;\n  another_map[\"fee\"] = 1;\n  another_map[\"fie\"] = 2;\n  another_map[\"foe\"] = 3;\n  another_map[\"fum\"] = 4;\n  EXPECT_THAT(another_map,\n              Contains(pair<const std::string, int>(std::string(\"fee\"), 1)));\n  EXPECT_THAT(another_map, Contains(pair<const std::string, int>(\"fie\", 2)));\n}\n\nTEST(ContainsTest, MapDoesNotMatchWhenElementIsNotInContainer) {\n  map<int, int> some_map;\n  some_map[1] = 11;\n  some_map[2] = 22;\n  EXPECT_THAT(some_map, Not(Contains(pair<const int, int>(2, 23))));\n}\n\nTEST(ContainsTest, ArrayMatchesWhenElementIsInContainer) {\n  const char* string_array[] = {\"fee\", \"fie\", \"foe\", \"fum\"};\n  EXPECT_THAT(string_array, Contains(Eq(std::string(\"fum\"))));\n}\n\nTEST(ContainsTest, ArrayDoesNotMatchWhenElementIsNotInContainer) {\n  int int_array[] = {1, 2, 3, 4};\n  EXPECT_THAT(int_array, Not(Contains(5)));\n}\n\nTEST(ContainsTest, AcceptsMatcher) {\n  const int a[] = {1, 2, 3};\n  EXPECT_THAT(a, Contains(Gt(2)));\n  EXPECT_THAT(a, Not(Contains(Gt(4))));\n}\n\nTEST(ContainsTest, WorksForNativeArrayAsTuple) {\n  const int a[] = {1, 2};\n  const int* const pointer = a;\n  EXPECT_THAT(std::make_tuple(pointer, 2), Contains(1));\n  EXPECT_THAT(std::make_tuple(pointer, 2), Not(Contains(Gt(3))));\n}\n\nTEST(ContainsTest, WorksForTwoDimensionalNativeArray) {\n  int a[][3] = {{1, 2, 3}, {4, 5, 6}};\n  EXPECT_THAT(a, Contains(ElementsAre(4, 5, 6)));\n  EXPECT_THAT(a, Contains(Contains(5)));\n  EXPECT_THAT(a, Not(Contains(ElementsAre(3, 4, 5))));\n  EXPECT_THAT(a, Contains(Not(Contains(5))));\n}\n\n}  // namespace\n}  // namespace gmock_matchers_test\n}  // namespace testing\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock-matchers-misc_test.cc",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file tests some commonly used argument matchers.\n\n// Silence warning C4244: 'initializing': conversion from 'int' to 'short',\n// possible loss of data and C4100, unreferenced local parameter\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 4244)\n#pragma warning(disable : 4100)\n#endif\n\n#include \"test/gmock-matchers_test.h\"\n\nnamespace testing {\nnamespace gmock_matchers_test {\nnamespace {\n\nTEST(AddressTest, NonConst) {\n  int n = 1;\n  const Matcher<int> m = Address(Eq(&n));\n\n  EXPECT_TRUE(m.Matches(n));\n\n  int other = 5;\n\n  EXPECT_FALSE(m.Matches(other));\n\n  int& n_ref = n;\n\n  EXPECT_TRUE(m.Matches(n_ref));\n}\n\nTEST(AddressTest, Const) {\n  const int n = 1;\n  const Matcher<int> m = Address(Eq(&n));\n\n  EXPECT_TRUE(m.Matches(n));\n\n  int other = 5;\n\n  EXPECT_FALSE(m.Matches(other));\n}\n\nTEST(AddressTest, MatcherDoesntCopy) {\n  std::unique_ptr<int> n(new int(1));\n  const Matcher<std::unique_ptr<int>> m = Address(Eq(&n));\n\n  EXPECT_TRUE(m.Matches(n));\n}\n\nTEST(AddressTest, Describe) {\n  Matcher<int> matcher = Address(_);\n  EXPECT_EQ(\"has address that is anything\", Describe(matcher));\n  EXPECT_EQ(\"does not have address that is anything\",\n            DescribeNegation(matcher));\n}\n\n// The following two tests verify that values without a public copy\n// ctor can be used as arguments to matchers like Eq(), Ge(), and etc\n// with the help of ByRef().\n\nclass NotCopyable {\n public:\n  explicit NotCopyable(int a_value) : value_(a_value) {}\n\n  int value() const { return value_; }\n\n  bool operator==(const NotCopyable& rhs) const {\n    return value() == rhs.value();\n  }\n\n  bool operator>=(const NotCopyable& rhs) const {\n    return value() >= rhs.value();\n  }\n\n private:\n  int value_;\n\n  NotCopyable(const NotCopyable&) = delete;\n  NotCopyable& operator=(const NotCopyable&) = delete;\n};\n\nTEST(ByRefTest, AllowsNotCopyableConstValueInMatchers) {\n  const NotCopyable const_value1(1);\n  const Matcher<const NotCopyable&> m = Eq(ByRef(const_value1));\n\n  const NotCopyable n1(1), n2(2);\n  EXPECT_TRUE(m.Matches(n1));\n  EXPECT_FALSE(m.Matches(n2));\n}\n\nTEST(ByRefTest, AllowsNotCopyableValueInMatchers) {\n  NotCopyable value2(2);\n  const Matcher<NotCopyable&> m = Ge(ByRef(value2));\n\n  NotCopyable n1(1), n2(2);\n  EXPECT_FALSE(m.Matches(n1));\n  EXPECT_TRUE(m.Matches(n2));\n}\n\nTEST(IsEmptyTest, ImplementsIsEmpty) {\n  vector<int> container;\n  EXPECT_THAT(container, IsEmpty());\n  container.push_back(0);\n  EXPECT_THAT(container, Not(IsEmpty()));\n  container.push_back(1);\n  EXPECT_THAT(container, Not(IsEmpty()));\n}\n\nTEST(IsEmptyTest, WorksWithString) {\n  std::string text;\n  EXPECT_THAT(text, IsEmpty());\n  text = \"foo\";\n  EXPECT_THAT(text, Not(IsEmpty()));\n  text = std::string(\"\\0\", 1);\n  EXPECT_THAT(text, Not(IsEmpty()));\n}\n\nTEST(IsEmptyTest, CanDescribeSelf) {\n  Matcher<vector<int>> m = IsEmpty();\n  EXPECT_EQ(\"is empty\", Describe(m));\n  EXPECT_EQ(\"isn't empty\", DescribeNegation(m));\n}\n\nTEST(IsEmptyTest, ExplainsResult) {\n  Matcher<vector<int>> m = IsEmpty();\n  vector<int> container;\n  EXPECT_EQ(\"\", Explain(m, container));\n  container.push_back(0);\n  EXPECT_EQ(\"whose size is 1\", Explain(m, container));\n}\n\nTEST(IsEmptyTest, WorksWithMoveOnly) {\n  ContainerHelper helper;\n  EXPECT_CALL(helper, Call(IsEmpty()));\n  helper.Call({});\n}\n\nTEST(IsTrueTest, IsTrueIsFalse) {\n  EXPECT_THAT(true, IsTrue());\n  EXPECT_THAT(false, IsFalse());\n  EXPECT_THAT(true, Not(IsFalse()));\n  EXPECT_THAT(false, Not(IsTrue()));\n  EXPECT_THAT(0, Not(IsTrue()));\n  EXPECT_THAT(0, IsFalse());\n  EXPECT_THAT(nullptr, Not(IsTrue()));\n  EXPECT_THAT(nullptr, IsFalse());\n  EXPECT_THAT(-1, IsTrue());\n  EXPECT_THAT(-1, Not(IsFalse()));\n  EXPECT_THAT(1, IsTrue());\n  EXPECT_THAT(1, Not(IsFalse()));\n  EXPECT_THAT(2, IsTrue());\n  EXPECT_THAT(2, Not(IsFalse()));\n  int a = 42;\n  EXPECT_THAT(a, IsTrue());\n  EXPECT_THAT(a, Not(IsFalse()));\n  EXPECT_THAT(&a, IsTrue());\n  EXPECT_THAT(&a, Not(IsFalse()));\n  EXPECT_THAT(false, Not(IsTrue()));\n  EXPECT_THAT(true, Not(IsFalse()));\n  EXPECT_THAT(std::true_type(), IsTrue());\n  EXPECT_THAT(std::true_type(), Not(IsFalse()));\n  EXPECT_THAT(std::false_type(), IsFalse());\n  EXPECT_THAT(std::false_type(), Not(IsTrue()));\n  EXPECT_THAT(nullptr, Not(IsTrue()));\n  EXPECT_THAT(nullptr, IsFalse());\n  std::unique_ptr<int> null_unique;\n  std::unique_ptr<int> nonnull_unique(new int(0));\n  EXPECT_THAT(null_unique, Not(IsTrue()));\n  EXPECT_THAT(null_unique, IsFalse());\n  EXPECT_THAT(nonnull_unique, IsTrue());\n  EXPECT_THAT(nonnull_unique, Not(IsFalse()));\n}\n\n#if GTEST_HAS_TYPED_TEST\n// Tests ContainerEq with different container types, and\n// different element types.\n\ntemplate <typename T>\nclass ContainerEqTest : public testing::Test {};\n\ntypedef testing::Types<set<int>, vector<size_t>, multiset<size_t>, list<int>>\n    ContainerEqTestTypes;\n\nTYPED_TEST_SUITE(ContainerEqTest, ContainerEqTestTypes);\n\n// Tests that the filled container is equal to itself.\nTYPED_TEST(ContainerEqTest, EqualsSelf) {\n  static const int vals[] = {1, 1, 2, 3, 5, 8};\n  TypeParam my_set(vals, vals + 6);\n  const Matcher<TypeParam> m = ContainerEq(my_set);\n  EXPECT_TRUE(m.Matches(my_set));\n  EXPECT_EQ(\"\", Explain(m, my_set));\n}\n\n// Tests that missing values are reported.\nTYPED_TEST(ContainerEqTest, ValueMissing) {\n  static const int vals[] = {1, 1, 2, 3, 5, 8};\n  static const int test_vals[] = {2, 1, 8, 5};\n  TypeParam my_set(vals, vals + 6);\n  TypeParam test_set(test_vals, test_vals + 4);\n  const Matcher<TypeParam> m = ContainerEq(my_set);\n  EXPECT_FALSE(m.Matches(test_set));\n  EXPECT_EQ(\"which doesn't have these expected elements: 3\",\n            Explain(m, test_set));\n}\n\n// Tests that added values are reported.\nTYPED_TEST(ContainerEqTest, ValueAdded) {\n  static const int vals[] = {1, 1, 2, 3, 5, 8};\n  static const int test_vals[] = {1, 2, 3, 5, 8, 46};\n  TypeParam my_set(vals, vals + 6);\n  TypeParam test_set(test_vals, test_vals + 6);\n  const Matcher<const TypeParam&> m = ContainerEq(my_set);\n  EXPECT_FALSE(m.Matches(test_set));\n  EXPECT_EQ(\"which has these unexpected elements: 46\", Explain(m, test_set));\n}\n\n// Tests that added and missing values are reported together.\nTYPED_TEST(ContainerEqTest, ValueAddedAndRemoved) {\n  static const int vals[] = {1, 1, 2, 3, 5, 8};\n  static const int test_vals[] = {1, 2, 3, 8, 46};\n  TypeParam my_set(vals, vals + 6);\n  TypeParam test_set(test_vals, test_vals + 5);\n  const Matcher<TypeParam> m = ContainerEq(my_set);\n  EXPECT_FALSE(m.Matches(test_set));\n  EXPECT_EQ(\n      \"which has these unexpected elements: 46,\\n\"\n      \"and doesn't have these expected elements: 5\",\n      Explain(m, test_set));\n}\n\n// Tests duplicated value -- expect no explanation.\nTYPED_TEST(ContainerEqTest, DuplicateDifference) {\n  static const int vals[] = {1, 1, 2, 3, 5, 8};\n  static const int test_vals[] = {1, 2, 3, 5, 8};\n  TypeParam my_set(vals, vals + 6);\n  TypeParam test_set(test_vals, test_vals + 5);\n  const Matcher<const TypeParam&> m = ContainerEq(my_set);\n  // Depending on the container, match may be true or false\n  // But in any case there should be no explanation.\n  EXPECT_EQ(\"\", Explain(m, test_set));\n}\n#endif  // GTEST_HAS_TYPED_TEST\n\n// Tests that multiple missing values are reported.\n// Using just vector here, so order is predictable.\nTEST(ContainerEqExtraTest, MultipleValuesMissing) {\n  static const int vals[] = {1, 1, 2, 3, 5, 8};\n  static const int test_vals[] = {2, 1, 5};\n  vector<int> my_set(vals, vals + 6);\n  vector<int> test_set(test_vals, test_vals + 3);\n  const Matcher<vector<int>> m = ContainerEq(my_set);\n  EXPECT_FALSE(m.Matches(test_set));\n  EXPECT_EQ(\"which doesn't have these expected elements: 3, 8\",\n            Explain(m, test_set));\n}\n\n// Tests that added values are reported.\n// Using just vector here, so order is predictable.\nTEST(ContainerEqExtraTest, MultipleValuesAdded) {\n  static const int vals[] = {1, 1, 2, 3, 5, 8};\n  static const int test_vals[] = {1, 2, 92, 3, 5, 8, 46};\n  list<size_t> my_set(vals, vals + 6);\n  list<size_t> test_set(test_vals, test_vals + 7);\n  const Matcher<const list<size_t>&> m = ContainerEq(my_set);\n  EXPECT_FALSE(m.Matches(test_set));\n  EXPECT_EQ(\"which has these unexpected elements: 92, 46\",\n            Explain(m, test_set));\n}\n\n// Tests that added and missing values are reported together.\nTEST(ContainerEqExtraTest, MultipleValuesAddedAndRemoved) {\n  static const int vals[] = {1, 1, 2, 3, 5, 8};\n  static const int test_vals[] = {1, 2, 3, 92, 46};\n  list<size_t> my_set(vals, vals + 6);\n  list<size_t> test_set(test_vals, test_vals + 5);\n  const Matcher<const list<size_t>> m = ContainerEq(my_set);\n  EXPECT_FALSE(m.Matches(test_set));\n  EXPECT_EQ(\n      \"which has these unexpected elements: 92, 46,\\n\"\n      \"and doesn't have these expected elements: 5, 8\",\n      Explain(m, test_set));\n}\n\n// Tests to see that duplicate elements are detected,\n// but (as above) not reported in the explanation.\nTEST(ContainerEqExtraTest, MultiSetOfIntDuplicateDifference) {\n  static const int vals[] = {1, 1, 2, 3, 5, 8};\n  static const int test_vals[] = {1, 2, 3, 5, 8};\n  vector<int> my_set(vals, vals + 6);\n  vector<int> test_set(test_vals, test_vals + 5);\n  const Matcher<vector<int>> m = ContainerEq(my_set);\n  EXPECT_TRUE(m.Matches(my_set));\n  EXPECT_FALSE(m.Matches(test_set));\n  // There is nothing to report when both sets contain all the same values.\n  EXPECT_EQ(\"\", Explain(m, test_set));\n}\n\n// Tests that ContainerEq works for non-trivial associative containers,\n// like maps.\nTEST(ContainerEqExtraTest, WorksForMaps) {\n  map<int, std::string> my_map;\n  my_map[0] = \"a\";\n  my_map[1] = \"b\";\n\n  map<int, std::string> test_map;\n  test_map[0] = \"aa\";\n  test_map[1] = \"b\";\n\n  const Matcher<const map<int, std::string>&> m = ContainerEq(my_map);\n  EXPECT_TRUE(m.Matches(my_map));\n  EXPECT_FALSE(m.Matches(test_map));\n\n  EXPECT_EQ(\n      \"which has these unexpected elements: (0, \\\"aa\\\"),\\n\"\n      \"and doesn't have these expected elements: (0, \\\"a\\\")\",\n      Explain(m, test_map));\n}\n\nTEST(ContainerEqExtraTest, WorksForNativeArray) {\n  int a1[] = {1, 2, 3};\n  int a2[] = {1, 2, 3};\n  int b[] = {1, 2, 4};\n\n  EXPECT_THAT(a1, ContainerEq(a2));\n  EXPECT_THAT(a1, Not(ContainerEq(b)));\n}\n\nTEST(ContainerEqExtraTest, WorksForTwoDimensionalNativeArray) {\n  const char a1[][3] = {\"hi\", \"lo\"};\n  const char a2[][3] = {\"hi\", \"lo\"};\n  const char b[][3] = {\"lo\", \"hi\"};\n\n  // Tests using ContainerEq() in the first dimension.\n  EXPECT_THAT(a1, ContainerEq(a2));\n  EXPECT_THAT(a1, Not(ContainerEq(b)));\n\n  // Tests using ContainerEq() in the second dimension.\n  EXPECT_THAT(a1, ElementsAre(ContainerEq(a2[0]), ContainerEq(a2[1])));\n  EXPECT_THAT(a1, ElementsAre(Not(ContainerEq(b[0])), ContainerEq(a2[1])));\n}\n\nTEST(ContainerEqExtraTest, WorksForNativeArrayAsTuple) {\n  const int a1[] = {1, 2, 3};\n  const int a2[] = {1, 2, 3};\n  const int b[] = {1, 2, 3, 4};\n\n  const int* const p1 = a1;\n  EXPECT_THAT(std::make_tuple(p1, 3), ContainerEq(a2));\n  EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(b)));\n\n  const int c[] = {1, 3, 2};\n  EXPECT_THAT(std::make_tuple(p1, 3), Not(ContainerEq(c)));\n}\n\nTEST(ContainerEqExtraTest, CopiesNativeArrayParameter) {\n  std::string a1[][3] = {{\"hi\", \"hello\", \"ciao\"}, {\"bye\", \"see you\", \"ciao\"}};\n\n  std::string a2[][3] = {{\"hi\", \"hello\", \"ciao\"}, {\"bye\", \"see you\", \"ciao\"}};\n\n  const Matcher<const std::string(&)[2][3]> m = ContainerEq(a2);\n  EXPECT_THAT(a1, m);\n\n  a2[0][0] = \"ha\";\n  EXPECT_THAT(a1, m);\n}\n\nnamespace {\n\n// Used as a check on the more complex max flow method used in the\n// real testing::internal::FindMaxBipartiteMatching. This method is\n// compatible but runs in worst-case factorial time, so we only\n// use it in testing for small problem sizes.\ntemplate <typename Graph>\nclass BacktrackingMaxBPMState {\n public:\n  // Does not take ownership of 'g'.\n  explicit BacktrackingMaxBPMState(const Graph* g) : graph_(g) {}\n\n  ElementMatcherPairs Compute() {\n    if (graph_->LhsSize() == 0 || graph_->RhsSize() == 0) {\n      return best_so_far_;\n    }\n    lhs_used_.assign(graph_->LhsSize(), kUnused);\n    rhs_used_.assign(graph_->RhsSize(), kUnused);\n    for (size_t irhs = 0; irhs < graph_->RhsSize(); ++irhs) {\n      matches_.clear();\n      RecurseInto(irhs);\n      if (best_so_far_.size() == graph_->RhsSize()) break;\n    }\n    return best_so_far_;\n  }\n\n private:\n  static const size_t kUnused = static_cast<size_t>(-1);\n\n  void PushMatch(size_t lhs, size_t rhs) {\n    matches_.push_back(ElementMatcherPair(lhs, rhs));\n    lhs_used_[lhs] = rhs;\n    rhs_used_[rhs] = lhs;\n    if (matches_.size() > best_so_far_.size()) {\n      best_so_far_ = matches_;\n    }\n  }\n\n  void PopMatch() {\n    const ElementMatcherPair& back = matches_.back();\n    lhs_used_[back.first] = kUnused;\n    rhs_used_[back.second] = kUnused;\n    matches_.pop_back();\n  }\n\n  bool RecurseInto(size_t irhs) {\n    if (rhs_used_[irhs] != kUnused) {\n      return true;\n    }\n    for (size_t ilhs = 0; ilhs < graph_->LhsSize(); ++ilhs) {\n      if (lhs_used_[ilhs] != kUnused) {\n        continue;\n      }\n      if (!graph_->HasEdge(ilhs, irhs)) {\n        continue;\n      }\n      PushMatch(ilhs, irhs);\n      if (best_so_far_.size() == graph_->RhsSize()) {\n        return false;\n      }\n      for (size_t mi = irhs + 1; mi < graph_->RhsSize(); ++mi) {\n        if (!RecurseInto(mi)) return false;\n      }\n      PopMatch();\n    }\n    return true;\n  }\n\n  const Graph* graph_;  // not owned\n  std::vector<size_t> lhs_used_;\n  std::vector<size_t> rhs_used_;\n  ElementMatcherPairs matches_;\n  ElementMatcherPairs best_so_far_;\n};\n\ntemplate <typename Graph>\nconst size_t BacktrackingMaxBPMState<Graph>::kUnused;\n\n}  // namespace\n\n// Implement a simple backtracking algorithm to determine if it is possible\n// to find one element per matcher, without reusing elements.\ntemplate <typename Graph>\nElementMatcherPairs FindBacktrackingMaxBPM(const Graph& g) {\n  return BacktrackingMaxBPMState<Graph>(&g).Compute();\n}\n\nclass BacktrackingBPMTest : public ::testing::Test {};\n\n// Tests the MaxBipartiteMatching algorithm with square matrices.\n// The single int param is the # of nodes on each of the left and right sides.\nclass BipartiteTest : public ::testing::TestWithParam<size_t> {};\n\n// Verify all match graphs up to some moderate number of edges.\nTEST_P(BipartiteTest, Exhaustive) {\n  size_t nodes = GetParam();\n  MatchMatrix graph(nodes, nodes);\n  do {\n    ElementMatcherPairs matches = internal::FindMaxBipartiteMatching(graph);\n    EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(), matches.size())\n        << \"graph: \" << graph.DebugString();\n    // Check that all elements of matches are in the graph.\n    // Check that elements of first and second are unique.\n    std::vector<bool> seen_element(graph.LhsSize());\n    std::vector<bool> seen_matcher(graph.RhsSize());\n    SCOPED_TRACE(PrintToString(matches));\n    for (size_t i = 0; i < matches.size(); ++i) {\n      size_t ilhs = matches[i].first;\n      size_t irhs = matches[i].second;\n      EXPECT_TRUE(graph.HasEdge(ilhs, irhs));\n      EXPECT_FALSE(seen_element[ilhs]);\n      EXPECT_FALSE(seen_matcher[irhs]);\n      seen_element[ilhs] = true;\n      seen_matcher[irhs] = true;\n    }\n  } while (graph.NextGraph());\n}\n\nINSTANTIATE_TEST_SUITE_P(AllGraphs, BipartiteTest,\n                         ::testing::Range(size_t{0}, size_t{5}));\n\n// Parameterized by a pair interpreted as (LhsSize, RhsSize).\nclass BipartiteNonSquareTest\n    : public ::testing::TestWithParam<std::pair<size_t, size_t>> {};\n\nTEST_F(BipartiteNonSquareTest, SimpleBacktracking) {\n  //   .......\n  // 0:-----\\ :\n  // 1:---\\ | :\n  // 2:---\\ | :\n  // 3:-\\ | | :\n  //  :.......:\n  //    0 1 2\n  MatchMatrix g(4, 3);\n  constexpr std::array<std::array<size_t, 2>, 4> kEdges = {\n      {{{0, 2}}, {{1, 1}}, {{2, 1}}, {{3, 0}}}};\n  for (size_t i = 0; i < kEdges.size(); ++i) {\n    g.SetEdge(kEdges[i][0], kEdges[i][1], true);\n  }\n  EXPECT_THAT(FindBacktrackingMaxBPM(g),\n              ElementsAre(Pair(3, 0), Pair(AnyOf(1, 2), 1), Pair(0, 2)))\n      << g.DebugString();\n}\n\n// Verify a few nonsquare matrices.\nTEST_P(BipartiteNonSquareTest, Exhaustive) {\n  size_t nlhs = GetParam().first;\n  size_t nrhs = GetParam().second;\n  MatchMatrix graph(nlhs, nrhs);\n  do {\n    EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),\n              internal::FindMaxBipartiteMatching(graph).size())\n        << \"graph: \" << graph.DebugString()\n        << \"\\nbacktracking: \" << PrintToString(FindBacktrackingMaxBPM(graph))\n        << \"\\nmax flow: \"\n        << PrintToString(internal::FindMaxBipartiteMatching(graph));\n  } while (graph.NextGraph());\n}\n\nINSTANTIATE_TEST_SUITE_P(\n    AllGraphs, BipartiteNonSquareTest,\n    testing::Values(std::make_pair(1, 2), std::make_pair(2, 1),\n                    std::make_pair(3, 2), std::make_pair(2, 3),\n                    std::make_pair(4, 1), std::make_pair(1, 4),\n                    std::make_pair(4, 3), std::make_pair(3, 4)));\n\nclass BipartiteRandomTest\n    : public ::testing::TestWithParam<std::pair<int, int>> {};\n\n// Verifies a large sample of larger graphs.\nTEST_P(BipartiteRandomTest, LargerNets) {\n  int nodes = GetParam().first;\n  int iters = GetParam().second;\n  MatchMatrix graph(static_cast<size_t>(nodes), static_cast<size_t>(nodes));\n\n  auto seed = static_cast<uint32_t>(GTEST_FLAG_GET(random_seed));\n  if (seed == 0) {\n    seed = static_cast<uint32_t>(time(nullptr));\n  }\n\n  for (; iters > 0; --iters, ++seed) {\n    srand(static_cast<unsigned int>(seed));\n    graph.Randomize();\n    EXPECT_EQ(FindBacktrackingMaxBPM(graph).size(),\n              internal::FindMaxBipartiteMatching(graph).size())\n        << \" graph: \" << graph.DebugString()\n        << \"\\nTo reproduce the failure, rerun the test with the flag\"\n           \" --\"\n        << GTEST_FLAG_PREFIX_ << \"random_seed=\" << seed;\n  }\n}\n\n// Test argument is a std::pair<int, int> representing (nodes, iters).\nINSTANTIATE_TEST_SUITE_P(Samples, BipartiteRandomTest,\n                         testing::Values(std::make_pair(5, 10000),\n                                         std::make_pair(6, 5000),\n                                         std::make_pair(7, 2000),\n                                         std::make_pair(8, 500),\n                                         std::make_pair(9, 100)));\n\n// Tests IsReadableTypeName().\n\nTEST(IsReadableTypeNameTest, ReturnsTrueForShortNames) {\n  EXPECT_TRUE(IsReadableTypeName(\"int\"));\n  EXPECT_TRUE(IsReadableTypeName(\"const unsigned char*\"));\n  EXPECT_TRUE(IsReadableTypeName(\"MyMap<int, void*>\"));\n  EXPECT_TRUE(IsReadableTypeName(\"void (*)(int, bool)\"));\n}\n\nTEST(IsReadableTypeNameTest, ReturnsTrueForLongNonTemplateNonFunctionNames) {\n  EXPECT_TRUE(IsReadableTypeName(\"my_long_namespace::MyClassName\"));\n  EXPECT_TRUE(IsReadableTypeName(\"int [5][6][7][8][9][10][11]\"));\n  EXPECT_TRUE(IsReadableTypeName(\"my_namespace::MyOuterClass::MyInnerClass\"));\n}\n\nTEST(IsReadableTypeNameTest, ReturnsFalseForLongTemplateNames) {\n  EXPECT_FALSE(\n      IsReadableTypeName(\"basic_string<char, std::char_traits<char> >\"));\n  EXPECT_FALSE(IsReadableTypeName(\"std::vector<int, std::alloc_traits<int> >\"));\n}\n\nTEST(IsReadableTypeNameTest, ReturnsFalseForLongFunctionTypeNames) {\n  EXPECT_FALSE(IsReadableTypeName(\"void (&)(int, bool, char, float)\"));\n}\n\n// Tests FormatMatcherDescription().\n\nTEST(FormatMatcherDescriptionTest, WorksForEmptyDescription) {\n  EXPECT_EQ(\"is even\",\n            FormatMatcherDescription(false, \"IsEven\", {}, Strings()));\n  EXPECT_EQ(\"not (is even)\",\n            FormatMatcherDescription(true, \"IsEven\", {}, Strings()));\n\n  EXPECT_EQ(\"equals (a: 5)\",\n            FormatMatcherDescription(false, \"Equals\", {\"a\"}, {\"5\"}));\n\n  EXPECT_EQ(\n      \"is in range (a: 5, b: 8)\",\n      FormatMatcherDescription(false, \"IsInRange\", {\"a\", \"b\"}, {\"5\", \"8\"}));\n}\n\nINSTANTIATE_GTEST_MATCHER_TEST_P(MatcherTupleTest);\n\nTEST_P(MatcherTupleTestP, ExplainsMatchFailure) {\n  stringstream ss1;\n  ExplainMatchFailureTupleTo(\n      std::make_tuple(Matcher<char>(Eq('a')), GreaterThan(5)),\n      std::make_tuple('a', 10), &ss1);\n  EXPECT_EQ(\"\", ss1.str());  // Successful match.\n\n  stringstream ss2;\n  ExplainMatchFailureTupleTo(\n      std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),\n      std::make_tuple(2, 'b'), &ss2);\n  EXPECT_EQ(\n      \"  Expected arg #0: is > 5\\n\"\n      \"           Actual: 2, which is 3 less than 5\\n\"\n      \"  Expected arg #1: is equal to 'a' (97, 0x61)\\n\"\n      \"           Actual: 'b' (98, 0x62)\\n\",\n      ss2.str());  // Failed match where both arguments need explanation.\n\n  stringstream ss3;\n  ExplainMatchFailureTupleTo(\n      std::make_tuple(GreaterThan(5), Matcher<char>(Eq('a'))),\n      std::make_tuple(2, 'a'), &ss3);\n  EXPECT_EQ(\n      \"  Expected arg #0: is > 5\\n\"\n      \"           Actual: 2, which is 3 less than 5\\n\",\n      ss3.str());  // Failed match where only one argument needs\n                   // explanation.\n}\n\n// Sample optional type implementation with minimal requirements for use with\n// Optional matcher.\ntemplate <typename T>\nclass SampleOptional {\n public:\n  using value_type = T;\n  explicit SampleOptional(T value)\n      : value_(std::move(value)), has_value_(true) {}\n  SampleOptional() : value_(), has_value_(false) {}\n  operator bool() const { return has_value_; }\n  const T& operator*() const { return value_; }\n\n private:\n  T value_;\n  bool has_value_;\n};\n\nTEST(OptionalTest, DescribesSelf) {\n  const Matcher<SampleOptional<int>> m = Optional(Eq(1));\n  EXPECT_EQ(\"value is equal to 1\", Describe(m));\n}\n\nTEST(OptionalTest, ExplainsSelf) {\n  const Matcher<SampleOptional<int>> m = Optional(Eq(1));\n  EXPECT_EQ(\"whose value 1 matches\", Explain(m, SampleOptional<int>(1)));\n  EXPECT_EQ(\"whose value 2 doesn't match\", Explain(m, SampleOptional<int>(2)));\n}\n\nTEST(OptionalTest, MatchesNonEmptyOptional) {\n  const Matcher<SampleOptional<int>> m1 = Optional(1);\n  const Matcher<SampleOptional<int>> m2 = Optional(Eq(2));\n  const Matcher<SampleOptional<int>> m3 = Optional(Lt(3));\n  SampleOptional<int> opt(1);\n  EXPECT_TRUE(m1.Matches(opt));\n  EXPECT_FALSE(m2.Matches(opt));\n  EXPECT_TRUE(m3.Matches(opt));\n}\n\nTEST(OptionalTest, DoesNotMatchNullopt) {\n  const Matcher<SampleOptional<int>> m = Optional(1);\n  SampleOptional<int> empty;\n  EXPECT_FALSE(m.Matches(empty));\n}\n\nTEST(OptionalTest, WorksWithMoveOnly) {\n  Matcher<SampleOptional<std::unique_ptr<int>>> m = Optional(Eq(nullptr));\n  EXPECT_TRUE(m.Matches(SampleOptional<std::unique_ptr<int>>(nullptr)));\n}\n\nclass SampleVariantIntString {\n public:\n  SampleVariantIntString(int i) : i_(i), has_int_(true) {}\n  SampleVariantIntString(const std::string& s) : s_(s), has_int_(false) {}\n\n  template <typename T>\n  friend bool holds_alternative(const SampleVariantIntString& value) {\n    return value.has_int_ == std::is_same<T, int>::value;\n  }\n\n  template <typename T>\n  friend const T& get(const SampleVariantIntString& value) {\n    return value.get_impl(static_cast<T*>(nullptr));\n  }\n\n private:\n  const int& get_impl(int*) const { return i_; }\n  const std::string& get_impl(std::string*) const { return s_; }\n\n  int i_;\n  std::string s_;\n  bool has_int_;\n};\n\nTEST(VariantTest, DescribesSelf) {\n  const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));\n  EXPECT_THAT(Describe(m), ContainsRegex(\"is a variant<> with value of type \"\n                                         \"'.*' and the value is equal to 1\"));\n}\n\nTEST(VariantTest, ExplainsSelf) {\n  const Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));\n  EXPECT_THAT(Explain(m, SampleVariantIntString(1)),\n              ContainsRegex(\"whose value 1\"));\n  EXPECT_THAT(Explain(m, SampleVariantIntString(\"A\")),\n              HasSubstr(\"whose value is not of type '\"));\n  EXPECT_THAT(Explain(m, SampleVariantIntString(2)),\n              \"whose value 2 doesn't match\");\n}\n\nTEST(VariantTest, FullMatch) {\n  Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));\n  EXPECT_TRUE(m.Matches(SampleVariantIntString(1)));\n\n  m = VariantWith<std::string>(Eq(\"1\"));\n  EXPECT_TRUE(m.Matches(SampleVariantIntString(\"1\")));\n}\n\nTEST(VariantTest, TypeDoesNotMatch) {\n  Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));\n  EXPECT_FALSE(m.Matches(SampleVariantIntString(\"1\")));\n\n  m = VariantWith<std::string>(Eq(\"1\"));\n  EXPECT_FALSE(m.Matches(SampleVariantIntString(1)));\n}\n\nTEST(VariantTest, InnerDoesNotMatch) {\n  Matcher<SampleVariantIntString> m = VariantWith<int>(Eq(1));\n  EXPECT_FALSE(m.Matches(SampleVariantIntString(2)));\n\n  m = VariantWith<std::string>(Eq(\"1\"));\n  EXPECT_FALSE(m.Matches(SampleVariantIntString(\"2\")));\n}\n\nclass SampleAnyType {\n public:\n  explicit SampleAnyType(int i) : index_(0), i_(i) {}\n  explicit SampleAnyType(const std::string& s) : index_(1), s_(s) {}\n\n  template <typename T>\n  friend const T* any_cast(const SampleAnyType* any) {\n    return any->get_impl(static_cast<T*>(nullptr));\n  }\n\n private:\n  int index_;\n  int i_;\n  std::string s_;\n\n  const int* get_impl(int*) const { return index_ == 0 ? &i_ : nullptr; }\n  const std::string* get_impl(std::string*) const {\n    return index_ == 1 ? &s_ : nullptr;\n  }\n};\n\nTEST(AnyWithTest, FullMatch) {\n  Matcher<SampleAnyType> m = AnyWith<int>(Eq(1));\n  EXPECT_TRUE(m.Matches(SampleAnyType(1)));\n}\n\nTEST(AnyWithTest, TestBadCastType) {\n  Matcher<SampleAnyType> m = AnyWith<std::string>(Eq(\"fail\"));\n  EXPECT_FALSE(m.Matches(SampleAnyType(1)));\n}\n\nTEST(AnyWithTest, TestUseInContainers) {\n  std::vector<SampleAnyType> a;\n  a.emplace_back(1);\n  a.emplace_back(2);\n  a.emplace_back(3);\n  EXPECT_THAT(\n      a, ElementsAreArray({AnyWith<int>(1), AnyWith<int>(2), AnyWith<int>(3)}));\n\n  std::vector<SampleAnyType> b;\n  b.emplace_back(\"hello\");\n  b.emplace_back(\"merhaba\");\n  b.emplace_back(\"salut\");\n  EXPECT_THAT(b, ElementsAreArray({AnyWith<std::string>(\"hello\"),\n                                   AnyWith<std::string>(\"merhaba\"),\n                                   AnyWith<std::string>(\"salut\")}));\n}\nTEST(AnyWithTest, TestCompare) {\n  EXPECT_THAT(SampleAnyType(1), AnyWith<int>(Gt(0)));\n}\n\nTEST(AnyWithTest, DescribesSelf) {\n  const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));\n  EXPECT_THAT(Describe(m), ContainsRegex(\"is an 'any' type with value of type \"\n                                         \"'.*' and the value is equal to 1\"));\n}\n\nTEST(AnyWithTest, ExplainsSelf) {\n  const Matcher<const SampleAnyType&> m = AnyWith<int>(Eq(1));\n\n  EXPECT_THAT(Explain(m, SampleAnyType(1)), ContainsRegex(\"whose value 1\"));\n  EXPECT_THAT(Explain(m, SampleAnyType(\"A\")),\n              HasSubstr(\"whose value is not of type '\"));\n  EXPECT_THAT(Explain(m, SampleAnyType(2)), \"whose value 2 doesn't match\");\n}\n\n// Tests Args<k0, ..., kn>(m).\n\nTEST(ArgsTest, AcceptsZeroTemplateArg) {\n  const std::tuple<int, bool> t(5, true);\n  EXPECT_THAT(t, Args<>(Eq(std::tuple<>())));\n  EXPECT_THAT(t, Not(Args<>(Ne(std::tuple<>()))));\n}\n\nTEST(ArgsTest, AcceptsOneTemplateArg) {\n  const std::tuple<int, bool> t(5, true);\n  EXPECT_THAT(t, Args<0>(Eq(std::make_tuple(5))));\n  EXPECT_THAT(t, Args<1>(Eq(std::make_tuple(true))));\n  EXPECT_THAT(t, Not(Args<1>(Eq(std::make_tuple(false)))));\n}\n\nTEST(ArgsTest, AcceptsTwoTemplateArgs) {\n  const std::tuple<short, int, long> t(4, 5, 6L);  // NOLINT\n\n  EXPECT_THAT(t, (Args<0, 1>(Lt())));\n  EXPECT_THAT(t, (Args<1, 2>(Lt())));\n  EXPECT_THAT(t, Not(Args<0, 2>(Gt())));\n}\n\nTEST(ArgsTest, AcceptsRepeatedTemplateArgs) {\n  const std::tuple<short, int, long> t(4, 5, 6L);  // NOLINT\n  EXPECT_THAT(t, (Args<0, 0>(Eq())));\n  EXPECT_THAT(t, Not(Args<1, 1>(Ne())));\n}\n\nTEST(ArgsTest, AcceptsDecreasingTemplateArgs) {\n  const std::tuple<short, int, long> t(4, 5, 6L);  // NOLINT\n  EXPECT_THAT(t, (Args<2, 0>(Gt())));\n  EXPECT_THAT(t, Not(Args<2, 1>(Lt())));\n}\n\nMATCHER(SumIsZero, \"\") {\n  return std::get<0>(arg) + std::get<1>(arg) + std::get<2>(arg) == 0;\n}\n\nTEST(ArgsTest, AcceptsMoreTemplateArgsThanArityOfOriginalTuple) {\n  EXPECT_THAT(std::make_tuple(-1, 2), (Args<0, 0, 1>(SumIsZero())));\n  EXPECT_THAT(std::make_tuple(1, 2), Not(Args<0, 0, 1>(SumIsZero())));\n}\n\nTEST(ArgsTest, CanBeNested) {\n  const std::tuple<short, int, long, int> t(4, 5, 6L, 6);  // NOLINT\n  EXPECT_THAT(t, (Args<1, 2, 3>(Args<1, 2>(Eq()))));\n  EXPECT_THAT(t, (Args<0, 1, 3>(Args<0, 2>(Lt()))));\n}\n\nTEST(ArgsTest, CanMatchTupleByValue) {\n  typedef std::tuple<char, int, int> Tuple3;\n  const Matcher<Tuple3> m = Args<1, 2>(Lt());\n  EXPECT_TRUE(m.Matches(Tuple3('a', 1, 2)));\n  EXPECT_FALSE(m.Matches(Tuple3('b', 2, 2)));\n}\n\nTEST(ArgsTest, CanMatchTupleByReference) {\n  typedef std::tuple<char, char, int> Tuple3;\n  const Matcher<const Tuple3&> m = Args<0, 1>(Lt());\n  EXPECT_TRUE(m.Matches(Tuple3('a', 'b', 2)));\n  EXPECT_FALSE(m.Matches(Tuple3('b', 'b', 2)));\n}\n\n// Validates that arg is printed as str.\nMATCHER_P(PrintsAs, str, \"\") { return testing::PrintToString(arg) == str; }\n\nTEST(ArgsTest, AcceptsTenTemplateArgs) {\n  EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),\n              (Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(\n                  PrintsAs(\"(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)\"))));\n  EXPECT_THAT(std::make_tuple(0, 1L, 2, 3L, 4, 5, 6, 7, 8, 9),\n              Not(Args<9, 8, 7, 6, 5, 4, 3, 2, 1, 0>(\n                  PrintsAs(\"(0, 8, 7, 6, 5, 4, 3, 2, 1, 0)\"))));\n}\n\nTEST(ArgsTest, DescirbesSelfCorrectly) {\n  const Matcher<std::tuple<int, bool, char>> m = Args<2, 0>(Lt());\n  EXPECT_EQ(\n      \"are a tuple whose fields (#2, #0) are a pair where \"\n      \"the first < the second\",\n      Describe(m));\n}\n\nTEST(ArgsTest, DescirbesNestedArgsCorrectly) {\n  const Matcher<const std::tuple<int, bool, char, int>&> m =\n      Args<0, 2, 3>(Args<2, 0>(Lt()));\n  EXPECT_EQ(\n      \"are a tuple whose fields (#0, #2, #3) are a tuple \"\n      \"whose fields (#2, #0) are a pair where the first < the second\",\n      Describe(m));\n}\n\nTEST(ArgsTest, DescribesNegationCorrectly) {\n  const Matcher<std::tuple<int, char>> m = Args<1, 0>(Gt());\n  EXPECT_EQ(\n      \"are a tuple whose fields (#1, #0) aren't a pair \"\n      \"where the first > the second\",\n      DescribeNegation(m));\n}\n\nTEST(ArgsTest, ExplainsMatchResultWithoutInnerExplanation) {\n  const Matcher<std::tuple<bool, int, int>> m = Args<1, 2>(Eq());\n  EXPECT_EQ(\"whose fields (#1, #2) are (42, 42)\",\n            Explain(m, std::make_tuple(false, 42, 42)));\n  EXPECT_EQ(\"whose fields (#1, #2) are (42, 43)\",\n            Explain(m, std::make_tuple(false, 42, 43)));\n}\n\n// For testing Args<>'s explanation.\nclass LessThanMatcher : public MatcherInterface<std::tuple<char, int>> {\n public:\n  void DescribeTo(::std::ostream* /*os*/) const override {}\n\n  bool MatchAndExplain(std::tuple<char, int> value,\n                       MatchResultListener* listener) const override {\n    const int diff = std::get<0>(value) - std::get<1>(value);\n    if (diff > 0) {\n      *listener << \"where the first value is \" << diff\n                << \" more than the second\";\n    }\n    return diff < 0;\n  }\n};\n\nMatcher<std::tuple<char, int>> LessThan() {\n  return MakeMatcher(new LessThanMatcher);\n}\n\nTEST(ArgsTest, ExplainsMatchResultWithInnerExplanation) {\n  const Matcher<std::tuple<char, int, int>> m = Args<0, 2>(LessThan());\n  EXPECT_EQ(\n      \"whose fields (#0, #2) are ('a' (97, 0x61), 42), \"\n      \"where the first value is 55 more than the second\",\n      Explain(m, std::make_tuple('a', 42, 42)));\n  EXPECT_EQ(\"whose fields (#0, #2) are ('\\\\0', 43)\",\n            Explain(m, std::make_tuple('\\0', 42, 43)));\n}\n\n// Tests for the MATCHER*() macro family.\n\n// Tests that a simple MATCHER() definition works.\n\nMATCHER(IsEven, \"\") { return (arg % 2) == 0; }\n\nTEST(MatcherMacroTest, Works) {\n  const Matcher<int> m = IsEven();\n  EXPECT_TRUE(m.Matches(6));\n  EXPECT_FALSE(m.Matches(7));\n\n  EXPECT_EQ(\"is even\", Describe(m));\n  EXPECT_EQ(\"not (is even)\", DescribeNegation(m));\n  EXPECT_EQ(\"\", Explain(m, 6));\n  EXPECT_EQ(\"\", Explain(m, 7));\n}\n\n// This also tests that the description string can reference 'negation'.\nMATCHER(IsEven2, negation ? \"is odd\" : \"is even\") {\n  if ((arg % 2) == 0) {\n    // Verifies that we can stream to result_listener, a listener\n    // supplied by the MATCHER macro implicitly.\n    *result_listener << \"OK\";\n    return true;\n  } else {\n    *result_listener << \"% 2 == \" << (arg % 2);\n    return false;\n  }\n}\n\n// This also tests that the description string can reference matcher\n// parameters.\nMATCHER_P2(EqSumOf, x, y,\n           std::string(negation ? \"doesn't equal\" : \"equals\") + \" the sum of \" +\n               PrintToString(x) + \" and \" + PrintToString(y)) {\n  if (arg == (x + y)) {\n    *result_listener << \"OK\";\n    return true;\n  } else {\n    // Verifies that we can stream to the underlying stream of\n    // result_listener.\n    if (result_listener->stream() != nullptr) {\n      *result_listener->stream() << \"diff == \" << (x + y - arg);\n    }\n    return false;\n  }\n}\n\n// Tests that the matcher description can reference 'negation' and the\n// matcher parameters.\nTEST(MatcherMacroTest, DescriptionCanReferenceNegationAndParameters) {\n  const Matcher<int> m1 = IsEven2();\n  EXPECT_EQ(\"is even\", Describe(m1));\n  EXPECT_EQ(\"is odd\", DescribeNegation(m1));\n\n  const Matcher<int> m2 = EqSumOf(5, 9);\n  EXPECT_EQ(\"equals the sum of 5 and 9\", Describe(m2));\n  EXPECT_EQ(\"doesn't equal the sum of 5 and 9\", DescribeNegation(m2));\n}\n\n// Tests explaining match result in a MATCHER* macro.\nTEST(MatcherMacroTest, CanExplainMatchResult) {\n  const Matcher<int> m1 = IsEven2();\n  EXPECT_EQ(\"OK\", Explain(m1, 4));\n  EXPECT_EQ(\"% 2 == 1\", Explain(m1, 5));\n\n  const Matcher<int> m2 = EqSumOf(1, 2);\n  EXPECT_EQ(\"OK\", Explain(m2, 3));\n  EXPECT_EQ(\"diff == -1\", Explain(m2, 4));\n}\n\n// Tests that the body of MATCHER() can reference the type of the\n// value being matched.\n\nMATCHER(IsEmptyString, \"\") {\n  StaticAssertTypeEq<::std::string, arg_type>();\n  return arg.empty();\n}\n\nMATCHER(IsEmptyStringByRef, \"\") {\n  StaticAssertTypeEq<const ::std::string&, arg_type>();\n  return arg.empty();\n}\n\nTEST(MatcherMacroTest, CanReferenceArgType) {\n  const Matcher<::std::string> m1 = IsEmptyString();\n  EXPECT_TRUE(m1.Matches(\"\"));\n\n  const Matcher<const ::std::string&> m2 = IsEmptyStringByRef();\n  EXPECT_TRUE(m2.Matches(\"\"));\n}\n\n// Tests that MATCHER() can be used in a namespace.\n\nnamespace matcher_test {\nMATCHER(IsOdd, \"\") { return (arg % 2) != 0; }\n}  // namespace matcher_test\n\nTEST(MatcherMacroTest, WorksInNamespace) {\n  Matcher<int> m = matcher_test::IsOdd();\n  EXPECT_FALSE(m.Matches(4));\n  EXPECT_TRUE(m.Matches(5));\n}\n\n// Tests that Value() can be used to compose matchers.\nMATCHER(IsPositiveOdd, \"\") {\n  return Value(arg, matcher_test::IsOdd()) && arg > 0;\n}\n\nTEST(MatcherMacroTest, CanBeComposedUsingValue) {\n  EXPECT_THAT(3, IsPositiveOdd());\n  EXPECT_THAT(4, Not(IsPositiveOdd()));\n  EXPECT_THAT(-1, Not(IsPositiveOdd()));\n}\n\n// Tests that a simple MATCHER_P() definition works.\n\nMATCHER_P(IsGreaterThan32And, n, \"\") { return arg > 32 && arg > n; }\n\nTEST(MatcherPMacroTest, Works) {\n  const Matcher<int> m = IsGreaterThan32And(5);\n  EXPECT_TRUE(m.Matches(36));\n  EXPECT_FALSE(m.Matches(5));\n\n  EXPECT_EQ(\"is greater than 32 and (n: 5)\", Describe(m));\n  EXPECT_EQ(\"not (is greater than 32 and (n: 5))\", DescribeNegation(m));\n  EXPECT_EQ(\"\", Explain(m, 36));\n  EXPECT_EQ(\"\", Explain(m, 5));\n}\n\n// Tests that the description is calculated correctly from the matcher name.\nMATCHER_P(_is_Greater_Than32and_, n, \"\") { return arg > 32 && arg > n; }\n\nTEST(MatcherPMacroTest, GeneratesCorrectDescription) {\n  const Matcher<int> m = _is_Greater_Than32and_(5);\n\n  EXPECT_EQ(\"is greater than 32 and (n: 5)\", Describe(m));\n  EXPECT_EQ(\"not (is greater than 32 and (n: 5))\", DescribeNegation(m));\n  EXPECT_EQ(\"\", Explain(m, 36));\n  EXPECT_EQ(\"\", Explain(m, 5));\n}\n\n// Tests that a MATCHER_P matcher can be explicitly instantiated with\n// a reference parameter type.\n\nclass UncopyableFoo {\n public:\n  explicit UncopyableFoo(char value) : value_(value) { (void)value_; }\n\n  UncopyableFoo(const UncopyableFoo&) = delete;\n  void operator=(const UncopyableFoo&) = delete;\n\n private:\n  char value_;\n};\n\nMATCHER_P(ReferencesUncopyable, variable, \"\") { return &arg == &variable; }\n\nTEST(MatcherPMacroTest, WorksWhenExplicitlyInstantiatedWithReference) {\n  UncopyableFoo foo1('1'), foo2('2');\n  const Matcher<const UncopyableFoo&> m =\n      ReferencesUncopyable<const UncopyableFoo&>(foo1);\n\n  EXPECT_TRUE(m.Matches(foo1));\n  EXPECT_FALSE(m.Matches(foo2));\n\n  // We don't want the address of the parameter printed, as most\n  // likely it will just annoy the user.  If the address is\n  // interesting, the user should consider passing the parameter by\n  // pointer instead.\n  EXPECT_EQ(\"references uncopyable (variable: 1-byte object <31>)\",\n            Describe(m));\n}\n\n// Tests that the body of MATCHER_Pn() can reference the parameter\n// types.\n\nMATCHER_P3(ParamTypesAreIntLongAndChar, foo, bar, baz, \"\") {\n  StaticAssertTypeEq<int, foo_type>();\n  StaticAssertTypeEq<long, bar_type>();  // NOLINT\n  StaticAssertTypeEq<char, baz_type>();\n  return arg == 0;\n}\n\nTEST(MatcherPnMacroTest, CanReferenceParamTypes) {\n  EXPECT_THAT(0, ParamTypesAreIntLongAndChar(10, 20L, 'a'));\n}\n\n// Tests that a MATCHER_Pn matcher can be explicitly instantiated with\n// reference parameter types.\n\nMATCHER_P2(ReferencesAnyOf, variable1, variable2, \"\") {\n  return &arg == &variable1 || &arg == &variable2;\n}\n\nTEST(MatcherPnMacroTest, WorksWhenExplicitlyInstantiatedWithReferences) {\n  UncopyableFoo foo1('1'), foo2('2'), foo3('3');\n  const Matcher<const UncopyableFoo&> const_m =\n      ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);\n\n  EXPECT_TRUE(const_m.Matches(foo1));\n  EXPECT_TRUE(const_m.Matches(foo2));\n  EXPECT_FALSE(const_m.Matches(foo3));\n\n  const Matcher<UncopyableFoo&> m =\n      ReferencesAnyOf<UncopyableFoo&, UncopyableFoo&>(foo1, foo2);\n\n  EXPECT_TRUE(m.Matches(foo1));\n  EXPECT_TRUE(m.Matches(foo2));\n  EXPECT_FALSE(m.Matches(foo3));\n}\n\nTEST(MatcherPnMacroTest,\n     GeneratesCorretDescriptionWhenExplicitlyInstantiatedWithReferences) {\n  UncopyableFoo foo1('1'), foo2('2');\n  const Matcher<const UncopyableFoo&> m =\n      ReferencesAnyOf<const UncopyableFoo&, const UncopyableFoo&>(foo1, foo2);\n\n  // We don't want the addresses of the parameters printed, as most\n  // likely they will just annoy the user.  If the addresses are\n  // interesting, the user should consider passing the parameters by\n  // pointers instead.\n  EXPECT_EQ(\n      \"references any of (variable1: 1-byte object <31>, variable2: 1-byte \"\n      \"object <32>)\",\n      Describe(m));\n}\n\n// Tests that a simple MATCHER_P2() definition works.\n\nMATCHER_P2(IsNotInClosedRange, low, hi, \"\") { return arg < low || arg > hi; }\n\nTEST(MatcherPnMacroTest, Works) {\n  const Matcher<const long&> m = IsNotInClosedRange(10, 20);  // NOLINT\n  EXPECT_TRUE(m.Matches(36L));\n  EXPECT_FALSE(m.Matches(15L));\n\n  EXPECT_EQ(\"is not in closed range (low: 10, hi: 20)\", Describe(m));\n  EXPECT_EQ(\"not (is not in closed range (low: 10, hi: 20))\",\n            DescribeNegation(m));\n  EXPECT_EQ(\"\", Explain(m, 36L));\n  EXPECT_EQ(\"\", Explain(m, 15L));\n}\n\n// Tests that MATCHER*() definitions can be overloaded on the number\n// of parameters; also tests MATCHER_Pn() where n >= 3.\n\nMATCHER(EqualsSumOf, \"\") { return arg == 0; }\nMATCHER_P(EqualsSumOf, a, \"\") { return arg == a; }\nMATCHER_P2(EqualsSumOf, a, b, \"\") { return arg == a + b; }\nMATCHER_P3(EqualsSumOf, a, b, c, \"\") { return arg == a + b + c; }\nMATCHER_P4(EqualsSumOf, a, b, c, d, \"\") { return arg == a + b + c + d; }\nMATCHER_P5(EqualsSumOf, a, b, c, d, e, \"\") { return arg == a + b + c + d + e; }\nMATCHER_P6(EqualsSumOf, a, b, c, d, e, f, \"\") {\n  return arg == a + b + c + d + e + f;\n}\nMATCHER_P7(EqualsSumOf, a, b, c, d, e, f, g, \"\") {\n  return arg == a + b + c + d + e + f + g;\n}\nMATCHER_P8(EqualsSumOf, a, b, c, d, e, f, g, h, \"\") {\n  return arg == a + b + c + d + e + f + g + h;\n}\nMATCHER_P9(EqualsSumOf, a, b, c, d, e, f, g, h, i, \"\") {\n  return arg == a + b + c + d + e + f + g + h + i;\n}\nMATCHER_P10(EqualsSumOf, a, b, c, d, e, f, g, h, i, j, \"\") {\n  return arg == a + b + c + d + e + f + g + h + i + j;\n}\n\nTEST(MatcherPnMacroTest, CanBeOverloadedOnNumberOfParameters) {\n  EXPECT_THAT(0, EqualsSumOf());\n  EXPECT_THAT(1, EqualsSumOf(1));\n  EXPECT_THAT(12, EqualsSumOf(10, 2));\n  EXPECT_THAT(123, EqualsSumOf(100, 20, 3));\n  EXPECT_THAT(1234, EqualsSumOf(1000, 200, 30, 4));\n  EXPECT_THAT(12345, EqualsSumOf(10000, 2000, 300, 40, 5));\n  EXPECT_THAT(\"abcdef\",\n              EqualsSumOf(::std::string(\"a\"), 'b', 'c', \"d\", \"e\", 'f'));\n  EXPECT_THAT(\"abcdefg\",\n              EqualsSumOf(::std::string(\"a\"), 'b', 'c', \"d\", \"e\", 'f', 'g'));\n  EXPECT_THAT(\"abcdefgh\", EqualsSumOf(::std::string(\"a\"), 'b', 'c', \"d\", \"e\",\n                                      'f', 'g', \"h\"));\n  EXPECT_THAT(\"abcdefghi\", EqualsSumOf(::std::string(\"a\"), 'b', 'c', \"d\", \"e\",\n                                       'f', 'g', \"h\", 'i'));\n  EXPECT_THAT(\"abcdefghij\",\n              EqualsSumOf(::std::string(\"a\"), 'b', 'c', \"d\", \"e\", 'f', 'g', \"h\",\n                          'i', ::std::string(\"j\")));\n\n  EXPECT_THAT(1, Not(EqualsSumOf()));\n  EXPECT_THAT(-1, Not(EqualsSumOf(1)));\n  EXPECT_THAT(-12, Not(EqualsSumOf(10, 2)));\n  EXPECT_THAT(-123, Not(EqualsSumOf(100, 20, 3)));\n  EXPECT_THAT(-1234, Not(EqualsSumOf(1000, 200, 30, 4)));\n  EXPECT_THAT(-12345, Not(EqualsSumOf(10000, 2000, 300, 40, 5)));\n  EXPECT_THAT(\"abcdef \",\n              Not(EqualsSumOf(::std::string(\"a\"), 'b', 'c', \"d\", \"e\", 'f')));\n  EXPECT_THAT(\"abcdefg \", Not(EqualsSumOf(::std::string(\"a\"), 'b', 'c', \"d\",\n                                          \"e\", 'f', 'g')));\n  EXPECT_THAT(\"abcdefgh \", Not(EqualsSumOf(::std::string(\"a\"), 'b', 'c', \"d\",\n                                           \"e\", 'f', 'g', \"h\")));\n  EXPECT_THAT(\"abcdefghi \", Not(EqualsSumOf(::std::string(\"a\"), 'b', 'c', \"d\",\n                                            \"e\", 'f', 'g', \"h\", 'i')));\n  EXPECT_THAT(\"abcdefghij \",\n              Not(EqualsSumOf(::std::string(\"a\"), 'b', 'c', \"d\", \"e\", 'f', 'g',\n                              \"h\", 'i', ::std::string(\"j\"))));\n}\n\n// Tests that a MATCHER_Pn() definition can be instantiated with any\n// compatible parameter types.\nTEST(MatcherPnMacroTest, WorksForDifferentParameterTypes) {\n  EXPECT_THAT(123, EqualsSumOf(100L, 20, static_cast<char>(3)));\n  EXPECT_THAT(\"abcd\", EqualsSumOf(::std::string(\"a\"), \"b\", 'c', \"d\"));\n\n  EXPECT_THAT(124, Not(EqualsSumOf(100L, 20, static_cast<char>(3))));\n  EXPECT_THAT(\"abcde\", Not(EqualsSumOf(::std::string(\"a\"), \"b\", 'c', \"d\")));\n}\n\n// Tests that the matcher body can promote the parameter types.\n\nMATCHER_P2(EqConcat, prefix, suffix, \"\") {\n  // The following lines promote the two parameters to desired types.\n  std::string prefix_str(prefix);\n  char suffix_char = static_cast<char>(suffix);\n  return arg == prefix_str + suffix_char;\n}\n\nTEST(MatcherPnMacroTest, SimpleTypePromotion) {\n  Matcher<std::string> no_promo = EqConcat(std::string(\"foo\"), 't');\n  Matcher<const std::string&> promo = EqConcat(\"foo\", static_cast<int>('t'));\n  EXPECT_FALSE(no_promo.Matches(\"fool\"));\n  EXPECT_FALSE(promo.Matches(\"fool\"));\n  EXPECT_TRUE(no_promo.Matches(\"foot\"));\n  EXPECT_TRUE(promo.Matches(\"foot\"));\n}\n\n// Verifies the type of a MATCHER*.\n\nTEST(MatcherPnMacroTest, TypesAreCorrect) {\n  // EqualsSumOf() must be assignable to a EqualsSumOfMatcher variable.\n  EqualsSumOfMatcher a0 = EqualsSumOf();\n\n  // EqualsSumOf(1) must be assignable to a EqualsSumOfMatcherP variable.\n  EqualsSumOfMatcherP<int> a1 = EqualsSumOf(1);\n\n  // EqualsSumOf(p1, ..., pk) must be assignable to a EqualsSumOfMatcherPk\n  // variable, and so on.\n  EqualsSumOfMatcherP2<int, char> a2 = EqualsSumOf(1, '2');\n  EqualsSumOfMatcherP3<int, int, char> a3 = EqualsSumOf(1, 2, '3');\n  EqualsSumOfMatcherP4<int, int, int, char> a4 = EqualsSumOf(1, 2, 3, '4');\n  EqualsSumOfMatcherP5<int, int, int, int, char> a5 =\n      EqualsSumOf(1, 2, 3, 4, '5');\n  EqualsSumOfMatcherP6<int, int, int, int, int, char> a6 =\n      EqualsSumOf(1, 2, 3, 4, 5, '6');\n  EqualsSumOfMatcherP7<int, int, int, int, int, int, char> a7 =\n      EqualsSumOf(1, 2, 3, 4, 5, 6, '7');\n  EqualsSumOfMatcherP8<int, int, int, int, int, int, int, char> a8 =\n      EqualsSumOf(1, 2, 3, 4, 5, 6, 7, '8');\n  EqualsSumOfMatcherP9<int, int, int, int, int, int, int, int, char> a9 =\n      EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, '9');\n  EqualsSumOfMatcherP10<int, int, int, int, int, int, int, int, int, char> a10 =\n      EqualsSumOf(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');\n\n  // Avoid \"unused variable\" warnings.\n  (void)a0;\n  (void)a1;\n  (void)a2;\n  (void)a3;\n  (void)a4;\n  (void)a5;\n  (void)a6;\n  (void)a7;\n  (void)a8;\n  (void)a9;\n  (void)a10;\n}\n\n// Tests that matcher-typed parameters can be used in Value() inside a\n// MATCHER_Pn definition.\n\n// Succeeds if arg matches exactly 2 of the 3 matchers.\nMATCHER_P3(TwoOf, m1, m2, m3, \"\") {\n  const int count = static_cast<int>(Value(arg, m1)) +\n                    static_cast<int>(Value(arg, m2)) +\n                    static_cast<int>(Value(arg, m3));\n  return count == 2;\n}\n\nTEST(MatcherPnMacroTest, CanUseMatcherTypedParameterInValue) {\n  EXPECT_THAT(42, TwoOf(Gt(0), Lt(50), Eq(10)));\n  EXPECT_THAT(0, Not(TwoOf(Gt(-1), Lt(1), Eq(0))));\n}\n\n// Tests Contains().Times().\n\nINSTANTIATE_GTEST_MATCHER_TEST_P(ContainsTimes);\n\nTEST(ContainsTimes, ListMatchesWhenElementQuantityMatches) {\n  list<int> some_list;\n  some_list.push_back(3);\n  some_list.push_back(1);\n  some_list.push_back(2);\n  some_list.push_back(3);\n  EXPECT_THAT(some_list, Contains(3).Times(2));\n  EXPECT_THAT(some_list, Contains(2).Times(1));\n  EXPECT_THAT(some_list, Contains(Ge(2)).Times(3));\n  EXPECT_THAT(some_list, Contains(Ge(2)).Times(Gt(2)));\n  EXPECT_THAT(some_list, Contains(4).Times(0));\n  EXPECT_THAT(some_list, Contains(_).Times(4));\n  EXPECT_THAT(some_list, Not(Contains(5).Times(1)));\n  EXPECT_THAT(some_list, Contains(5).Times(_));  // Times(_) always matches\n  EXPECT_THAT(some_list, Not(Contains(3).Times(1)));\n  EXPECT_THAT(some_list, Contains(3).Times(Not(1)));\n  EXPECT_THAT(list<int>{}, Not(Contains(_)));\n}\n\nTEST_P(ContainsTimesP, ExplainsMatchResultCorrectly) {\n  const int a[2] = {1, 2};\n  Matcher<const int(&)[2]> m = Contains(2).Times(3);\n  EXPECT_EQ(\n      \"whose element #1 matches but whose match quantity of 1 does not match\",\n      Explain(m, a));\n\n  m = Contains(3).Times(0);\n  EXPECT_EQ(\"has no element that matches and whose match quantity of 0 matches\",\n            Explain(m, a));\n\n  m = Contains(3).Times(4);\n  EXPECT_EQ(\n      \"has no element that matches and whose match quantity of 0 does not \"\n      \"match\",\n      Explain(m, a));\n\n  m = Contains(2).Times(4);\n  EXPECT_EQ(\n      \"whose element #1 matches but whose match quantity of 1 does not \"\n      \"match\",\n      Explain(m, a));\n\n  m = Contains(GreaterThan(0)).Times(2);\n  EXPECT_EQ(\"whose elements (0, 1) match and whose match quantity of 2 matches\",\n            Explain(m, a));\n\n  m = Contains(GreaterThan(10)).Times(Gt(1));\n  EXPECT_EQ(\n      \"has no element that matches and whose match quantity of 0 does not \"\n      \"match\",\n      Explain(m, a));\n\n  m = Contains(GreaterThan(0)).Times(GreaterThan<size_t>(5));\n  EXPECT_EQ(\n      \"whose elements (0, 1) match but whose match quantity of 2 does not \"\n      \"match, which is 3 less than 5\",\n      Explain(m, a));\n}\n\nTEST(ContainsTimes, DescribesItselfCorrectly) {\n  Matcher<vector<int>> m = Contains(1).Times(2);\n  EXPECT_EQ(\"quantity of elements that match is equal to 1 is equal to 2\",\n            Describe(m));\n\n  Matcher<vector<int>> m2 = Not(m);\n  EXPECT_EQ(\"quantity of elements that match is equal to 1 isn't equal to 2\",\n            Describe(m2));\n}\n\n// Tests AllOfArray()\n\nTEST(AllOfArrayTest, BasicForms) {\n  // Iterator\n  std::vector<int> v0{};\n  std::vector<int> v1{1};\n  std::vector<int> v2{2, 3};\n  std::vector<int> v3{4, 4, 4};\n  EXPECT_THAT(0, AllOfArray(v0.begin(), v0.end()));\n  EXPECT_THAT(1, AllOfArray(v1.begin(), v1.end()));\n  EXPECT_THAT(2, Not(AllOfArray(v1.begin(), v1.end())));\n  EXPECT_THAT(3, Not(AllOfArray(v2.begin(), v2.end())));\n  EXPECT_THAT(4, AllOfArray(v3.begin(), v3.end()));\n  // Pointer +  size\n  int ar[6] = {1, 2, 3, 4, 4, 4};\n  EXPECT_THAT(0, AllOfArray(ar, 0));\n  EXPECT_THAT(1, AllOfArray(ar, 1));\n  EXPECT_THAT(2, Not(AllOfArray(ar, 1)));\n  EXPECT_THAT(3, Not(AllOfArray(ar + 1, 3)));\n  EXPECT_THAT(4, AllOfArray(ar + 3, 3));\n  // Array\n  // int ar0[0];  Not usable\n  int ar1[1] = {1};\n  int ar2[2] = {2, 3};\n  int ar3[3] = {4, 4, 4};\n  // EXPECT_THAT(0, Not(AllOfArray(ar0)));  // Cannot work\n  EXPECT_THAT(1, AllOfArray(ar1));\n  EXPECT_THAT(2, Not(AllOfArray(ar1)));\n  EXPECT_THAT(3, Not(AllOfArray(ar2)));\n  EXPECT_THAT(4, AllOfArray(ar3));\n  // Container\n  EXPECT_THAT(0, AllOfArray(v0));\n  EXPECT_THAT(1, AllOfArray(v1));\n  EXPECT_THAT(2, Not(AllOfArray(v1)));\n  EXPECT_THAT(3, Not(AllOfArray(v2)));\n  EXPECT_THAT(4, AllOfArray(v3));\n  // Initializer\n  EXPECT_THAT(0, AllOfArray<int>({}));  // Requires template arg.\n  EXPECT_THAT(1, AllOfArray({1}));\n  EXPECT_THAT(2, Not(AllOfArray({1})));\n  EXPECT_THAT(3, Not(AllOfArray({2, 3})));\n  EXPECT_THAT(4, AllOfArray({4, 4, 4}));\n}\n\nTEST(AllOfArrayTest, Matchers) {\n  // vector\n  std::vector<Matcher<int>> matchers{Ge(1), Lt(2)};\n  EXPECT_THAT(0, Not(AllOfArray(matchers)));\n  EXPECT_THAT(1, AllOfArray(matchers));\n  EXPECT_THAT(2, Not(AllOfArray(matchers)));\n  // initializer_list\n  EXPECT_THAT(0, Not(AllOfArray({Ge(0), Ge(1)})));\n  EXPECT_THAT(1, AllOfArray({Ge(0), Ge(1)}));\n}\n\nINSTANTIATE_GTEST_MATCHER_TEST_P(AnyOfArrayTest);\n\nTEST(AnyOfArrayTest, BasicForms) {\n  // Iterator\n  std::vector<int> v0{};\n  std::vector<int> v1{1};\n  std::vector<int> v2{2, 3};\n  EXPECT_THAT(0, Not(AnyOfArray(v0.begin(), v0.end())));\n  EXPECT_THAT(1, AnyOfArray(v1.begin(), v1.end()));\n  EXPECT_THAT(2, Not(AnyOfArray(v1.begin(), v1.end())));\n  EXPECT_THAT(3, AnyOfArray(v2.begin(), v2.end()));\n  EXPECT_THAT(4, Not(AnyOfArray(v2.begin(), v2.end())));\n  // Pointer +  size\n  int ar[3] = {1, 2, 3};\n  EXPECT_THAT(0, Not(AnyOfArray(ar, 0)));\n  EXPECT_THAT(1, AnyOfArray(ar, 1));\n  EXPECT_THAT(2, Not(AnyOfArray(ar, 1)));\n  EXPECT_THAT(3, AnyOfArray(ar + 1, 2));\n  EXPECT_THAT(4, Not(AnyOfArray(ar + 1, 2)));\n  // Array\n  // int ar0[0];  Not usable\n  int ar1[1] = {1};\n  int ar2[2] = {2, 3};\n  // EXPECT_THAT(0, Not(AnyOfArray(ar0)));  // Cannot work\n  EXPECT_THAT(1, AnyOfArray(ar1));\n  EXPECT_THAT(2, Not(AnyOfArray(ar1)));\n  EXPECT_THAT(3, AnyOfArray(ar2));\n  EXPECT_THAT(4, Not(AnyOfArray(ar2)));\n  // Container\n  EXPECT_THAT(0, Not(AnyOfArray(v0)));\n  EXPECT_THAT(1, AnyOfArray(v1));\n  EXPECT_THAT(2, Not(AnyOfArray(v1)));\n  EXPECT_THAT(3, AnyOfArray(v2));\n  EXPECT_THAT(4, Not(AnyOfArray(v2)));\n  // Initializer\n  EXPECT_THAT(0, Not(AnyOfArray<int>({})));  // Requires template arg.\n  EXPECT_THAT(1, AnyOfArray({1}));\n  EXPECT_THAT(2, Not(AnyOfArray({1})));\n  EXPECT_THAT(3, AnyOfArray({2, 3}));\n  EXPECT_THAT(4, Not(AnyOfArray({2, 3})));\n}\n\nTEST(AnyOfArrayTest, Matchers) {\n  // We negate test AllOfArrayTest.Matchers.\n  // vector\n  std::vector<Matcher<int>> matchers{Lt(1), Ge(2)};\n  EXPECT_THAT(0, AnyOfArray(matchers));\n  EXPECT_THAT(1, Not(AnyOfArray(matchers)));\n  EXPECT_THAT(2, AnyOfArray(matchers));\n  // initializer_list\n  EXPECT_THAT(0, AnyOfArray({Lt(0), Lt(1)}));\n  EXPECT_THAT(1, Not(AllOfArray({Lt(0), Lt(1)})));\n}\n\nTEST_P(AnyOfArrayTestP, ExplainsMatchResultCorrectly) {\n  // AnyOfArray and AllOfArry use the same underlying template-template,\n  // thus it is sufficient to test one here.\n  const std::vector<int> v0{};\n  const std::vector<int> v1{1};\n  const std::vector<int> v2{2, 3};\n  const Matcher<int> m0 = AnyOfArray(v0);\n  const Matcher<int> m1 = AnyOfArray(v1);\n  const Matcher<int> m2 = AnyOfArray(v2);\n  EXPECT_EQ(\"\", Explain(m0, 0));\n  EXPECT_EQ(\"\", Explain(m1, 1));\n  EXPECT_EQ(\"\", Explain(m1, 2));\n  EXPECT_EQ(\"\", Explain(m2, 3));\n  EXPECT_EQ(\"\", Explain(m2, 4));\n  EXPECT_EQ(\"()\", Describe(m0));\n  EXPECT_EQ(\"(is equal to 1)\", Describe(m1));\n  EXPECT_EQ(\"(is equal to 2) or (is equal to 3)\", Describe(m2));\n  EXPECT_EQ(\"()\", DescribeNegation(m0));\n  EXPECT_EQ(\"(isn't equal to 1)\", DescribeNegation(m1));\n  EXPECT_EQ(\"(isn't equal to 2) and (isn't equal to 3)\", DescribeNegation(m2));\n  // Explain with matchers\n  const Matcher<int> g1 = AnyOfArray({GreaterThan(1)});\n  const Matcher<int> g2 = AnyOfArray({GreaterThan(1), GreaterThan(2)});\n  // Explains the first positive match and all prior negative matches...\n  EXPECT_EQ(\"which is 1 less than 1\", Explain(g1, 0));\n  EXPECT_EQ(\"which is the same as 1\", Explain(g1, 1));\n  EXPECT_EQ(\"which is 1 more than 1\", Explain(g1, 2));\n  EXPECT_EQ(\"which is 1 less than 1, and which is 2 less than 2\",\n            Explain(g2, 0));\n  EXPECT_EQ(\"which is the same as 1, and which is 1 less than 2\",\n            Explain(g2, 1));\n  EXPECT_EQ(\"which is 1 more than 1\",  // Only the first\n            Explain(g2, 2));\n}\n\nMATCHER(IsNotNull, \"\") { return arg != nullptr; }\n\n// Verifies that a matcher defined using MATCHER() can work on\n// move-only types.\nTEST(MatcherMacroTest, WorksOnMoveOnlyType) {\n  std::unique_ptr<int> p(new int(3));\n  EXPECT_THAT(p, IsNotNull());\n  EXPECT_THAT(std::unique_ptr<int>(), Not(IsNotNull()));\n}\n\nMATCHER_P(UniquePointee, pointee, \"\") { return *arg == pointee; }\n\n// Verifies that a matcher defined using MATCHER_P*() can work on\n// move-only types.\nTEST(MatcherPMacroTest, WorksOnMoveOnlyType) {\n  std::unique_ptr<int> p(new int(3));\n  EXPECT_THAT(p, UniquePointee(3));\n  EXPECT_THAT(p, Not(UniquePointee(2)));\n}\n\n#if GTEST_HAS_EXCEPTIONS\n\n// std::function<void()> is used below for compatibility with older copies of\n// GCC. Normally, a raw lambda is all that is needed.\n\n// Test that examples from documentation compile\nTEST(ThrowsTest, Examples) {\n  EXPECT_THAT(\n      std::function<void()>([]() { throw std::runtime_error(\"message\"); }),\n      Throws<std::runtime_error>());\n\n  EXPECT_THAT(\n      std::function<void()>([]() { throw std::runtime_error(\"message\"); }),\n      ThrowsMessage<std::runtime_error>(HasSubstr(\"message\")));\n}\n\nTEST(ThrowsTest, PrintsExceptionWhat) {\n  EXPECT_THAT(\n      std::function<void()>([]() { throw std::runtime_error(\"ABC123XYZ\"); }),\n      ThrowsMessage<std::runtime_error>(HasSubstr(\"ABC123XYZ\")));\n}\n\nTEST(ThrowsTest, DoesNotGenerateDuplicateCatchClauseWarning) {\n  EXPECT_THAT(std::function<void()>([]() { throw std::exception(); }),\n              Throws<std::exception>());\n}\n\nTEST(ThrowsTest, CallableExecutedExactlyOnce) {\n  size_t a = 0;\n\n  EXPECT_THAT(std::function<void()>([&a]() {\n                a++;\n                throw 10;\n              }),\n              Throws<int>());\n  EXPECT_EQ(a, 1u);\n\n  EXPECT_THAT(std::function<void()>([&a]() {\n                a++;\n                throw std::runtime_error(\"message\");\n              }),\n              Throws<std::runtime_error>());\n  EXPECT_EQ(a, 2u);\n\n  EXPECT_THAT(std::function<void()>([&a]() {\n                a++;\n                throw std::runtime_error(\"message\");\n              }),\n              ThrowsMessage<std::runtime_error>(HasSubstr(\"message\")));\n  EXPECT_EQ(a, 3u);\n\n  EXPECT_THAT(std::function<void()>([&a]() {\n                a++;\n                throw std::runtime_error(\"message\");\n              }),\n              Throws<std::runtime_error>(\n                  Property(&std::runtime_error::what, HasSubstr(\"message\"))));\n  EXPECT_EQ(a, 4u);\n}\n\nTEST(ThrowsTest, Describe) {\n  Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();\n  std::stringstream ss;\n  matcher.DescribeTo(&ss);\n  auto explanation = ss.str();\n  EXPECT_THAT(explanation, HasSubstr(\"std::runtime_error\"));\n}\n\nTEST(ThrowsTest, Success) {\n  Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();\n  StringMatchResultListener listener;\n  EXPECT_TRUE(matcher.MatchAndExplain(\n      []() { throw std::runtime_error(\"error message\"); }, &listener));\n  EXPECT_THAT(listener.str(), HasSubstr(\"std::runtime_error\"));\n}\n\nTEST(ThrowsTest, FailWrongType) {\n  Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();\n  StringMatchResultListener listener;\n  EXPECT_FALSE(matcher.MatchAndExplain(\n      []() { throw std::logic_error(\"error message\"); }, &listener));\n  EXPECT_THAT(listener.str(), HasSubstr(\"std::logic_error\"));\n  EXPECT_THAT(listener.str(), HasSubstr(\"\\\"error message\\\"\"));\n}\n\nTEST(ThrowsTest, FailWrongTypeNonStd) {\n  Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();\n  StringMatchResultListener listener;\n  EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));\n  EXPECT_THAT(listener.str(),\n              HasSubstr(\"throws an exception of an unknown type\"));\n}\n\nTEST(ThrowsTest, FailNoThrow) {\n  Matcher<std::function<void()>> matcher = Throws<std::runtime_error>();\n  StringMatchResultListener listener;\n  EXPECT_FALSE(matcher.MatchAndExplain([]() { (void)0; }, &listener));\n  EXPECT_THAT(listener.str(), HasSubstr(\"does not throw any exception\"));\n}\n\nclass ThrowsPredicateTest\n    : public TestWithParam<Matcher<std::function<void()>>> {};\n\nTEST_P(ThrowsPredicateTest, Describe) {\n  Matcher<std::function<void()>> matcher = GetParam();\n  std::stringstream ss;\n  matcher.DescribeTo(&ss);\n  auto explanation = ss.str();\n  EXPECT_THAT(explanation, HasSubstr(\"std::runtime_error\"));\n  EXPECT_THAT(explanation, HasSubstr(\"error message\"));\n}\n\nTEST_P(ThrowsPredicateTest, Success) {\n  Matcher<std::function<void()>> matcher = GetParam();\n  StringMatchResultListener listener;\n  EXPECT_TRUE(matcher.MatchAndExplain(\n      []() { throw std::runtime_error(\"error message\"); }, &listener));\n  EXPECT_THAT(listener.str(), HasSubstr(\"std::runtime_error\"));\n}\n\nTEST_P(ThrowsPredicateTest, FailWrongType) {\n  Matcher<std::function<void()>> matcher = GetParam();\n  StringMatchResultListener listener;\n  EXPECT_FALSE(matcher.MatchAndExplain(\n      []() { throw std::logic_error(\"error message\"); }, &listener));\n  EXPECT_THAT(listener.str(), HasSubstr(\"std::logic_error\"));\n  EXPECT_THAT(listener.str(), HasSubstr(\"\\\"error message\\\"\"));\n}\n\nTEST_P(ThrowsPredicateTest, FailWrongTypeNonStd) {\n  Matcher<std::function<void()>> matcher = GetParam();\n  StringMatchResultListener listener;\n  EXPECT_FALSE(matcher.MatchAndExplain([]() { throw 10; }, &listener));\n  EXPECT_THAT(listener.str(),\n              HasSubstr(\"throws an exception of an unknown type\"));\n}\n\nTEST_P(ThrowsPredicateTest, FailNoThrow) {\n  Matcher<std::function<void()>> matcher = GetParam();\n  StringMatchResultListener listener;\n  EXPECT_FALSE(matcher.MatchAndExplain([]() {}, &listener));\n  EXPECT_THAT(listener.str(), HasSubstr(\"does not throw any exception\"));\n}\n\nINSTANTIATE_TEST_SUITE_P(\n    AllMessagePredicates, ThrowsPredicateTest,\n    Values(Matcher<std::function<void()>>(\n        ThrowsMessage<std::runtime_error>(HasSubstr(\"error message\")))));\n\n// Tests that Throws<E1>(Matcher<E2>{}) compiles even when E2 != const E1&.\nTEST(ThrowsPredicateCompilesTest, ExceptionMatcherAcceptsBroadType) {\n  {\n    Matcher<std::function<void()>> matcher =\n        ThrowsMessage<std::runtime_error>(HasSubstr(\"error message\"));\n    EXPECT_TRUE(\n        matcher.Matches([]() { throw std::runtime_error(\"error message\"); }));\n    EXPECT_FALSE(\n        matcher.Matches([]() { throw std::runtime_error(\"wrong message\"); }));\n  }\n\n  {\n    Matcher<uint64_t> inner = Eq(10);\n    Matcher<std::function<void()>> matcher = Throws<uint32_t>(inner);\n    EXPECT_TRUE(matcher.Matches([]() { throw(uint32_t) 10; }));\n    EXPECT_FALSE(matcher.Matches([]() { throw(uint32_t) 11; }));\n  }\n}\n\n// Tests that ThrowsMessage(\"message\") is equivalent\n// to ThrowsMessage(Eq<std::string>(\"message\")).\nTEST(ThrowsPredicateCompilesTest, MessageMatcherAcceptsNonMatcher) {\n  Matcher<std::function<void()>> matcher =\n      ThrowsMessage<std::runtime_error>(\"error message\");\n  EXPECT_TRUE(\n      matcher.Matches([]() { throw std::runtime_error(\"error message\"); }));\n  EXPECT_FALSE(matcher.Matches(\n      []() { throw std::runtime_error(\"wrong error message\"); }));\n}\n\n#endif  // GTEST_HAS_EXCEPTIONS\n\n}  // namespace\n}  // namespace gmock_matchers_test\n}  // namespace testing\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock-matchers_test.h",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file tests some commonly used argument matchers.\n\n#ifndef GOOGLEMOCK_TEST_GMOCK_MATCHERS_TEST_H_\n#define GOOGLEMOCK_TEST_GMOCK_MATCHERS_TEST_H_\n\n#include <string.h>\n#include <time.h>\n\n#include <array>\n#include <cstdint>\n#include <deque>\n#include <forward_list>\n#include <functional>\n#include <iostream>\n#include <iterator>\n#include <limits>\n#include <list>\n#include <map>\n#include <memory>\n#include <set>\n#include <sstream>\n#include <string>\n#include <type_traits>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#include \"gmock/gmock-matchers.h\"\n#include \"gmock/gmock-more-matchers.h\"\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest-spi.h\"\n#include \"gtest/gtest.h\"\n\nnamespace testing {\nnamespace gmock_matchers_test {\n\nusing std::greater;\nusing std::less;\nusing std::list;\nusing std::make_pair;\nusing std::map;\nusing std::multimap;\nusing std::multiset;\nusing std::ostream;\nusing std::pair;\nusing std::set;\nusing std::stringstream;\nusing std::vector;\nusing testing::internal::DummyMatchResultListener;\nusing testing::internal::ElementMatcherPair;\nusing testing::internal::ElementMatcherPairs;\nusing testing::internal::ElementsAreArrayMatcher;\nusing testing::internal::ExplainMatchFailureTupleTo;\nusing testing::internal::FloatingEqMatcher;\nusing testing::internal::FormatMatcherDescription;\nusing testing::internal::IsReadableTypeName;\nusing testing::internal::MatchMatrix;\nusing testing::internal::PredicateFormatterFromMatcher;\nusing testing::internal::RE;\nusing testing::internal::StreamMatchResultListener;\nusing testing::internal::Strings;\n\n// Helper for testing container-valued matchers in mock method context. It is\n// important to test matchers in this context, since it requires additional type\n// deduction beyond what EXPECT_THAT does, thus making it more restrictive.\nstruct ContainerHelper {\n  MOCK_METHOD1(Call, void(std::vector<std::unique_ptr<int>>));\n};\n\n// For testing ExplainMatchResultTo().\ntemplate <typename T>\nstruct GtestGreaterThanMatcher {\n  using is_gtest_matcher = void;\n\n  void DescribeTo(ostream* os) const { *os << \"is > \" << rhs; }\n  void DescribeNegationTo(ostream* os) const { *os << \"is <= \" << rhs; }\n\n  bool MatchAndExplain(T lhs, MatchResultListener* listener) const {\n    if (lhs > rhs) {\n      *listener << \"which is \" << (lhs - rhs) << \" more than \" << rhs;\n    } else if (lhs == rhs) {\n      *listener << \"which is the same as \" << rhs;\n    } else {\n      *listener << \"which is \" << (rhs - lhs) << \" less than \" << rhs;\n    }\n\n    return lhs > rhs;\n  }\n\n  T rhs;\n};\n\ntemplate <typename T>\nGtestGreaterThanMatcher<typename std::decay<T>::type> GtestGreaterThan(\n    T&& rhs) {\n  return {rhs};\n}\n\n// As the matcher above, but using the base class with virtual functions.\ntemplate <typename T>\nclass GreaterThanMatcher : public MatcherInterface<T> {\n public:\n  explicit GreaterThanMatcher(T rhs) : impl_{rhs} {}\n\n  void DescribeTo(ostream* os) const override { impl_.DescribeTo(os); }\n  void DescribeNegationTo(ostream* os) const override {\n    impl_.DescribeNegationTo(os);\n  }\n\n  bool MatchAndExplain(T lhs, MatchResultListener* listener) const override {\n    return impl_.MatchAndExplain(lhs, listener);\n  }\n\n private:\n  const GtestGreaterThanMatcher<T> impl_;\n};\n\n// Names and instantiates a new instance of GTestMatcherTestP.\n#define INSTANTIATE_GTEST_MATCHER_TEST_P(TestSuite)                         \\\n  using TestSuite##P = GTestMatcherTestP;                                   \\\n  INSTANTIATE_TEST_SUITE_P(MatcherInterface, TestSuite##P, Values(false));  \\\n  INSTANTIATE_TEST_SUITE_P(GtestMatcher, TestSuite##P, Values(true))\n\nclass GTestMatcherTestP : public testing::TestWithParam<bool> {\n public:\n  template <typename T>\n  Matcher<T> GreaterThan(T n) {\n    if (use_gtest_matcher_) {\n      return GtestGreaterThan(n);\n    } else {\n      return MakeMatcher(new GreaterThanMatcher<T>(n));\n    }\n  }\n  const bool use_gtest_matcher_ = GetParam();\n};\n\n// Returns the description of the given matcher.\ntemplate <typename T>\nstd::string Describe(const Matcher<T>& m) {\n  return DescribeMatcher<T>(m);\n}\n\n// Returns the description of the negation of the given matcher.\ntemplate <typename T>\nstd::string DescribeNegation(const Matcher<T>& m) {\n  return DescribeMatcher<T>(m, true);\n}\n\n// Returns the reason why x matches, or doesn't match, m.\ntemplate <typename MatcherType, typename Value>\nstd::string Explain(const MatcherType& m, const Value& x) {\n  StringMatchResultListener listener;\n  ExplainMatchResult(m, x, &listener);\n  return listener.str();\n}\n\n}  // namespace gmock_matchers_test\n}  // namespace testing\n\n#endif  // GOOGLEMOCK_TEST_GMOCK_MATCHERS_TEST_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock-more-actions_test.cc",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file tests the built-in actions in gmock-actions.h.\n\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 4577)\n#endif\n\n#include \"gmock/gmock-more-actions.h\"\n\n#include <functional>\n#include <memory>\n#include <sstream>\n#include <string>\n\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest-spi.h\"\n#include \"gtest/gtest.h\"\n\nnamespace testing {\nnamespace gmock_more_actions_test {\n\nusing ::std::plus;\nusing ::std::string;\nusing testing::Action;\nusing testing::DeleteArg;\nusing testing::Invoke;\nusing testing::ReturnArg;\nusing testing::ReturnPointee;\nusing testing::SaveArg;\nusing testing::SaveArgPointee;\nusing testing::SetArgReferee;\nusing testing::Unused;\nusing testing::WithArg;\nusing testing::WithoutArgs;\n\n// For suppressing compiler warnings on conversion possibly losing precision.\ninline short Short(short n) { return n; }  // NOLINT\ninline char Char(char ch) { return ch; }\n\n// Sample functions and functors for testing Invoke() and etc.\nint Nullary() { return 1; }\n\nbool g_done = false;\n\nbool Unary(int x) { return x < 0; }\n\nbool ByConstRef(const std::string& s) { return s == \"Hi\"; }\n\nconst double g_double = 0;\nbool ReferencesGlobalDouble(const double& x) { return &x == &g_double; }\n\nstruct UnaryFunctor {\n  int operator()(bool x) { return x ? 1 : -1; }\n};\n\nconst char* Binary(const char* input, short n) { return input + n; }  // NOLINT\n\nint Ternary(int x, char y, short z) { return x + y + z; }  // NOLINT\n\nint SumOf4(int a, int b, int c, int d) { return a + b + c + d; }\n\nint SumOfFirst2(int a, int b, Unused, Unused) { return a + b; }\n\nint SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; }\n\nstruct SumOf5Functor {\n  int operator()(int a, int b, int c, int d, int e) {\n    return a + b + c + d + e;\n  }\n};\n\nint SumOf6(int a, int b, int c, int d, int e, int f) {\n  return a + b + c + d + e + f;\n}\n\nstruct SumOf6Functor {\n  int operator()(int a, int b, int c, int d, int e, int f) {\n    return a + b + c + d + e + f;\n  }\n};\n\nstd::string Concat7(const char* s1, const char* s2, const char* s3,\n                    const char* s4, const char* s5, const char* s6,\n                    const char* s7) {\n  return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7;\n}\n\nstd::string Concat8(const char* s1, const char* s2, const char* s3,\n                    const char* s4, const char* s5, const char* s6,\n                    const char* s7, const char* s8) {\n  return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8;\n}\n\nstd::string Concat9(const char* s1, const char* s2, const char* s3,\n                    const char* s4, const char* s5, const char* s6,\n                    const char* s7, const char* s8, const char* s9) {\n  return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9;\n}\n\nstd::string Concat10(const char* s1, const char* s2, const char* s3,\n                     const char* s4, const char* s5, const char* s6,\n                     const char* s7, const char* s8, const char* s9,\n                     const char* s10) {\n  return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10;\n}\n\nclass Foo {\n public:\n  Foo() : value_(123) {}\n\n  int Nullary() const { return value_; }\n\n  short Unary(long x) { return static_cast<short>(value_ + x); }  // NOLINT\n\n  std::string Binary(const std::string& str, char c) const { return str + c; }\n\n  int Ternary(int x, bool y, char z) { return value_ + x + y * z; }\n\n  int SumOf4(int a, int b, int c, int d) const {\n    return a + b + c + d + value_;\n  }\n\n  int SumOfLast2(Unused, Unused, int a, int b) const { return a + b; }\n\n  int SumOf5(int a, int b, int c, int d, int e) { return a + b + c + d + e; }\n\n  int SumOf6(int a, int b, int c, int d, int e, int f) {\n    return a + b + c + d + e + f;\n  }\n\n  std::string Concat7(const char* s1, const char* s2, const char* s3,\n                      const char* s4, const char* s5, const char* s6,\n                      const char* s7) {\n    return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7;\n  }\n\n  std::string Concat8(const char* s1, const char* s2, const char* s3,\n                      const char* s4, const char* s5, const char* s6,\n                      const char* s7, const char* s8) {\n    return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8;\n  }\n\n  std::string Concat9(const char* s1, const char* s2, const char* s3,\n                      const char* s4, const char* s5, const char* s6,\n                      const char* s7, const char* s8, const char* s9) {\n    return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9;\n  }\n\n  std::string Concat10(const char* s1, const char* s2, const char* s3,\n                       const char* s4, const char* s5, const char* s6,\n                       const char* s7, const char* s8, const char* s9,\n                       const char* s10) {\n    return std::string(s1) + s2 + s3 + s4 + s5 + s6 + s7 + s8 + s9 + s10;\n  }\n\n private:\n  int value_;\n};\n\n// Tests using Invoke() with a nullary function.\nTEST(InvokeTest, Nullary) {\n  Action<int()> a = Invoke(Nullary);  // NOLINT\n  EXPECT_EQ(1, a.Perform(std::make_tuple()));\n}\n\n// Tests using Invoke() with a unary function.\nTEST(InvokeTest, Unary) {\n  Action<bool(int)> a = Invoke(Unary);  // NOLINT\n  EXPECT_FALSE(a.Perform(std::make_tuple(1)));\n  EXPECT_TRUE(a.Perform(std::make_tuple(-1)));\n}\n\n// Tests using Invoke() with a binary function.\nTEST(InvokeTest, Binary) {\n  Action<const char*(const char*, short)> a = Invoke(Binary);  // NOLINT\n  const char* p = \"Hello\";\n  EXPECT_EQ(p + 2, a.Perform(std::make_tuple(p, Short(2))));\n}\n\n// Tests using Invoke() with a ternary function.\nTEST(InvokeTest, Ternary) {\n  Action<int(int, char, short)> a = Invoke(Ternary);  // NOLINT\n  EXPECT_EQ(6, a.Perform(std::make_tuple(1, '\\2', Short(3))));\n}\n\n// Tests using Invoke() with a 4-argument function.\nTEST(InvokeTest, FunctionThatTakes4Arguments) {\n  Action<int(int, int, int, int)> a = Invoke(SumOf4);  // NOLINT\n  EXPECT_EQ(1234, a.Perform(std::make_tuple(1000, 200, 30, 4)));\n}\n\n// Tests using Invoke() with a 5-argument function.\nTEST(InvokeTest, FunctionThatTakes5Arguments) {\n  Action<int(int, int, int, int, int)> a = Invoke(SumOf5);  // NOLINT\n  EXPECT_EQ(12345, a.Perform(std::make_tuple(10000, 2000, 300, 40, 5)));\n}\n\n// Tests using Invoke() with a 6-argument function.\nTEST(InvokeTest, FunctionThatTakes6Arguments) {\n  Action<int(int, int, int, int, int, int)> a = Invoke(SumOf6);  // NOLINT\n  EXPECT_EQ(123456,\n            a.Perform(std::make_tuple(100000, 20000, 3000, 400, 50, 6)));\n}\n\n// A helper that turns the type of a C-string literal from const\n// char[N] to const char*.\ninline const char* CharPtr(const char* s) { return s; }\n\n// Tests using Invoke() with a 7-argument function.\nTEST(InvokeTest, FunctionThatTakes7Arguments) {\n  Action<std::string(const char*, const char*, const char*, const char*,\n                     const char*, const char*, const char*)>\n      a = Invoke(Concat7);\n  EXPECT_EQ(\"1234567\",\n            a.Perform(std::make_tuple(CharPtr(\"1\"), CharPtr(\"2\"), CharPtr(\"3\"),\n                                      CharPtr(\"4\"), CharPtr(\"5\"), CharPtr(\"6\"),\n                                      CharPtr(\"7\"))));\n}\n\n// Tests using Invoke() with a 8-argument function.\nTEST(InvokeTest, FunctionThatTakes8Arguments) {\n  Action<std::string(const char*, const char*, const char*, const char*,\n                     const char*, const char*, const char*, const char*)>\n      a = Invoke(Concat8);\n  EXPECT_EQ(\"12345678\",\n            a.Perform(std::make_tuple(CharPtr(\"1\"), CharPtr(\"2\"), CharPtr(\"3\"),\n                                      CharPtr(\"4\"), CharPtr(\"5\"), CharPtr(\"6\"),\n                                      CharPtr(\"7\"), CharPtr(\"8\"))));\n}\n\n// Tests using Invoke() with a 9-argument function.\nTEST(InvokeTest, FunctionThatTakes9Arguments) {\n  Action<std::string(const char*, const char*, const char*, const char*,\n                     const char*, const char*, const char*, const char*,\n                     const char*)>\n      a = Invoke(Concat9);\n  EXPECT_EQ(\"123456789\", a.Perform(std::make_tuple(\n                             CharPtr(\"1\"), CharPtr(\"2\"), CharPtr(\"3\"),\n                             CharPtr(\"4\"), CharPtr(\"5\"), CharPtr(\"6\"),\n                             CharPtr(\"7\"), CharPtr(\"8\"), CharPtr(\"9\"))));\n}\n\n// Tests using Invoke() with a 10-argument function.\nTEST(InvokeTest, FunctionThatTakes10Arguments) {\n  Action<std::string(const char*, const char*, const char*, const char*,\n                     const char*, const char*, const char*, const char*,\n                     const char*, const char*)>\n      a = Invoke(Concat10);\n  EXPECT_EQ(\"1234567890\",\n            a.Perform(std::make_tuple(CharPtr(\"1\"), CharPtr(\"2\"), CharPtr(\"3\"),\n                                      CharPtr(\"4\"), CharPtr(\"5\"), CharPtr(\"6\"),\n                                      CharPtr(\"7\"), CharPtr(\"8\"), CharPtr(\"9\"),\n                                      CharPtr(\"0\"))));\n}\n\n// Tests using Invoke() with functions with parameters declared as Unused.\nTEST(InvokeTest, FunctionWithUnusedParameters) {\n  Action<int(int, int, double, const std::string&)> a1 = Invoke(SumOfFirst2);\n  std::tuple<int, int, double, std::string> dummy =\n      std::make_tuple(10, 2, 5.6, std::string(\"hi\"));\n  EXPECT_EQ(12, a1.Perform(dummy));\n\n  Action<int(int, int, bool, int*)> a2 = Invoke(SumOfFirst2);\n  EXPECT_EQ(\n      23, a2.Perform(std::make_tuple(20, 3, true, static_cast<int*>(nullptr))));\n}\n\n// Tests using Invoke() with methods with parameters declared as Unused.\nTEST(InvokeTest, MethodWithUnusedParameters) {\n  Foo foo;\n  Action<int(std::string, bool, int, int)> a1 = Invoke(&foo, &Foo::SumOfLast2);\n  EXPECT_EQ(12, a1.Perform(std::make_tuple(CharPtr(\"hi\"), true, 10, 2)));\n\n  Action<int(char, double, int, int)> a2 = Invoke(&foo, &Foo::SumOfLast2);\n  EXPECT_EQ(23, a2.Perform(std::make_tuple('a', 2.5, 20, 3)));\n}\n\n// Tests using Invoke() with a functor.\nTEST(InvokeTest, Functor) {\n  Action<long(long, int)> a = Invoke(plus<long>());  // NOLINT\n  EXPECT_EQ(3L, a.Perform(std::make_tuple(1, 2)));\n}\n\n// Tests using Invoke(f) as an action of a compatible type.\nTEST(InvokeTest, FunctionWithCompatibleType) {\n  Action<long(int, short, char, bool)> a = Invoke(SumOf4);  // NOLINT\n  EXPECT_EQ(4321, a.Perform(std::make_tuple(4000, Short(300), Char(20), true)));\n}\n\n// Tests using Invoke() with an object pointer and a method pointer.\n\n// Tests using Invoke() with a nullary method.\nTEST(InvokeMethodTest, Nullary) {\n  Foo foo;\n  Action<int()> a = Invoke(&foo, &Foo::Nullary);  // NOLINT\n  EXPECT_EQ(123, a.Perform(std::make_tuple()));\n}\n\n// Tests using Invoke() with a unary method.\nTEST(InvokeMethodTest, Unary) {\n  Foo foo;\n  Action<short(long)> a = Invoke(&foo, &Foo::Unary);  // NOLINT\n  EXPECT_EQ(4123, a.Perform(std::make_tuple(4000)));\n}\n\n// Tests using Invoke() with a binary method.\nTEST(InvokeMethodTest, Binary) {\n  Foo foo;\n  Action<std::string(const std::string&, char)> a = Invoke(&foo, &Foo::Binary);\n  std::string s(\"Hell\");\n  std::tuple<std::string, char> dummy = std::make_tuple(s, 'o');\n  EXPECT_EQ(\"Hello\", a.Perform(dummy));\n}\n\n// Tests using Invoke() with a ternary method.\nTEST(InvokeMethodTest, Ternary) {\n  Foo foo;\n  Action<int(int, bool, char)> a = Invoke(&foo, &Foo::Ternary);  // NOLINT\n  EXPECT_EQ(1124, a.Perform(std::make_tuple(1000, true, Char(1))));\n}\n\n// Tests using Invoke() with a 4-argument method.\nTEST(InvokeMethodTest, MethodThatTakes4Arguments) {\n  Foo foo;\n  Action<int(int, int, int, int)> a = Invoke(&foo, &Foo::SumOf4);  // NOLINT\n  EXPECT_EQ(1357, a.Perform(std::make_tuple(1000, 200, 30, 4)));\n}\n\n// Tests using Invoke() with a 5-argument method.\nTEST(InvokeMethodTest, MethodThatTakes5Arguments) {\n  Foo foo;\n  Action<int(int, int, int, int, int)> a =\n      Invoke(&foo, &Foo::SumOf5);  // NOLINT\n  EXPECT_EQ(12345, a.Perform(std::make_tuple(10000, 2000, 300, 40, 5)));\n}\n\n// Tests using Invoke() with a 6-argument method.\nTEST(InvokeMethodTest, MethodThatTakes6Arguments) {\n  Foo foo;\n  Action<int(int, int, int, int, int, int)> a =  // NOLINT\n      Invoke(&foo, &Foo::SumOf6);\n  EXPECT_EQ(123456,\n            a.Perform(std::make_tuple(100000, 20000, 3000, 400, 50, 6)));\n}\n\n// Tests using Invoke() with a 7-argument method.\nTEST(InvokeMethodTest, MethodThatTakes7Arguments) {\n  Foo foo;\n  Action<std::string(const char*, const char*, const char*, const char*,\n                     const char*, const char*, const char*)>\n      a = Invoke(&foo, &Foo::Concat7);\n  EXPECT_EQ(\"1234567\",\n            a.Perform(std::make_tuple(CharPtr(\"1\"), CharPtr(\"2\"), CharPtr(\"3\"),\n                                      CharPtr(\"4\"), CharPtr(\"5\"), CharPtr(\"6\"),\n                                      CharPtr(\"7\"))));\n}\n\n// Tests using Invoke() with a 8-argument method.\nTEST(InvokeMethodTest, MethodThatTakes8Arguments) {\n  Foo foo;\n  Action<std::string(const char*, const char*, const char*, const char*,\n                     const char*, const char*, const char*, const char*)>\n      a = Invoke(&foo, &Foo::Concat8);\n  EXPECT_EQ(\"12345678\",\n            a.Perform(std::make_tuple(CharPtr(\"1\"), CharPtr(\"2\"), CharPtr(\"3\"),\n                                      CharPtr(\"4\"), CharPtr(\"5\"), CharPtr(\"6\"),\n                                      CharPtr(\"7\"), CharPtr(\"8\"))));\n}\n\n// Tests using Invoke() with a 9-argument method.\nTEST(InvokeMethodTest, MethodThatTakes9Arguments) {\n  Foo foo;\n  Action<std::string(const char*, const char*, const char*, const char*,\n                     const char*, const char*, const char*, const char*,\n                     const char*)>\n      a = Invoke(&foo, &Foo::Concat9);\n  EXPECT_EQ(\"123456789\", a.Perform(std::make_tuple(\n                             CharPtr(\"1\"), CharPtr(\"2\"), CharPtr(\"3\"),\n                             CharPtr(\"4\"), CharPtr(\"5\"), CharPtr(\"6\"),\n                             CharPtr(\"7\"), CharPtr(\"8\"), CharPtr(\"9\"))));\n}\n\n// Tests using Invoke() with a 10-argument method.\nTEST(InvokeMethodTest, MethodThatTakes10Arguments) {\n  Foo foo;\n  Action<std::string(const char*, const char*, const char*, const char*,\n                     const char*, const char*, const char*, const char*,\n                     const char*, const char*)>\n      a = Invoke(&foo, &Foo::Concat10);\n  EXPECT_EQ(\"1234567890\",\n            a.Perform(std::make_tuple(CharPtr(\"1\"), CharPtr(\"2\"), CharPtr(\"3\"),\n                                      CharPtr(\"4\"), CharPtr(\"5\"), CharPtr(\"6\"),\n                                      CharPtr(\"7\"), CharPtr(\"8\"), CharPtr(\"9\"),\n                                      CharPtr(\"0\"))));\n}\n\n// Tests using Invoke(f) as an action of a compatible type.\nTEST(InvokeMethodTest, MethodWithCompatibleType) {\n  Foo foo;\n  Action<long(int, short, char, bool)> a =  // NOLINT\n      Invoke(&foo, &Foo::SumOf4);\n  EXPECT_EQ(4444, a.Perform(std::make_tuple(4000, Short(300), Char(20), true)));\n}\n\n// Tests using WithoutArgs with an action that takes no argument.\nTEST(WithoutArgsTest, NoArg) {\n  Action<int(int n)> a = WithoutArgs(Invoke(Nullary));  // NOLINT\n  EXPECT_EQ(1, a.Perform(std::make_tuple(2)));\n}\n\n// Tests using WithArg with an action that takes 1 argument.\nTEST(WithArgTest, OneArg) {\n  Action<bool(double x, int n)> b = WithArg<1>(Invoke(Unary));  // NOLINT\n  EXPECT_TRUE(b.Perform(std::make_tuple(1.5, -1)));\n  EXPECT_FALSE(b.Perform(std::make_tuple(1.5, 1)));\n}\n\nTEST(ReturnArgActionTest, WorksForOneArgIntArg0) {\n  const Action<int(int)> a = ReturnArg<0>();\n  EXPECT_EQ(5, a.Perform(std::make_tuple(5)));\n}\n\nTEST(ReturnArgActionTest, WorksForMultiArgBoolArg0) {\n  const Action<bool(bool, bool, bool)> a = ReturnArg<0>();\n  EXPECT_TRUE(a.Perform(std::make_tuple(true, false, false)));\n}\n\nTEST(ReturnArgActionTest, WorksForMultiArgStringArg2) {\n  const Action<std::string(int, int, std::string, int)> a = ReturnArg<2>();\n  EXPECT_EQ(\"seven\", a.Perform(std::make_tuple(5, 6, std::string(\"seven\"), 8)));\n}\n\nTEST(ReturnArgActionTest, WorksForNonConstRefArg0) {\n  const Action<std::string&(std::string&)> a = ReturnArg<0>();\n  std::string s = \"12345\";\n  EXPECT_EQ(&s, &a.Perform(std::forward_as_tuple(s)));\n}\n\nTEST(SaveArgActionTest, WorksForSameType) {\n  int result = 0;\n  const Action<void(int n)> a1 = SaveArg<0>(&result);\n  a1.Perform(std::make_tuple(5));\n  EXPECT_EQ(5, result);\n}\n\nTEST(SaveArgActionTest, WorksForCompatibleType) {\n  int result = 0;\n  const Action<void(bool, char)> a1 = SaveArg<1>(&result);\n  a1.Perform(std::make_tuple(true, 'a'));\n  EXPECT_EQ('a', result);\n}\n\nTEST(SaveArgPointeeActionTest, WorksForSameType) {\n  int result = 0;\n  const int value = 5;\n  const Action<void(const int*)> a1 = SaveArgPointee<0>(&result);\n  a1.Perform(std::make_tuple(&value));\n  EXPECT_EQ(5, result);\n}\n\nTEST(SaveArgPointeeActionTest, WorksForCompatibleType) {\n  int result = 0;\n  char value = 'a';\n  const Action<void(bool, char*)> a1 = SaveArgPointee<1>(&result);\n  a1.Perform(std::make_tuple(true, &value));\n  EXPECT_EQ('a', result);\n}\n\nTEST(SetArgRefereeActionTest, WorksForSameType) {\n  int value = 0;\n  const Action<void(int&)> a1 = SetArgReferee<0>(1);\n  a1.Perform(std::tuple<int&>(value));\n  EXPECT_EQ(1, value);\n}\n\nTEST(SetArgRefereeActionTest, WorksForCompatibleType) {\n  int value = 0;\n  const Action<void(int, int&)> a1 = SetArgReferee<1>('a');\n  a1.Perform(std::tuple<int, int&>(0, value));\n  EXPECT_EQ('a', value);\n}\n\nTEST(SetArgRefereeActionTest, WorksWithExtraArguments) {\n  int value = 0;\n  const Action<void(bool, int, int&, const char*)> a1 = SetArgReferee<2>('a');\n  a1.Perform(std::tuple<bool, int, int&, const char*>(true, 0, value, \"hi\"));\n  EXPECT_EQ('a', value);\n}\n\n// A class that can be used to verify that its destructor is called: it will set\n// the bool provided to the constructor to true when destroyed.\nclass DeletionTester {\n public:\n  explicit DeletionTester(bool* is_deleted) : is_deleted_(is_deleted) {\n    // Make sure the bit is set to false.\n    *is_deleted_ = false;\n  }\n\n  ~DeletionTester() { *is_deleted_ = true; }\n\n private:\n  bool* is_deleted_;\n};\n\nTEST(DeleteArgActionTest, OneArg) {\n  bool is_deleted = false;\n  DeletionTester* t = new DeletionTester(&is_deleted);\n  const Action<void(DeletionTester*)> a1 = DeleteArg<0>();  // NOLINT\n  EXPECT_FALSE(is_deleted);\n  a1.Perform(std::make_tuple(t));\n  EXPECT_TRUE(is_deleted);\n}\n\nTEST(DeleteArgActionTest, TenArgs) {\n  bool is_deleted = false;\n  DeletionTester* t = new DeletionTester(&is_deleted);\n  const Action<void(bool, int, int, const char*, bool, int, int, int, int,\n                    DeletionTester*)>\n      a1 = DeleteArg<9>();\n  EXPECT_FALSE(is_deleted);\n  a1.Perform(std::make_tuple(true, 5, 6, CharPtr(\"hi\"), false, 7, 8, 9, 10, t));\n  EXPECT_TRUE(is_deleted);\n}\n\n#if GTEST_HAS_EXCEPTIONS\n\nTEST(ThrowActionTest, ThrowsGivenExceptionInVoidFunction) {\n  const Action<void(int n)> a = Throw('a');\n  EXPECT_THROW(a.Perform(std::make_tuple(0)), char);\n}\n\nclass MyException {};\n\nTEST(ThrowActionTest, ThrowsGivenExceptionInNonVoidFunction) {\n  const Action<double(char ch)> a = Throw(MyException());\n  EXPECT_THROW(a.Perform(std::make_tuple('0')), MyException);\n}\n\nTEST(ThrowActionTest, ThrowsGivenExceptionInNullaryFunction) {\n  const Action<double()> a = Throw(MyException());\n  EXPECT_THROW(a.Perform(std::make_tuple()), MyException);\n}\n\nclass Object {\n public:\n  virtual ~Object() {}\n  virtual void Func() {}\n};\n\nclass MockObject : public Object {\n public:\n  ~MockObject() override {}\n  MOCK_METHOD(void, Func, (), (override));\n};\n\nTEST(ThrowActionTest, Times0) {\n  EXPECT_NONFATAL_FAILURE(\n      [] {\n        try {\n          MockObject m;\n          ON_CALL(m, Func()).WillByDefault([] { throw \"something\"; });\n          EXPECT_CALL(m, Func()).Times(0);\n          m.Func();\n        } catch (...) {\n          // Exception is caught but Times(0) still triggers a failure.\n        }\n      }(),\n      \"\");\n}\n\n#endif  // GTEST_HAS_EXCEPTIONS\n\n// Tests that SetArrayArgument<N>(first, last) sets the elements of the array\n// pointed to by the N-th (0-based) argument to values in range [first, last).\nTEST(SetArrayArgumentTest, SetsTheNthArray) {\n  using MyFunction = void(bool, int*, char*);\n  int numbers[] = {1, 2, 3};\n  Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers + 3);\n\n  int n[4] = {};\n  int* pn = n;\n  char ch[4] = {};\n  char* pch = ch;\n  a.Perform(std::make_tuple(true, pn, pch));\n  EXPECT_EQ(1, n[0]);\n  EXPECT_EQ(2, n[1]);\n  EXPECT_EQ(3, n[2]);\n  EXPECT_EQ(0, n[3]);\n  EXPECT_EQ('\\0', ch[0]);\n  EXPECT_EQ('\\0', ch[1]);\n  EXPECT_EQ('\\0', ch[2]);\n  EXPECT_EQ('\\0', ch[3]);\n\n  // Tests first and last are iterators.\n  std::string letters = \"abc\";\n  a = SetArrayArgument<2>(letters.begin(), letters.end());\n  std::fill_n(n, 4, 0);\n  std::fill_n(ch, 4, '\\0');\n  a.Perform(std::make_tuple(true, pn, pch));\n  EXPECT_EQ(0, n[0]);\n  EXPECT_EQ(0, n[1]);\n  EXPECT_EQ(0, n[2]);\n  EXPECT_EQ(0, n[3]);\n  EXPECT_EQ('a', ch[0]);\n  EXPECT_EQ('b', ch[1]);\n  EXPECT_EQ('c', ch[2]);\n  EXPECT_EQ('\\0', ch[3]);\n}\n\n// Tests SetArrayArgument<N>(first, last) where first == last.\nTEST(SetArrayArgumentTest, SetsTheNthArrayWithEmptyRange) {\n  using MyFunction = void(bool, int*);\n  int numbers[] = {1, 2, 3};\n  Action<MyFunction> a = SetArrayArgument<1>(numbers, numbers);\n\n  int n[4] = {};\n  int* pn = n;\n  a.Perform(std::make_tuple(true, pn));\n  EXPECT_EQ(0, n[0]);\n  EXPECT_EQ(0, n[1]);\n  EXPECT_EQ(0, n[2]);\n  EXPECT_EQ(0, n[3]);\n}\n\n// Tests SetArrayArgument<N>(first, last) where *first is convertible\n// (but not equal) to the argument type.\nTEST(SetArrayArgumentTest, SetsTheNthArrayWithConvertibleType) {\n  using MyFunction = void(bool, int*);\n  char chars[] = {97, 98, 99};\n  Action<MyFunction> a = SetArrayArgument<1>(chars, chars + 3);\n\n  int codes[4] = {111, 222, 333, 444};\n  int* pcodes = codes;\n  a.Perform(std::make_tuple(true, pcodes));\n  EXPECT_EQ(97, codes[0]);\n  EXPECT_EQ(98, codes[1]);\n  EXPECT_EQ(99, codes[2]);\n  EXPECT_EQ(444, codes[3]);\n}\n\n// Test SetArrayArgument<N>(first, last) with iterator as argument.\nTEST(SetArrayArgumentTest, SetsTheNthArrayWithIteratorArgument) {\n  using MyFunction = void(bool, std::back_insert_iterator<std::string>);\n  std::string letters = \"abc\";\n  Action<MyFunction> a = SetArrayArgument<1>(letters.begin(), letters.end());\n\n  std::string s;\n  a.Perform(std::make_tuple(true, back_inserter(s)));\n  EXPECT_EQ(letters, s);\n}\n\nTEST(ReturnPointeeTest, Works) {\n  int n = 42;\n  const Action<int()> a = ReturnPointee(&n);\n  EXPECT_EQ(42, a.Perform(std::make_tuple()));\n\n  n = 43;\n  EXPECT_EQ(43, a.Perform(std::make_tuple()));\n}\n\n// Tests InvokeArgument<N>(...).\n\n// Tests using InvokeArgument with a nullary function.\nTEST(InvokeArgumentTest, Function0) {\n  Action<int(int, int (*)())> a = InvokeArgument<1>();  // NOLINT\n  EXPECT_EQ(1, a.Perform(std::make_tuple(2, &Nullary)));\n}\n\n// Tests using InvokeArgument with a unary function.\nTEST(InvokeArgumentTest, Functor1) {\n  Action<int(UnaryFunctor)> a = InvokeArgument<0>(true);  // NOLINT\n  EXPECT_EQ(1, a.Perform(std::make_tuple(UnaryFunctor())));\n}\n\n// Tests using InvokeArgument with a 5-ary function.\nTEST(InvokeArgumentTest, Function5) {\n  Action<int(int (*)(int, int, int, int, int))> a =  // NOLINT\n      InvokeArgument<0>(10000, 2000, 300, 40, 5);\n  EXPECT_EQ(12345, a.Perform(std::make_tuple(&SumOf5)));\n}\n\n// Tests using InvokeArgument with a 5-ary functor.\nTEST(InvokeArgumentTest, Functor5) {\n  Action<int(SumOf5Functor)> a =  // NOLINT\n      InvokeArgument<0>(10000, 2000, 300, 40, 5);\n  EXPECT_EQ(12345, a.Perform(std::make_tuple(SumOf5Functor())));\n}\n\n// Tests using InvokeArgument with a 6-ary function.\nTEST(InvokeArgumentTest, Function6) {\n  Action<int(int (*)(int, int, int, int, int, int))> a =  // NOLINT\n      InvokeArgument<0>(100000, 20000, 3000, 400, 50, 6);\n  EXPECT_EQ(123456, a.Perform(std::make_tuple(&SumOf6)));\n}\n\n// Tests using InvokeArgument with a 6-ary functor.\nTEST(InvokeArgumentTest, Functor6) {\n  Action<int(SumOf6Functor)> a =  // NOLINT\n      InvokeArgument<0>(100000, 20000, 3000, 400, 50, 6);\n  EXPECT_EQ(123456, a.Perform(std::make_tuple(SumOf6Functor())));\n}\n\n// Tests using InvokeArgument with a 7-ary function.\nTEST(InvokeArgumentTest, Function7) {\n  Action<std::string(std::string(*)(const char*, const char*, const char*,\n                                    const char*, const char*, const char*,\n                                    const char*))>\n      a = InvokeArgument<0>(\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\");\n  EXPECT_EQ(\"1234567\", a.Perform(std::make_tuple(&Concat7)));\n}\n\n// Tests using InvokeArgument with a 8-ary function.\nTEST(InvokeArgumentTest, Function8) {\n  Action<std::string(std::string(*)(const char*, const char*, const char*,\n                                    const char*, const char*, const char*,\n                                    const char*, const char*))>\n      a = InvokeArgument<0>(\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\");\n  EXPECT_EQ(\"12345678\", a.Perform(std::make_tuple(&Concat8)));\n}\n\n// Tests using InvokeArgument with a 9-ary function.\nTEST(InvokeArgumentTest, Function9) {\n  Action<std::string(std::string(*)(const char*, const char*, const char*,\n                                    const char*, const char*, const char*,\n                                    const char*, const char*, const char*))>\n      a = InvokeArgument<0>(\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\");\n  EXPECT_EQ(\"123456789\", a.Perform(std::make_tuple(&Concat9)));\n}\n\n// Tests using InvokeArgument with a 10-ary function.\nTEST(InvokeArgumentTest, Function10) {\n  Action<std::string(std::string(*)(\n      const char*, const char*, const char*, const char*, const char*,\n      const char*, const char*, const char*, const char*, const char*))>\n      a = InvokeArgument<0>(\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"0\");\n  EXPECT_EQ(\"1234567890\", a.Perform(std::make_tuple(&Concat10)));\n}\n\n// Tests using InvokeArgument with a function that takes a pointer argument.\nTEST(InvokeArgumentTest, ByPointerFunction) {\n  Action<const char*(const char* (*)(const char* input, short n))>  // NOLINT\n      a = InvokeArgument<0>(static_cast<const char*>(\"Hi\"), Short(1));\n  EXPECT_STREQ(\"i\", a.Perform(std::make_tuple(&Binary)));\n}\n\n// Tests using InvokeArgument with a function that takes a const char*\n// by passing it a C-string literal.\nTEST(InvokeArgumentTest, FunctionWithCStringLiteral) {\n  Action<const char*(const char* (*)(const char* input, short n))>  // NOLINT\n      a = InvokeArgument<0>(\"Hi\", Short(1));\n  EXPECT_STREQ(\"i\", a.Perform(std::make_tuple(&Binary)));\n}\n\n// Tests using InvokeArgument with a function that takes a const reference.\nTEST(InvokeArgumentTest, ByConstReferenceFunction) {\n  Action<bool(bool (*function)(const std::string& s))> a =  // NOLINT\n      InvokeArgument<0>(std::string(\"Hi\"));\n  // When action 'a' is constructed, it makes a copy of the temporary\n  // string object passed to it, so it's OK to use 'a' later, when the\n  // temporary object has already died.\n  EXPECT_TRUE(a.Perform(std::make_tuple(&ByConstRef)));\n}\n\n// Tests using InvokeArgument with ByRef() and a function that takes a\n// const reference.\nTEST(InvokeArgumentTest, ByExplicitConstReferenceFunction) {\n  Action<bool(bool (*)(const double& x))> a =  // NOLINT\n      InvokeArgument<0>(ByRef(g_double));\n  // The above line calls ByRef() on a const value.\n  EXPECT_TRUE(a.Perform(std::make_tuple(&ReferencesGlobalDouble)));\n\n  double x = 0;\n  a = InvokeArgument<0>(ByRef(x));  // This calls ByRef() on a non-const.\n  EXPECT_FALSE(a.Perform(std::make_tuple(&ReferencesGlobalDouble)));\n}\n\n// Tests DoAll(a1, a2).\nTEST(DoAllTest, TwoActions) {\n  int n = 0;\n  Action<int(int*)> a = DoAll(SetArgPointee<0>(1),  // NOLINT\n                              Return(2));\n  EXPECT_EQ(2, a.Perform(std::make_tuple(&n)));\n  EXPECT_EQ(1, n);\n}\n\n// Tests DoAll(a1, a2, a3).\nTEST(DoAllTest, ThreeActions) {\n  int m = 0, n = 0;\n  Action<int(int*, int*)> a = DoAll(SetArgPointee<0>(1),  // NOLINT\n                                    SetArgPointee<1>(2), Return(3));\n  EXPECT_EQ(3, a.Perform(std::make_tuple(&m, &n)));\n  EXPECT_EQ(1, m);\n  EXPECT_EQ(2, n);\n}\n\n// Tests DoAll(a1, a2, a3, a4).\nTEST(DoAllTest, FourActions) {\n  int m = 0, n = 0;\n  char ch = '\\0';\n  Action<int(int*, int*, char*)> a =  // NOLINT\n      DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'),\n            Return(3));\n  EXPECT_EQ(3, a.Perform(std::make_tuple(&m, &n, &ch)));\n  EXPECT_EQ(1, m);\n  EXPECT_EQ(2, n);\n  EXPECT_EQ('a', ch);\n}\n\n// Tests DoAll(a1, a2, a3, a4, a5).\nTEST(DoAllTest, FiveActions) {\n  int m = 0, n = 0;\n  char a = '\\0', b = '\\0';\n  Action<int(int*, int*, char*, char*)> action =  // NOLINT\n      DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'),\n            SetArgPointee<3>('b'), Return(3));\n  EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b)));\n  EXPECT_EQ(1, m);\n  EXPECT_EQ(2, n);\n  EXPECT_EQ('a', a);\n  EXPECT_EQ('b', b);\n}\n\n// Tests DoAll(a1, a2, ..., a6).\nTEST(DoAllTest, SixActions) {\n  int m = 0, n = 0;\n  char a = '\\0', b = '\\0', c = '\\0';\n  Action<int(int*, int*, char*, char*, char*)> action =  // NOLINT\n      DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'),\n            SetArgPointee<3>('b'), SetArgPointee<4>('c'), Return(3));\n  EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c)));\n  EXPECT_EQ(1, m);\n  EXPECT_EQ(2, n);\n  EXPECT_EQ('a', a);\n  EXPECT_EQ('b', b);\n  EXPECT_EQ('c', c);\n}\n\n// Tests DoAll(a1, a2, ..., a7).\nTEST(DoAllTest, SevenActions) {\n  int m = 0, n = 0;\n  char a = '\\0', b = '\\0', c = '\\0', d = '\\0';\n  Action<int(int*, int*, char*, char*, char*, char*)> action =  // NOLINT\n      DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'),\n            SetArgPointee<3>('b'), SetArgPointee<4>('c'), SetArgPointee<5>('d'),\n            Return(3));\n  EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d)));\n  EXPECT_EQ(1, m);\n  EXPECT_EQ(2, n);\n  EXPECT_EQ('a', a);\n  EXPECT_EQ('b', b);\n  EXPECT_EQ('c', c);\n  EXPECT_EQ('d', d);\n}\n\n// Tests DoAll(a1, a2, ..., a8).\nTEST(DoAllTest, EightActions) {\n  int m = 0, n = 0;\n  char a = '\\0', b = '\\0', c = '\\0', d = '\\0', e = '\\0';\n  Action<int(int*, int*, char*, char*, char*, char*,  // NOLINT\n             char*)>\n      action =\n          DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'),\n                SetArgPointee<3>('b'), SetArgPointee<4>('c'),\n                SetArgPointee<5>('d'), SetArgPointee<6>('e'), Return(3));\n  EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e)));\n  EXPECT_EQ(1, m);\n  EXPECT_EQ(2, n);\n  EXPECT_EQ('a', a);\n  EXPECT_EQ('b', b);\n  EXPECT_EQ('c', c);\n  EXPECT_EQ('d', d);\n  EXPECT_EQ('e', e);\n}\n\n// Tests DoAll(a1, a2, ..., a9).\nTEST(DoAllTest, NineActions) {\n  int m = 0, n = 0;\n  char a = '\\0', b = '\\0', c = '\\0', d = '\\0', e = '\\0', f = '\\0';\n  Action<int(int*, int*, char*, char*, char*, char*,  // NOLINT\n             char*, char*)>\n      action = DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2),\n                     SetArgPointee<2>('a'), SetArgPointee<3>('b'),\n                     SetArgPointee<4>('c'), SetArgPointee<5>('d'),\n                     SetArgPointee<6>('e'), SetArgPointee<7>('f'), Return(3));\n  EXPECT_EQ(3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e, &f)));\n  EXPECT_EQ(1, m);\n  EXPECT_EQ(2, n);\n  EXPECT_EQ('a', a);\n  EXPECT_EQ('b', b);\n  EXPECT_EQ('c', c);\n  EXPECT_EQ('d', d);\n  EXPECT_EQ('e', e);\n  EXPECT_EQ('f', f);\n}\n\n// Tests DoAll(a1, a2, ..., a10).\nTEST(DoAllTest, TenActions) {\n  int m = 0, n = 0;\n  char a = '\\0', b = '\\0', c = '\\0', d = '\\0';\n  char e = '\\0', f = '\\0', g = '\\0';\n  Action<int(int*, int*, char*, char*, char*, char*,  // NOLINT\n             char*, char*, char*)>\n      action =\n          DoAll(SetArgPointee<0>(1), SetArgPointee<1>(2), SetArgPointee<2>('a'),\n                SetArgPointee<3>('b'), SetArgPointee<4>('c'),\n                SetArgPointee<5>('d'), SetArgPointee<6>('e'),\n                SetArgPointee<7>('f'), SetArgPointee<8>('g'), Return(3));\n  EXPECT_EQ(\n      3, action.Perform(std::make_tuple(&m, &n, &a, &b, &c, &d, &e, &f, &g)));\n  EXPECT_EQ(1, m);\n  EXPECT_EQ(2, n);\n  EXPECT_EQ('a', a);\n  EXPECT_EQ('b', b);\n  EXPECT_EQ('c', c);\n  EXPECT_EQ('d', d);\n  EXPECT_EQ('e', e);\n  EXPECT_EQ('f', f);\n  EXPECT_EQ('g', g);\n}\n\nTEST(DoAllTest, NoArgs) {\n  bool ran_first = false;\n  Action<bool()> a =\n      DoAll([&] { ran_first = true; }, [&] { return ran_first; });\n  EXPECT_TRUE(a.Perform({}));\n}\n\nTEST(DoAllTest, MoveOnlyArgs) {\n  bool ran_first = false;\n  Action<int(std::unique_ptr<int>)> a =\n      DoAll(InvokeWithoutArgs([&] { ran_first = true; }),\n            [](std::unique_ptr<int> p) { return *p; });\n  EXPECT_EQ(7, a.Perform(std::make_tuple(std::unique_ptr<int>(new int(7)))));\n  EXPECT_TRUE(ran_first);\n}\n\nTEST(DoAllTest, ImplicitlyConvertsActionArguments) {\n  bool ran_first = false;\n  // Action<void(std::vector<int>)> isn't an\n  // Action<void(const std::vector<int>&) but can be converted.\n  Action<void(std::vector<int>)> first = [&] { ran_first = true; };\n  Action<int(std::vector<int>)> a =\n      DoAll(first, [](std::vector<int> arg) { return arg.front(); });\n  EXPECT_EQ(7, a.Perform(std::make_tuple(std::vector<int>{7})));\n  EXPECT_TRUE(ran_first);\n}\n\n// The ACTION*() macros trigger warning C4100 (unreferenced formal\n// parameter) in MSVC with -W4.  Unfortunately they cannot be fixed in\n// the macro definition, as the warnings are generated when the macro\n// is expanded and macro expansion cannot contain #pragma.  Therefore\n// we suppress them here.\n// Also suppress C4503 decorated name length exceeded, name was truncated\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 4100)\n#pragma warning(disable : 4503)\n#endif\n// Tests the ACTION*() macro family.\n\n// Tests that ACTION() can define an action that doesn't reference the\n// mock function arguments.\nACTION(Return5) { return 5; }\n\nTEST(ActionMacroTest, WorksWhenNotReferencingArguments) {\n  Action<double()> a1 = Return5();\n  EXPECT_DOUBLE_EQ(5, a1.Perform(std::make_tuple()));\n\n  Action<int(double, bool)> a2 = Return5();\n  EXPECT_EQ(5, a2.Perform(std::make_tuple(1, true)));\n}\n\n// Tests that ACTION() can define an action that returns void.\nACTION(IncrementArg1) { (*arg1)++; }\n\nTEST(ActionMacroTest, WorksWhenReturningVoid) {\n  Action<void(int, int*)> a1 = IncrementArg1();\n  int n = 0;\n  a1.Perform(std::make_tuple(5, &n));\n  EXPECT_EQ(1, n);\n}\n\n// Tests that the body of ACTION() can reference the type of the\n// argument.\nACTION(IncrementArg2) {\n  StaticAssertTypeEq<int*, arg2_type>();\n  arg2_type temp = arg2;\n  (*temp)++;\n}\n\nTEST(ActionMacroTest, CanReferenceArgumentType) {\n  Action<void(int, bool, int*)> a1 = IncrementArg2();\n  int n = 0;\n  a1.Perform(std::make_tuple(5, false, &n));\n  EXPECT_EQ(1, n);\n}\n\n// Tests that the body of ACTION() can reference the argument tuple\n// via args_type and args.\nACTION(Sum2) {\n  StaticAssertTypeEq<std::tuple<int, char, int*>, args_type>();\n  args_type args_copy = args;\n  return std::get<0>(args_copy) + std::get<1>(args_copy);\n}\n\nTEST(ActionMacroTest, CanReferenceArgumentTuple) {\n  Action<int(int, char, int*)> a1 = Sum2();\n  int dummy = 0;\n  EXPECT_EQ(11, a1.Perform(std::make_tuple(5, Char(6), &dummy)));\n}\n\nnamespace {\n\n// Tests that the body of ACTION() can reference the mock function\n// type.\nint Dummy(bool flag) { return flag ? 1 : 0; }\n\n}  // namespace\n\nACTION(InvokeDummy) {\n  StaticAssertTypeEq<int(bool), function_type>();\n  function_type* fp = &Dummy;\n  return (*fp)(true);\n}\n\nTEST(ActionMacroTest, CanReferenceMockFunctionType) {\n  Action<int(bool)> a1 = InvokeDummy();\n  EXPECT_EQ(1, a1.Perform(std::make_tuple(true)));\n  EXPECT_EQ(1, a1.Perform(std::make_tuple(false)));\n}\n\n// Tests that the body of ACTION() can reference the mock function's\n// return type.\nACTION(InvokeDummy2) {\n  StaticAssertTypeEq<int, return_type>();\n  return_type result = Dummy(true);\n  return result;\n}\n\nTEST(ActionMacroTest, CanReferenceMockFunctionReturnType) {\n  Action<int(bool)> a1 = InvokeDummy2();\n  EXPECT_EQ(1, a1.Perform(std::make_tuple(true)));\n  EXPECT_EQ(1, a1.Perform(std::make_tuple(false)));\n}\n\n// Tests that ACTION() works for arguments passed by const reference.\nACTION(ReturnAddrOfConstBoolReferenceArg) {\n  StaticAssertTypeEq<const bool&, arg1_type>();\n  return &arg1;\n}\n\nTEST(ActionMacroTest, WorksForConstReferenceArg) {\n  Action<const bool*(int, const bool&)> a = ReturnAddrOfConstBoolReferenceArg();\n  const bool b = false;\n  EXPECT_EQ(&b, a.Perform(std::tuple<int, const bool&>(0, b)));\n}\n\n// Tests that ACTION() works for arguments passed by non-const reference.\nACTION(ReturnAddrOfIntReferenceArg) {\n  StaticAssertTypeEq<int&, arg0_type>();\n  return &arg0;\n}\n\nTEST(ActionMacroTest, WorksForNonConstReferenceArg) {\n  Action<int*(int&, bool, int)> a = ReturnAddrOfIntReferenceArg();\n  int n = 0;\n  EXPECT_EQ(&n, a.Perform(std::tuple<int&, bool, int>(n, true, 1)));\n}\n\n// Tests that ACTION() can be used in a namespace.\nnamespace action_test {\nACTION(Sum) { return arg0 + arg1; }\n}  // namespace action_test\n\nTEST(ActionMacroTest, WorksInNamespace) {\n  Action<int(int, int)> a1 = action_test::Sum();\n  EXPECT_EQ(3, a1.Perform(std::make_tuple(1, 2)));\n}\n\n// Tests that the same ACTION definition works for mock functions with\n// different argument numbers.\nACTION(PlusTwo) { return arg0 + 2; }\n\nTEST(ActionMacroTest, WorksForDifferentArgumentNumbers) {\n  Action<int(int)> a1 = PlusTwo();\n  EXPECT_EQ(4, a1.Perform(std::make_tuple(2)));\n\n  Action<double(float, void*)> a2 = PlusTwo();\n  int dummy;\n  EXPECT_DOUBLE_EQ(6, a2.Perform(std::make_tuple(4.0f, &dummy)));\n}\n\n// Tests that ACTION_P can define a parameterized action.\nACTION_P(Plus, n) { return arg0 + n; }\n\nTEST(ActionPMacroTest, DefinesParameterizedAction) {\n  Action<int(int m, bool t)> a1 = Plus(9);\n  EXPECT_EQ(10, a1.Perform(std::make_tuple(1, true)));\n}\n\n// Tests that the body of ACTION_P can reference the argument types\n// and the parameter type.\nACTION_P(TypedPlus, n) {\n  arg0_type t1 = arg0;\n  n_type t2 = n;\n  return t1 + t2;\n}\n\nTEST(ActionPMacroTest, CanReferenceArgumentAndParameterTypes) {\n  Action<int(char m, bool t)> a1 = TypedPlus(9);\n  EXPECT_EQ(10, a1.Perform(std::make_tuple(Char(1), true)));\n}\n\n// Tests that a parameterized action can be used in any mock function\n// whose type is compatible.\nTEST(ActionPMacroTest, WorksInCompatibleMockFunction) {\n  Action<std::string(const std::string& s)> a1 = Plus(\"tail\");\n  const std::string re = \"re\";\n  std::tuple<const std::string> dummy = std::make_tuple(re);\n  EXPECT_EQ(\"retail\", a1.Perform(dummy));\n}\n\n// Tests that we can use ACTION*() to define actions overloaded on the\n// number of parameters.\n\nACTION(OverloadedAction) { return arg0 ? arg1 : \"hello\"; }\n\nACTION_P(OverloadedAction, default_value) {\n  return arg0 ? arg1 : default_value;\n}\n\nACTION_P2(OverloadedAction, true_value, false_value) {\n  return arg0 ? true_value : false_value;\n}\n\nTEST(ActionMacroTest, CanDefineOverloadedActions) {\n  using MyAction = Action<const char*(bool, const char*)>;\n\n  const MyAction a1 = OverloadedAction();\n  EXPECT_STREQ(\"hello\", a1.Perform(std::make_tuple(false, CharPtr(\"world\"))));\n  EXPECT_STREQ(\"world\", a1.Perform(std::make_tuple(true, CharPtr(\"world\"))));\n\n  const MyAction a2 = OverloadedAction(\"hi\");\n  EXPECT_STREQ(\"hi\", a2.Perform(std::make_tuple(false, CharPtr(\"world\"))));\n  EXPECT_STREQ(\"world\", a2.Perform(std::make_tuple(true, CharPtr(\"world\"))));\n\n  const MyAction a3 = OverloadedAction(\"hi\", \"you\");\n  EXPECT_STREQ(\"hi\", a3.Perform(std::make_tuple(true, CharPtr(\"world\"))));\n  EXPECT_STREQ(\"you\", a3.Perform(std::make_tuple(false, CharPtr(\"world\"))));\n}\n\n// Tests ACTION_Pn where n >= 3.\n\nACTION_P3(Plus, m, n, k) { return arg0 + m + n + k; }\n\nTEST(ActionPnMacroTest, WorksFor3Parameters) {\n  Action<double(int m, bool t)> a1 = Plus(100, 20, 3.4);\n  EXPECT_DOUBLE_EQ(3123.4, a1.Perform(std::make_tuple(3000, true)));\n\n  Action<std::string(const std::string& s)> a2 = Plus(\"tail\", \"-\", \">\");\n  const std::string re = \"re\";\n  std::tuple<const std::string> dummy = std::make_tuple(re);\n  EXPECT_EQ(\"retail->\", a2.Perform(dummy));\n}\n\nACTION_P4(Plus, p0, p1, p2, p3) { return arg0 + p0 + p1 + p2 + p3; }\n\nTEST(ActionPnMacroTest, WorksFor4Parameters) {\n  Action<int(int)> a1 = Plus(1, 2, 3, 4);\n  EXPECT_EQ(10 + 1 + 2 + 3 + 4, a1.Perform(std::make_tuple(10)));\n}\n\nACTION_P5(Plus, p0, p1, p2, p3, p4) { return arg0 + p0 + p1 + p2 + p3 + p4; }\n\nTEST(ActionPnMacroTest, WorksFor5Parameters) {\n  Action<int(int)> a1 = Plus(1, 2, 3, 4, 5);\n  EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5, a1.Perform(std::make_tuple(10)));\n}\n\nACTION_P6(Plus, p0, p1, p2, p3, p4, p5) {\n  return arg0 + p0 + p1 + p2 + p3 + p4 + p5;\n}\n\nTEST(ActionPnMacroTest, WorksFor6Parameters) {\n  Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6);\n  EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6, a1.Perform(std::make_tuple(10)));\n}\n\nACTION_P7(Plus, p0, p1, p2, p3, p4, p5, p6) {\n  return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6;\n}\n\nTEST(ActionPnMacroTest, WorksFor7Parameters) {\n  Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7);\n  EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7, a1.Perform(std::make_tuple(10)));\n}\n\nACTION_P8(Plus, p0, p1, p2, p3, p4, p5, p6, p7) {\n  return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7;\n}\n\nTEST(ActionPnMacroTest, WorksFor8Parameters) {\n  Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8);\n  EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8,\n            a1.Perform(std::make_tuple(10)));\n}\n\nACTION_P9(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8) {\n  return arg0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8;\n}\n\nTEST(ActionPnMacroTest, WorksFor9Parameters) {\n  Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9);\n  EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9,\n            a1.Perform(std::make_tuple(10)));\n}\n\nACTION_P10(Plus, p0, p1, p2, p3, p4, p5, p6, p7, p8, last_param) {\n  arg0_type t0 = arg0;\n  last_param_type t9 = last_param;\n  return t0 + p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + t9;\n}\n\nTEST(ActionPnMacroTest, WorksFor10Parameters) {\n  Action<int(int)> a1 = Plus(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);\n  EXPECT_EQ(10 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10,\n            a1.Perform(std::make_tuple(10)));\n}\n\n// Tests that the action body can promote the parameter types.\n\nACTION_P2(PadArgument, prefix, suffix) {\n  // The following lines promote the two parameters to desired types.\n  std::string prefix_str(prefix);\n  char suffix_char = static_cast<char>(suffix);\n  return prefix_str + arg0 + suffix_char;\n}\n\nTEST(ActionPnMacroTest, SimpleTypePromotion) {\n  Action<std::string(const char*)> no_promo =\n      PadArgument(std::string(\"foo\"), 'r');\n  Action<std::string(const char*)> promo =\n      PadArgument(\"foo\", static_cast<int>('r'));\n  EXPECT_EQ(\"foobar\", no_promo.Perform(std::make_tuple(CharPtr(\"ba\"))));\n  EXPECT_EQ(\"foobar\", promo.Perform(std::make_tuple(CharPtr(\"ba\"))));\n}\n\n// Tests that we can partially restrict parameter types using a\n// straight-forward pattern.\n\n// Defines a generic action that doesn't restrict the types of its\n// parameters.\nACTION_P3(ConcatImpl, a, b, c) {\n  std::stringstream ss;\n  ss << a << b << c;\n  return ss.str();\n}\n\n// Next, we try to restrict that either the first parameter is a\n// string, or the second parameter is an int.\n\n// Defines a partially specialized wrapper that restricts the first\n// parameter to std::string.\ntemplate <typename T1, typename T2>\n// ConcatImplActionP3 is the class template ACTION_P3 uses to\n// implement ConcatImpl.  We shouldn't change the name as this\n// pattern requires the user to use it directly.\nConcatImplActionP3<std::string, T1, T2> Concat(const std::string& a, T1 b,\n                                               T2 c) {\n  GTEST_INTENTIONAL_CONST_COND_PUSH_()\n  if (true) {\n    GTEST_INTENTIONAL_CONST_COND_POP_()\n    // This branch verifies that ConcatImpl() can be invoked without\n    // explicit template arguments.\n    return ConcatImpl(a, b, c);\n  } else {\n    // This branch verifies that ConcatImpl() can also be invoked with\n    // explicit template arguments.  It doesn't really need to be\n    // executed as this is a compile-time verification.\n    return ConcatImpl<std::string, T1, T2>(a, b, c);\n  }\n}\n\n// Defines another partially specialized wrapper that restricts the\n// second parameter to int.\ntemplate <typename T1, typename T2>\nConcatImplActionP3<T1, int, T2> Concat(T1 a, int b, T2 c) {\n  return ConcatImpl(a, b, c);\n}\n\nTEST(ActionPnMacroTest, CanPartiallyRestrictParameterTypes) {\n  Action<const std::string()> a1 = Concat(\"Hello\", \"1\", 2);\n  EXPECT_EQ(\"Hello12\", a1.Perform(std::make_tuple()));\n\n  a1 = Concat(1, 2, 3);\n  EXPECT_EQ(\"123\", a1.Perform(std::make_tuple()));\n}\n\n// Verifies the type of an ACTION*.\n\nACTION(DoFoo) {}\nACTION_P(DoFoo, p) {}\nACTION_P2(DoFoo, p0, p1) {}\n\nTEST(ActionPnMacroTest, TypesAreCorrect) {\n  // DoFoo() must be assignable to a DoFooAction variable.\n  DoFooAction a0 = DoFoo();\n\n  // DoFoo(1) must be assignable to a DoFooActionP variable.\n  DoFooActionP<int> a1 = DoFoo(1);\n\n  // DoFoo(p1, ..., pk) must be assignable to a DoFooActionPk\n  // variable, and so on.\n  DoFooActionP2<int, char> a2 = DoFoo(1, '2');\n  PlusActionP3<int, int, char> a3 = Plus(1, 2, '3');\n  PlusActionP4<int, int, int, char> a4 = Plus(1, 2, 3, '4');\n  PlusActionP5<int, int, int, int, char> a5 = Plus(1, 2, 3, 4, '5');\n  PlusActionP6<int, int, int, int, int, char> a6 = Plus(1, 2, 3, 4, 5, '6');\n  PlusActionP7<int, int, int, int, int, int, char> a7 =\n      Plus(1, 2, 3, 4, 5, 6, '7');\n  PlusActionP8<int, int, int, int, int, int, int, char> a8 =\n      Plus(1, 2, 3, 4, 5, 6, 7, '8');\n  PlusActionP9<int, int, int, int, int, int, int, int, char> a9 =\n      Plus(1, 2, 3, 4, 5, 6, 7, 8, '9');\n  PlusActionP10<int, int, int, int, int, int, int, int, int, char> a10 =\n      Plus(1, 2, 3, 4, 5, 6, 7, 8, 9, '0');\n\n  // Avoid \"unused variable\" warnings.\n  (void)a0;\n  (void)a1;\n  (void)a2;\n  (void)a3;\n  (void)a4;\n  (void)a5;\n  (void)a6;\n  (void)a7;\n  (void)a8;\n  (void)a9;\n  (void)a10;\n}\n\n// Tests that an ACTION_P*() action can be explicitly instantiated\n// with reference-typed parameters.\n\nACTION_P(Plus1, x) { return x; }\nACTION_P2(Plus2, x, y) { return x + y; }\nACTION_P3(Plus3, x, y, z) { return x + y + z; }\nACTION_P10(Plus10, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {\n  return a0 + a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9;\n}\n\nTEST(ActionPnMacroTest, CanExplicitlyInstantiateWithReferenceTypes) {\n  int x = 1, y = 2, z = 3;\n  const std::tuple<> empty = std::make_tuple();\n\n  Action<int()> a = Plus1<int&>(x);\n  EXPECT_EQ(1, a.Perform(empty));\n\n  a = Plus2<const int&, int&>(x, y);\n  EXPECT_EQ(3, a.Perform(empty));\n\n  a = Plus3<int&, const int&, int&>(x, y, z);\n  EXPECT_EQ(6, a.Perform(empty));\n\n  int n[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n  a = Plus10<const int&, int&, const int&, int&, const int&, int&, const int&,\n             int&, const int&, int&>(n[0], n[1], n[2], n[3], n[4], n[5], n[6],\n                                     n[7], n[8], n[9]);\n  EXPECT_EQ(55, a.Perform(empty));\n}\n\nclass TenArgConstructorClass {\n public:\n  TenArgConstructorClass(int a1, int a2, int a3, int a4, int a5, int a6, int a7,\n                         int a8, int a9, int a10)\n      : value_(a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10) {}\n  int value_;\n};\n\n// Tests that ACTION_TEMPLATE works when there is no value parameter.\nACTION_TEMPLATE(CreateNew, HAS_1_TEMPLATE_PARAMS(typename, T),\n                AND_0_VALUE_PARAMS()) {\n  return new T;\n}\n\nTEST(ActionTemplateTest, WorksWithoutValueParam) {\n  const Action<int*()> a = CreateNew<int>();\n  int* p = a.Perform(std::make_tuple());\n  delete p;\n}\n\n// Tests that ACTION_TEMPLATE works when there are value parameters.\nACTION_TEMPLATE(CreateNew, HAS_1_TEMPLATE_PARAMS(typename, T),\n                AND_1_VALUE_PARAMS(a0)) {\n  return new T(a0);\n}\n\nTEST(ActionTemplateTest, WorksWithValueParams) {\n  const Action<int*()> a = CreateNew<int>(42);\n  int* p = a.Perform(std::make_tuple());\n  EXPECT_EQ(42, *p);\n  delete p;\n}\n\n// Tests that ACTION_TEMPLATE works for integral template parameters.\nACTION_TEMPLATE(MyDeleteArg, HAS_1_TEMPLATE_PARAMS(int, k),\n                AND_0_VALUE_PARAMS()) {\n  delete std::get<k>(args);\n}\n\n// Resets a bool variable in the destructor.\nclass BoolResetter {\n public:\n  explicit BoolResetter(bool* value) : value_(value) {}\n  ~BoolResetter() { *value_ = false; }\n\n private:\n  bool* value_;\n};\n\nTEST(ActionTemplateTest, WorksForIntegralTemplateParams) {\n  const Action<void(int*, BoolResetter*)> a = MyDeleteArg<1>();\n  int n = 0;\n  bool b = true;\n  auto* resetter = new BoolResetter(&b);\n  a.Perform(std::make_tuple(&n, resetter));\n  EXPECT_FALSE(b);  // Verifies that resetter is deleted.\n}\n\n// Tests that ACTION_TEMPLATES works for template template parameters.\nACTION_TEMPLATE(ReturnSmartPointer,\n                HAS_1_TEMPLATE_PARAMS(template <typename Pointee> class,\n                                      Pointer),\n                AND_1_VALUE_PARAMS(pointee)) {\n  return Pointer<pointee_type>(new pointee_type(pointee));\n}\n\nTEST(ActionTemplateTest, WorksForTemplateTemplateParameters) {\n  const Action<std::shared_ptr<int>()> a =\n      ReturnSmartPointer<std::shared_ptr>(42);\n  std::shared_ptr<int> p = a.Perform(std::make_tuple());\n  EXPECT_EQ(42, *p);\n}\n\n// Tests that ACTION_TEMPLATE works for 10 template parameters.\ntemplate <typename T1, typename T2, typename T3, int k4, bool k5,\n          unsigned int k6, typename T7, typename T8, typename T9>\nstruct GiantTemplate {\n public:\n  explicit GiantTemplate(int a_value) : value(a_value) {}\n  int value;\n};\n\nACTION_TEMPLATE(ReturnGiant,\n                HAS_10_TEMPLATE_PARAMS(typename, T1, typename, T2, typename, T3,\n                                       int, k4, bool, k5, unsigned int, k6,\n                                       class, T7, class, T8, class, T9,\n                                       template <typename T> class, T10),\n                AND_1_VALUE_PARAMS(value)) {\n  return GiantTemplate<T10<T1>, T2, T3, k4, k5, k6, T7, T8, T9>(value);\n}\n\nTEST(ActionTemplateTest, WorksFor10TemplateParameters) {\n  using Giant = GiantTemplate<std::shared_ptr<int>, bool, double, 5, true, 6,\n                              char, unsigned, int>;\n  const Action<Giant()> a = ReturnGiant<int, bool, double, 5, true, 6, char,\n                                        unsigned, int, std::shared_ptr>(42);\n  Giant giant = a.Perform(std::make_tuple());\n  EXPECT_EQ(42, giant.value);\n}\n\n// Tests that ACTION_TEMPLATE works for 10 value parameters.\nACTION_TEMPLATE(ReturnSum, HAS_1_TEMPLATE_PARAMS(typename, Number),\n                AND_10_VALUE_PARAMS(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10)) {\n  return static_cast<Number>(v1) + v2 + v3 + v4 + v5 + v6 + v7 + v8 + v9 + v10;\n}\n\nTEST(ActionTemplateTest, WorksFor10ValueParameters) {\n  const Action<int()> a = ReturnSum<int>(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);\n  EXPECT_EQ(55, a.Perform(std::make_tuple()));\n}\n\n// Tests that ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded\n// on the number of value parameters.\n\nACTION(ReturnSum) { return 0; }\n\nACTION_P(ReturnSum, x) { return x; }\n\nACTION_TEMPLATE(ReturnSum, HAS_1_TEMPLATE_PARAMS(typename, Number),\n                AND_2_VALUE_PARAMS(v1, v2)) {\n  return static_cast<Number>(v1) + v2;\n}\n\nACTION_TEMPLATE(ReturnSum, HAS_1_TEMPLATE_PARAMS(typename, Number),\n                AND_3_VALUE_PARAMS(v1, v2, v3)) {\n  return static_cast<Number>(v1) + v2 + v3;\n}\n\nACTION_TEMPLATE(ReturnSum, HAS_2_TEMPLATE_PARAMS(typename, Number, int, k),\n                AND_4_VALUE_PARAMS(v1, v2, v3, v4)) {\n  return static_cast<Number>(v1) + v2 + v3 + v4 + k;\n}\n\nTEST(ActionTemplateTest, CanBeOverloadedOnNumberOfValueParameters) {\n  const Action<int()> a0 = ReturnSum();\n  const Action<int()> a1 = ReturnSum(1);\n  const Action<int()> a2 = ReturnSum<int>(1, 2);\n  const Action<int()> a3 = ReturnSum<int>(1, 2, 3);\n  const Action<int()> a4 = ReturnSum<int, 10000>(2000, 300, 40, 5);\n  EXPECT_EQ(0, a0.Perform(std::make_tuple()));\n  EXPECT_EQ(1, a1.Perform(std::make_tuple()));\n  EXPECT_EQ(3, a2.Perform(std::make_tuple()));\n  EXPECT_EQ(6, a3.Perform(std::make_tuple()));\n  EXPECT_EQ(12345, a4.Perform(std::make_tuple()));\n}\n\n}  // namespace gmock_more_actions_test\n}  // namespace testing\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock-nice-strict_test.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"gmock/gmock-nice-strict.h\"\n\n#include <string>\n#include <utility>\n\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest-spi.h\"\n#include \"gtest/gtest.h\"\n\n// This must not be defined inside the ::testing namespace, or it will\n// clash with ::testing::Mock.\nclass Mock {\n public:\n  Mock() {}\n\n  MOCK_METHOD0(DoThis, void());\n\n private:\n  Mock(const Mock&) = delete;\n  Mock& operator=(const Mock&) = delete;\n};\n\nnamespace testing {\nnamespace gmock_nice_strict_test {\n\nusing testing::HasSubstr;\nusing testing::NaggyMock;\nusing testing::NiceMock;\nusing testing::StrictMock;\n\n#if GTEST_HAS_STREAM_REDIRECTION\nusing testing::internal::CaptureStdout;\nusing testing::internal::GetCapturedStdout;\n#endif\n\n// Class without default constructor.\nclass NotDefaultConstructible {\n public:\n  explicit NotDefaultConstructible(int) {}\n};\n\nclass CallsMockMethodInDestructor {\n public:\n  ~CallsMockMethodInDestructor() { OnDestroy(); }\n  MOCK_METHOD(void, OnDestroy, ());\n};\n\n// Defines some mock classes needed by the tests.\n\nclass Foo {\n public:\n  virtual ~Foo() {}\n\n  virtual void DoThis() = 0;\n  virtual int DoThat(bool flag) = 0;\n};\n\nclass MockFoo : public Foo {\n public:\n  MockFoo() {}\n  void Delete() { delete this; }\n\n  MOCK_METHOD0(DoThis, void());\n  MOCK_METHOD1(DoThat, int(bool flag));\n  MOCK_METHOD0(ReturnNonDefaultConstructible, NotDefaultConstructible());\n\n private:\n  MockFoo(const MockFoo&) = delete;\n  MockFoo& operator=(const MockFoo&) = delete;\n};\n\nclass MockBar {\n public:\n  explicit MockBar(const std::string& s) : str_(s) {}\n\n  MockBar(char a1, char a2, std::string a3, std::string a4, int a5, int a6,\n          const std::string& a7, const std::string& a8, bool a9, bool a10) {\n    str_ = std::string() + a1 + a2 + a3 + a4 + static_cast<char>(a5) +\n           static_cast<char>(a6) + a7 + a8 + (a9 ? 'T' : 'F') +\n           (a10 ? 'T' : 'F');\n  }\n\n  virtual ~MockBar() {}\n\n  const std::string& str() const { return str_; }\n\n  MOCK_METHOD0(This, int());\n  MOCK_METHOD2(That, std::string(int, bool));\n\n private:\n  std::string str_;\n\n  MockBar(const MockBar&) = delete;\n  MockBar& operator=(const MockBar&) = delete;\n};\n\nclass MockBaz {\n public:\n  class MoveOnly {\n   public:\n    MoveOnly() = default;\n\n    MoveOnly(const MoveOnly&) = delete;\n    MoveOnly& operator=(const MoveOnly&) = delete;\n\n    MoveOnly(MoveOnly&&) = default;\n    MoveOnly& operator=(MoveOnly&&) = default;\n  };\n\n  MockBaz(MoveOnly) {}\n};\n\n#if GTEST_HAS_STREAM_REDIRECTION\n\n// Tests that a raw mock generates warnings for uninteresting calls.\nTEST(RawMockTest, WarningForUninterestingCall) {\n  const std::string saved_flag = GMOCK_FLAG_GET(verbose);\n  GMOCK_FLAG_SET(verbose, \"warning\");\n\n  MockFoo raw_foo;\n\n  CaptureStdout();\n  raw_foo.DoThis();\n  raw_foo.DoThat(true);\n  EXPECT_THAT(GetCapturedStdout(),\n              HasSubstr(\"Uninteresting mock function call\"));\n\n  GMOCK_FLAG_SET(verbose, saved_flag);\n}\n\n// Tests that a raw mock generates warnings for uninteresting calls\n// that delete the mock object.\nTEST(RawMockTest, WarningForUninterestingCallAfterDeath) {\n  const std::string saved_flag = GMOCK_FLAG_GET(verbose);\n  GMOCK_FLAG_SET(verbose, \"warning\");\n\n  MockFoo* const raw_foo = new MockFoo;\n\n  ON_CALL(*raw_foo, DoThis()).WillByDefault(Invoke(raw_foo, &MockFoo::Delete));\n\n  CaptureStdout();\n  raw_foo->DoThis();\n  EXPECT_THAT(GetCapturedStdout(),\n              HasSubstr(\"Uninteresting mock function call\"));\n\n  GMOCK_FLAG_SET(verbose, saved_flag);\n}\n\n// Tests that a raw mock generates informational logs for\n// uninteresting calls.\nTEST(RawMockTest, InfoForUninterestingCall) {\n  MockFoo raw_foo;\n\n  const std::string saved_flag = GMOCK_FLAG_GET(verbose);\n  GMOCK_FLAG_SET(verbose, \"info\");\n  CaptureStdout();\n  raw_foo.DoThis();\n  EXPECT_THAT(GetCapturedStdout(),\n              HasSubstr(\"Uninteresting mock function call\"));\n\n  GMOCK_FLAG_SET(verbose, saved_flag);\n}\n\nTEST(RawMockTest, IsNaggy_IsNice_IsStrict) {\n  MockFoo raw_foo;\n  EXPECT_TRUE(Mock::IsNaggy(&raw_foo));\n  EXPECT_FALSE(Mock::IsNice(&raw_foo));\n  EXPECT_FALSE(Mock::IsStrict(&raw_foo));\n}\n\n// Tests that a nice mock generates no warning for uninteresting calls.\nTEST(NiceMockTest, NoWarningForUninterestingCall) {\n  NiceMock<MockFoo> nice_foo;\n\n  CaptureStdout();\n  nice_foo.DoThis();\n  nice_foo.DoThat(true);\n  EXPECT_EQ(\"\", GetCapturedStdout());\n}\n\n// Tests that a nice mock generates no warning for uninteresting calls\n// that delete the mock object.\nTEST(NiceMockTest, NoWarningForUninterestingCallAfterDeath) {\n  NiceMock<MockFoo>* const nice_foo = new NiceMock<MockFoo>;\n\n  ON_CALL(*nice_foo, DoThis())\n      .WillByDefault(Invoke(nice_foo, &MockFoo::Delete));\n\n  CaptureStdout();\n  nice_foo->DoThis();\n  EXPECT_EQ(\"\", GetCapturedStdout());\n}\n\n// Tests that a nice mock generates informational logs for\n// uninteresting calls.\nTEST(NiceMockTest, InfoForUninterestingCall) {\n  NiceMock<MockFoo> nice_foo;\n\n  const std::string saved_flag = GMOCK_FLAG_GET(verbose);\n  GMOCK_FLAG_SET(verbose, \"info\");\n  CaptureStdout();\n  nice_foo.DoThis();\n  EXPECT_THAT(GetCapturedStdout(),\n              HasSubstr(\"Uninteresting mock function call\"));\n\n  GMOCK_FLAG_SET(verbose, saved_flag);\n}\n\n#endif  // GTEST_HAS_STREAM_REDIRECTION\n\n// Tests that a nice mock allows expected calls.\nTEST(NiceMockTest, AllowsExpectedCall) {\n  NiceMock<MockFoo> nice_foo;\n\n  EXPECT_CALL(nice_foo, DoThis());\n  nice_foo.DoThis();\n}\n\n// Tests that an unexpected call on a nice mock which returns a\n// not-default-constructible type throws an exception and the exception contains\n// the method's name.\nTEST(NiceMockTest, ThrowsExceptionForUnknownReturnTypes) {\n  NiceMock<MockFoo> nice_foo;\n#if GTEST_HAS_EXCEPTIONS\n  try {\n    nice_foo.ReturnNonDefaultConstructible();\n    FAIL();\n  } catch (const std::runtime_error& ex) {\n    EXPECT_THAT(ex.what(), HasSubstr(\"ReturnNonDefaultConstructible\"));\n  }\n#else\n  EXPECT_DEATH_IF_SUPPORTED({ nice_foo.ReturnNonDefaultConstructible(); }, \"\");\n#endif\n}\n\n// Tests that an unexpected call on a nice mock fails.\nTEST(NiceMockTest, UnexpectedCallFails) {\n  NiceMock<MockFoo> nice_foo;\n\n  EXPECT_CALL(nice_foo, DoThis()).Times(0);\n  EXPECT_NONFATAL_FAILURE(nice_foo.DoThis(), \"called more times than expected\");\n}\n\n// Tests that NiceMock works with a mock class that has a non-default\n// constructor.\nTEST(NiceMockTest, NonDefaultConstructor) {\n  NiceMock<MockBar> nice_bar(\"hi\");\n  EXPECT_EQ(\"hi\", nice_bar.str());\n\n  nice_bar.This();\n  nice_bar.That(5, true);\n}\n\n// Tests that NiceMock works with a mock class that has a 10-ary\n// non-default constructor.\nTEST(NiceMockTest, NonDefaultConstructor10) {\n  NiceMock<MockBar> nice_bar('a', 'b', \"c\", \"d\", 'e', 'f', \"g\", \"h\", true,\n                             false);\n  EXPECT_EQ(\"abcdefghTF\", nice_bar.str());\n\n  nice_bar.This();\n  nice_bar.That(5, true);\n}\n\nTEST(NiceMockTest, AllowLeak) {\n  NiceMock<MockFoo>* leaked = new NiceMock<MockFoo>;\n  Mock::AllowLeak(leaked);\n  EXPECT_CALL(*leaked, DoThis());\n  leaked->DoThis();\n}\n\nTEST(NiceMockTest, MoveOnlyConstructor) {\n  NiceMock<MockBaz> nice_baz(MockBaz::MoveOnly{});\n}\n\n// Tests that NiceMock<Mock> compiles where Mock is a user-defined\n// class (as opposed to ::testing::Mock).\nTEST(NiceMockTest, AcceptsClassNamedMock) {\n  NiceMock< ::Mock> nice;\n  EXPECT_CALL(nice, DoThis());\n  nice.DoThis();\n}\n\nTEST(NiceMockTest, IsNiceInDestructor) {\n  {\n    NiceMock<CallsMockMethodInDestructor> nice_on_destroy;\n    // Don't add an expectation for the call before the mock goes out of scope.\n  }\n}\n\nTEST(NiceMockTest, IsNaggy_IsNice_IsStrict) {\n  NiceMock<MockFoo> nice_foo;\n  EXPECT_FALSE(Mock::IsNaggy(&nice_foo));\n  EXPECT_TRUE(Mock::IsNice(&nice_foo));\n  EXPECT_FALSE(Mock::IsStrict(&nice_foo));\n}\n\n#if GTEST_HAS_STREAM_REDIRECTION\n\n// Tests that a naggy mock generates warnings for uninteresting calls.\nTEST(NaggyMockTest, WarningForUninterestingCall) {\n  const std::string saved_flag = GMOCK_FLAG_GET(verbose);\n  GMOCK_FLAG_SET(verbose, \"warning\");\n\n  NaggyMock<MockFoo> naggy_foo;\n\n  CaptureStdout();\n  naggy_foo.DoThis();\n  naggy_foo.DoThat(true);\n  EXPECT_THAT(GetCapturedStdout(),\n              HasSubstr(\"Uninteresting mock function call\"));\n\n  GMOCK_FLAG_SET(verbose, saved_flag);\n}\n\n// Tests that a naggy mock generates a warning for an uninteresting call\n// that deletes the mock object.\nTEST(NaggyMockTest, WarningForUninterestingCallAfterDeath) {\n  const std::string saved_flag = GMOCK_FLAG_GET(verbose);\n  GMOCK_FLAG_SET(verbose, \"warning\");\n\n  NaggyMock<MockFoo>* const naggy_foo = new NaggyMock<MockFoo>;\n\n  ON_CALL(*naggy_foo, DoThis())\n      .WillByDefault(Invoke(naggy_foo, &MockFoo::Delete));\n\n  CaptureStdout();\n  naggy_foo->DoThis();\n  EXPECT_THAT(GetCapturedStdout(),\n              HasSubstr(\"Uninteresting mock function call\"));\n\n  GMOCK_FLAG_SET(verbose, saved_flag);\n}\n\n#endif  // GTEST_HAS_STREAM_REDIRECTION\n\n// Tests that a naggy mock allows expected calls.\nTEST(NaggyMockTest, AllowsExpectedCall) {\n  NaggyMock<MockFoo> naggy_foo;\n\n  EXPECT_CALL(naggy_foo, DoThis());\n  naggy_foo.DoThis();\n}\n\n// Tests that an unexpected call on a naggy mock fails.\nTEST(NaggyMockTest, UnexpectedCallFails) {\n  NaggyMock<MockFoo> naggy_foo;\n\n  EXPECT_CALL(naggy_foo, DoThis()).Times(0);\n  EXPECT_NONFATAL_FAILURE(naggy_foo.DoThis(),\n                          \"called more times than expected\");\n}\n\n// Tests that NaggyMock works with a mock class that has a non-default\n// constructor.\nTEST(NaggyMockTest, NonDefaultConstructor) {\n  NaggyMock<MockBar> naggy_bar(\"hi\");\n  EXPECT_EQ(\"hi\", naggy_bar.str());\n\n  naggy_bar.This();\n  naggy_bar.That(5, true);\n}\n\n// Tests that NaggyMock works with a mock class that has a 10-ary\n// non-default constructor.\nTEST(NaggyMockTest, NonDefaultConstructor10) {\n  NaggyMock<MockBar> naggy_bar('0', '1', \"2\", \"3\", '4', '5', \"6\", \"7\", true,\n                               false);\n  EXPECT_EQ(\"01234567TF\", naggy_bar.str());\n\n  naggy_bar.This();\n  naggy_bar.That(5, true);\n}\n\nTEST(NaggyMockTest, AllowLeak) {\n  NaggyMock<MockFoo>* leaked = new NaggyMock<MockFoo>;\n  Mock::AllowLeak(leaked);\n  EXPECT_CALL(*leaked, DoThis());\n  leaked->DoThis();\n}\n\nTEST(NaggyMockTest, MoveOnlyConstructor) {\n  NaggyMock<MockBaz> naggy_baz(MockBaz::MoveOnly{});\n}\n\n// Tests that NaggyMock<Mock> compiles where Mock is a user-defined\n// class (as opposed to ::testing::Mock).\nTEST(NaggyMockTest, AcceptsClassNamedMock) {\n  NaggyMock< ::Mock> naggy;\n  EXPECT_CALL(naggy, DoThis());\n  naggy.DoThis();\n}\n\nTEST(NaggyMockTest, IsNaggyInDestructor) {\n  const std::string saved_flag = GMOCK_FLAG_GET(verbose);\n  GMOCK_FLAG_SET(verbose, \"warning\");\n  CaptureStdout();\n\n  {\n    NaggyMock<CallsMockMethodInDestructor> naggy_on_destroy;\n    // Don't add an expectation for the call before the mock goes out of scope.\n  }\n\n  EXPECT_THAT(GetCapturedStdout(),\n              HasSubstr(\"Uninteresting mock function call\"));\n\n  GMOCK_FLAG_SET(verbose, saved_flag);\n}\n\nTEST(NaggyMockTest, IsNaggy_IsNice_IsStrict) {\n  NaggyMock<MockFoo> naggy_foo;\n  EXPECT_TRUE(Mock::IsNaggy(&naggy_foo));\n  EXPECT_FALSE(Mock::IsNice(&naggy_foo));\n  EXPECT_FALSE(Mock::IsStrict(&naggy_foo));\n}\n\n// Tests that a strict mock allows expected calls.\nTEST(StrictMockTest, AllowsExpectedCall) {\n  StrictMock<MockFoo> strict_foo;\n\n  EXPECT_CALL(strict_foo, DoThis());\n  strict_foo.DoThis();\n}\n\n// Tests that an unexpected call on a strict mock fails.\nTEST(StrictMockTest, UnexpectedCallFails) {\n  StrictMock<MockFoo> strict_foo;\n\n  EXPECT_CALL(strict_foo, DoThis()).Times(0);\n  EXPECT_NONFATAL_FAILURE(strict_foo.DoThis(),\n                          \"called more times than expected\");\n}\n\n// Tests that an uninteresting call on a strict mock fails.\nTEST(StrictMockTest, UninterestingCallFails) {\n  StrictMock<MockFoo> strict_foo;\n\n  EXPECT_NONFATAL_FAILURE(strict_foo.DoThis(),\n                          \"Uninteresting mock function call\");\n}\n\n// Tests that an uninteresting call on a strict mock fails, even if\n// the call deletes the mock object.\nTEST(StrictMockTest, UninterestingCallFailsAfterDeath) {\n  StrictMock<MockFoo>* const strict_foo = new StrictMock<MockFoo>;\n\n  ON_CALL(*strict_foo, DoThis())\n      .WillByDefault(Invoke(strict_foo, &MockFoo::Delete));\n\n  EXPECT_NONFATAL_FAILURE(strict_foo->DoThis(),\n                          \"Uninteresting mock function call\");\n}\n\n// Tests that StrictMock works with a mock class that has a\n// non-default constructor.\nTEST(StrictMockTest, NonDefaultConstructor) {\n  StrictMock<MockBar> strict_bar(\"hi\");\n  EXPECT_EQ(\"hi\", strict_bar.str());\n\n  EXPECT_NONFATAL_FAILURE(strict_bar.That(5, true),\n                          \"Uninteresting mock function call\");\n}\n\n// Tests that StrictMock works with a mock class that has a 10-ary\n// non-default constructor.\nTEST(StrictMockTest, NonDefaultConstructor10) {\n  StrictMock<MockBar> strict_bar('a', 'b', \"c\", \"d\", 'e', 'f', \"g\", \"h\", true,\n                                 false);\n  EXPECT_EQ(\"abcdefghTF\", strict_bar.str());\n\n  EXPECT_NONFATAL_FAILURE(strict_bar.That(5, true),\n                          \"Uninteresting mock function call\");\n}\n\nTEST(StrictMockTest, AllowLeak) {\n  StrictMock<MockFoo>* leaked = new StrictMock<MockFoo>;\n  Mock::AllowLeak(leaked);\n  EXPECT_CALL(*leaked, DoThis());\n  leaked->DoThis();\n}\n\nTEST(StrictMockTest, MoveOnlyConstructor) {\n  StrictMock<MockBaz> strict_baz(MockBaz::MoveOnly{});\n}\n\n// Tests that StrictMock<Mock> compiles where Mock is a user-defined\n// class (as opposed to ::testing::Mock).\nTEST(StrictMockTest, AcceptsClassNamedMock) {\n  StrictMock< ::Mock> strict;\n  EXPECT_CALL(strict, DoThis());\n  strict.DoThis();\n}\n\nTEST(StrictMockTest, IsStrictInDestructor) {\n  EXPECT_NONFATAL_FAILURE(\n      {\n        StrictMock<CallsMockMethodInDestructor> strict_on_destroy;\n        // Don't add an expectation for the call before the mock goes out of\n        // scope.\n      },\n      \"Uninteresting mock function call\");\n}\n\nTEST(StrictMockTest, IsNaggy_IsNice_IsStrict) {\n  StrictMock<MockFoo> strict_foo;\n  EXPECT_FALSE(Mock::IsNaggy(&strict_foo));\n  EXPECT_FALSE(Mock::IsNice(&strict_foo));\n  EXPECT_TRUE(Mock::IsStrict(&strict_foo));\n}\n\n}  // namespace gmock_nice_strict_test\n}  // namespace testing\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock-port_test.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file tests the internal cross-platform support utilities.\n\n#include \"gmock/internal/gmock-port.h\"\n\n#include \"gtest/gtest.h\"\n\n// NOTE: if this file is left without tests for some reason, put a dummy\n// test here to make references to symbols in the gtest library and avoid\n// 'undefined symbol' linker errors in gmock_main:\n\nTEST(DummyTest, Dummy) {}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock-pp-string_test.cc",
    "content": "// Copyright 2018, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file tests the internal preprocessor macro library.\n#include <string>\n\n#include \"gmock/gmock.h\"\n#include \"gmock/internal/gmock-pp.h\"\n\nnamespace testing {\nnamespace {\n\n// Matcher to verify that to strings are identical up to whitespace\n// Not 100% correct, because it treats \"AB\" as equal to \"A B\".\n::testing::Matcher<const std::string&> SameExceptSpaces(const std::string& s) {\n  auto remove_spaces = [](std::string to_split) {\n    to_split.erase(std::remove(to_split.begin(), to_split.end(), ' '),\n                   to_split.end());\n    return to_split;\n  };\n  return ::testing::ResultOf(remove_spaces, remove_spaces(s));\n}\n\n// Verify that a macro expands to a given text. Ignores whitespace difference.\n// In MSVC, GMOCK_PP_STRINGIZE() returns nothing, rather than \"\". So concatenate\n// with an empty string.\n#define EXPECT_EXPANSION(Result, Macro) \\\n  EXPECT_THAT(\"\" GMOCK_PP_STRINGIZE(Macro), SameExceptSpaces(Result))\n\nTEST(Macros, Cat) {\n  EXPECT_EXPANSION(\"14\", GMOCK_PP_CAT(1, 4));\n  EXPECT_EXPANSION(\"+=\", GMOCK_PP_CAT(+, =));\n}\n\nTEST(Macros, Narg) {\n  EXPECT_EXPANSION(\"1\", GMOCK_PP_NARG());\n  EXPECT_EXPANSION(\"1\", GMOCK_PP_NARG(x));\n  EXPECT_EXPANSION(\"2\", GMOCK_PP_NARG(x, y));\n  EXPECT_EXPANSION(\"3\", GMOCK_PP_NARG(x, y, z));\n  EXPECT_EXPANSION(\"4\", GMOCK_PP_NARG(x, y, z, w));\n\n  EXPECT_EXPANSION(\"0\", GMOCK_PP_NARG0());\n  EXPECT_EXPANSION(\"1\", GMOCK_PP_NARG0(x));\n  EXPECT_EXPANSION(\"2\", GMOCK_PP_NARG0(x, y));\n}\n\nTEST(Macros, Comma) {\n  EXPECT_EXPANSION(\"0\", GMOCK_PP_HAS_COMMA());\n  EXPECT_EXPANSION(\"1\", GMOCK_PP_HAS_COMMA(, ));\n  EXPECT_EXPANSION(\"0\", GMOCK_PP_HAS_COMMA((, )));\n}\n\nTEST(Macros, IsEmpty) {\n  EXPECT_EXPANSION(\"1\", GMOCK_PP_IS_EMPTY());\n  EXPECT_EXPANSION(\"0\", GMOCK_PP_IS_EMPTY(, ));\n  EXPECT_EXPANSION(\"0\", GMOCK_PP_IS_EMPTY(a));\n  EXPECT_EXPANSION(\"0\", GMOCK_PP_IS_EMPTY(()));\n\n#define GMOCK_PP_INTERNAL_IS_EMPTY_TEST_1\n  EXPECT_EXPANSION(\"1\", GMOCK_PP_IS_EMPTY(GMOCK_PP_INTERNAL_IS_EMPTY_TEST_1));\n}\n\nTEST(Macros, If) {\n  EXPECT_EXPANSION(\"1\", GMOCK_PP_IF(1, 1, 2));\n  EXPECT_EXPANSION(\"2\", GMOCK_PP_IF(0, 1, 2));\n}\n\nTEST(Macros, HeadTail) {\n  EXPECT_EXPANSION(\"1\", GMOCK_PP_HEAD(1));\n  EXPECT_EXPANSION(\"1\", GMOCK_PP_HEAD(1, 2));\n  EXPECT_EXPANSION(\"1\", GMOCK_PP_HEAD(1, 2, 3));\n\n  EXPECT_EXPANSION(\"\", GMOCK_PP_TAIL(1));\n  EXPECT_EXPANSION(\"2\", GMOCK_PP_TAIL(1, 2));\n  EXPECT_EXPANSION(\"2\", GMOCK_PP_HEAD(GMOCK_PP_TAIL(1, 2, 3)));\n}\n\nTEST(Macros, Parentheses) {\n  EXPECT_EXPANSION(\"0\", GMOCK_PP_IS_BEGIN_PARENS(sss));\n  EXPECT_EXPANSION(\"0\", GMOCK_PP_IS_BEGIN_PARENS(sss()));\n  EXPECT_EXPANSION(\"0\", GMOCK_PP_IS_BEGIN_PARENS(sss() sss));\n  EXPECT_EXPANSION(\"1\", GMOCK_PP_IS_BEGIN_PARENS((sss)));\n  EXPECT_EXPANSION(\"1\", GMOCK_PP_IS_BEGIN_PARENS((sss)ss));\n\n  EXPECT_EXPANSION(\"0\", GMOCK_PP_IS_ENCLOSED_PARENS(sss));\n  EXPECT_EXPANSION(\"0\", GMOCK_PP_IS_ENCLOSED_PARENS(sss()));\n  EXPECT_EXPANSION(\"0\", GMOCK_PP_IS_ENCLOSED_PARENS(sss() sss));\n  EXPECT_EXPANSION(\"1\", GMOCK_PP_IS_ENCLOSED_PARENS((sss)));\n  EXPECT_EXPANSION(\"0\", GMOCK_PP_IS_ENCLOSED_PARENS((sss)ss));\n\n  EXPECT_EXPANSION(\"1 + 1\", GMOCK_PP_REMOVE_PARENS((1 + 1)));\n}\n\nTEST(Macros, Increment) {\n  EXPECT_EXPANSION(\"1\", GMOCK_PP_INC(0));\n  EXPECT_EXPANSION(\"2\", GMOCK_PP_INC(1));\n  EXPECT_EXPANSION(\"3\", GMOCK_PP_INC(2));\n  EXPECT_EXPANSION(\"4\", GMOCK_PP_INC(3));\n  EXPECT_EXPANSION(\"5\", GMOCK_PP_INC(4));\n\n  EXPECT_EXPANSION(\"16\", GMOCK_PP_INC(15));\n}\n\n#define JOINER_CAT(a, b) a##b\n#define JOINER(_N, _Data, _Elem) JOINER_CAT(_Data, _N) = _Elem\n\nTEST(Macros, Repeat) {\n  EXPECT_EXPANSION(\"\", GMOCK_PP_REPEAT(JOINER, X, 0));\n  EXPECT_EXPANSION(\"X0=\", GMOCK_PP_REPEAT(JOINER, X, 1));\n  EXPECT_EXPANSION(\"X0= X1=\", GMOCK_PP_REPEAT(JOINER, X, 2));\n  EXPECT_EXPANSION(\"X0= X1= X2=\", GMOCK_PP_REPEAT(JOINER, X, 3));\n  EXPECT_EXPANSION(\"X0= X1= X2= X3=\", GMOCK_PP_REPEAT(JOINER, X, 4));\n  EXPECT_EXPANSION(\"X0= X1= X2= X3= X4=\", GMOCK_PP_REPEAT(JOINER, X, 5));\n  EXPECT_EXPANSION(\"X0= X1= X2= X3= X4= X5=\", GMOCK_PP_REPEAT(JOINER, X, 6));\n  EXPECT_EXPANSION(\"X0= X1= X2= X3= X4= X5= X6=\",\n                   GMOCK_PP_REPEAT(JOINER, X, 7));\n  EXPECT_EXPANSION(\"X0= X1= X2= X3= X4= X5= X6= X7=\",\n                   GMOCK_PP_REPEAT(JOINER, X, 8));\n  EXPECT_EXPANSION(\"X0= X1= X2= X3= X4= X5= X6= X7= X8=\",\n                   GMOCK_PP_REPEAT(JOINER, X, 9));\n  EXPECT_EXPANSION(\"X0= X1= X2= X3= X4= X5= X6= X7= X8= X9=\",\n                   GMOCK_PP_REPEAT(JOINER, X, 10));\n  EXPECT_EXPANSION(\"X0= X1= X2= X3= X4= X5= X6= X7= X8= X9= X10=\",\n                   GMOCK_PP_REPEAT(JOINER, X, 11));\n  EXPECT_EXPANSION(\"X0= X1= X2= X3= X4= X5= X6= X7= X8= X9= X10= X11=\",\n                   GMOCK_PP_REPEAT(JOINER, X, 12));\n  EXPECT_EXPANSION(\"X0= X1= X2= X3= X4= X5= X6= X7= X8= X9= X10= X11= X12=\",\n                   GMOCK_PP_REPEAT(JOINER, X, 13));\n  EXPECT_EXPANSION(\n      \"X0= X1= X2= X3= X4= X5= X6= X7= X8= X9= X10= X11= X12= X13=\",\n      GMOCK_PP_REPEAT(JOINER, X, 14));\n  EXPECT_EXPANSION(\n      \"X0= X1= X2= X3= X4= X5= X6= X7= X8= X9= X10= X11= X12= X13= X14=\",\n      GMOCK_PP_REPEAT(JOINER, X, 15));\n}\nTEST(Macros, ForEach) {\n  EXPECT_EXPANSION(\"\", GMOCK_PP_FOR_EACH(JOINER, X, ()));\n  EXPECT_EXPANSION(\"X0=a\", GMOCK_PP_FOR_EACH(JOINER, X, (a)));\n  EXPECT_EXPANSION(\"X0=a X1=b\", GMOCK_PP_FOR_EACH(JOINER, X, (a, b)));\n  EXPECT_EXPANSION(\"X0=a X1=b X2=c\", GMOCK_PP_FOR_EACH(JOINER, X, (a, b, c)));\n  EXPECT_EXPANSION(\"X0=a X1=b X2=c X3=d\",\n                   GMOCK_PP_FOR_EACH(JOINER, X, (a, b, c, d)));\n  EXPECT_EXPANSION(\"X0=a X1=b X2=c X3=d X4=e\",\n                   GMOCK_PP_FOR_EACH(JOINER, X, (a, b, c, d, e)));\n  EXPECT_EXPANSION(\"X0=a X1=b X2=c X3=d X4=e X5=f\",\n                   GMOCK_PP_FOR_EACH(JOINER, X, (a, b, c, d, e, f)));\n  EXPECT_EXPANSION(\"X0=a X1=b X2=c X3=d X4=e X5=f X6=g\",\n                   GMOCK_PP_FOR_EACH(JOINER, X, (a, b, c, d, e, f, g)));\n  EXPECT_EXPANSION(\"X0=a X1=b X2=c X3=d X4=e X5=f X6=g X7=h\",\n                   GMOCK_PP_FOR_EACH(JOINER, X, (a, b, c, d, e, f, g, h)));\n  EXPECT_EXPANSION(\"X0=a X1=b X2=c X3=d X4=e X5=f X6=g X7=h X8=i\",\n                   GMOCK_PP_FOR_EACH(JOINER, X, (a, b, c, d, e, f, g, h, i)));\n  EXPECT_EXPANSION(\n      \"X0=a X1=b X2=c X3=d X4=e X5=f X6=g X7=h X8=i X9=j\",\n      GMOCK_PP_FOR_EACH(JOINER, X, (a, b, c, d, e, f, g, h, i, j)));\n  EXPECT_EXPANSION(\n      \"X0=a X1=b X2=c X3=d X4=e X5=f X6=g X7=h X8=i X9=j X10=k\",\n      GMOCK_PP_FOR_EACH(JOINER, X, (a, b, c, d, e, f, g, h, i, j, k)));\n  EXPECT_EXPANSION(\n      \"X0=a X1=b X2=c X3=d X4=e X5=f X6=g X7=h X8=i X9=j X10=k X11=l\",\n      GMOCK_PP_FOR_EACH(JOINER, X, (a, b, c, d, e, f, g, h, i, j, k, l)));\n  EXPECT_EXPANSION(\n      \"X0=a X1=b X2=c X3=d X4=e X5=f X6=g X7=h X8=i X9=j X10=k X11=l X12=m\",\n      GMOCK_PP_FOR_EACH(JOINER, X, (a, b, c, d, e, f, g, h, i, j, k, l, m)));\n  EXPECT_EXPANSION(\n      \"X0=a X1=b X2=c X3=d X4=e X5=f X6=g X7=h X8=i X9=j X10=k X11=l X12=m \"\n      \"X13=n\",\n      GMOCK_PP_FOR_EACH(JOINER, X, (a, b, c, d, e, f, g, h, i, j, k, l, m, n)));\n  EXPECT_EXPANSION(\n      \"X0=a X1=b X2=c X3=d X4=e X5=f X6=g X7=h X8=i X9=j X10=k X11=l X12=m \"\n      \"X13=n X14=o\",\n      GMOCK_PP_FOR_EACH(JOINER, X,\n                        (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)));\n}\n\n}  // namespace\n}  // namespace testing\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock-pp_test.cc",
    "content": "#include \"gmock/internal/gmock-pp.h\"\n\n// Used to test MSVC treating __VA_ARGS__ with a comma in it as one value\n#define GMOCK_TEST_REPLACE_comma_WITH_COMMA_I_comma ,\n#define GMOCK_TEST_REPLACE_comma_WITH_COMMA(x) \\\n  GMOCK_PP_CAT(GMOCK_TEST_REPLACE_comma_WITH_COMMA_I_, x)\n\n// Static assertions.\nnamespace testing {\nnamespace internal {\nnamespace gmockpp {\n\nstatic_assert(GMOCK_PP_CAT(1, 4) == 14, \"\");\nstatic_assert(GMOCK_PP_INTERNAL_INTERNAL_16TH(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,\n                                              12, 13, 14, 15, 16, 17, 18) == 16,\n              \"\");\nstatic_assert(GMOCK_PP_NARG() == 1, \"\");\nstatic_assert(GMOCK_PP_NARG(x) == 1, \"\");\nstatic_assert(GMOCK_PP_NARG(x, y) == 2, \"\");\nstatic_assert(GMOCK_PP_NARG(x, y, z) == 3, \"\");\nstatic_assert(GMOCK_PP_NARG(x, y, z, w) == 4, \"\");\nstatic_assert(!GMOCK_PP_HAS_COMMA(), \"\");\nstatic_assert(GMOCK_PP_HAS_COMMA(b, ), \"\");\nstatic_assert(!GMOCK_PP_HAS_COMMA((, )), \"\");\nstatic_assert(GMOCK_PP_HAS_COMMA(GMOCK_TEST_REPLACE_comma_WITH_COMMA(comma)),\n              \"\");\nstatic_assert(\n    GMOCK_PP_HAS_COMMA(GMOCK_TEST_REPLACE_comma_WITH_COMMA(comma(unrelated))),\n    \"\");\nstatic_assert(!GMOCK_PP_IS_EMPTY(, ), \"\");\nstatic_assert(!GMOCK_PP_IS_EMPTY(a), \"\");\nstatic_assert(!GMOCK_PP_IS_EMPTY(()), \"\");\nstatic_assert(GMOCK_PP_IF(1, 1, 2) == 1, \"\");\nstatic_assert(GMOCK_PP_IF(0, 1, 2) == 2, \"\");\nstatic_assert(GMOCK_PP_NARG0(x) == 1, \"\");\nstatic_assert(GMOCK_PP_NARG0(x, y) == 2, \"\");\nstatic_assert(GMOCK_PP_HEAD(1) == 1, \"\");\nstatic_assert(GMOCK_PP_HEAD(1, 2) == 1, \"\");\nstatic_assert(GMOCK_PP_HEAD(1, 2, 3) == 1, \"\");\nstatic_assert(GMOCK_PP_TAIL(1, 2) == 2, \"\");\nstatic_assert(GMOCK_PP_HEAD(GMOCK_PP_TAIL(1, 2, 3)) == 2, \"\");\nstatic_assert(!GMOCK_PP_IS_BEGIN_PARENS(sss), \"\");\nstatic_assert(!GMOCK_PP_IS_BEGIN_PARENS(sss()), \"\");\nstatic_assert(!GMOCK_PP_IS_BEGIN_PARENS(sss() sss), \"\");\nstatic_assert(GMOCK_PP_IS_BEGIN_PARENS((sss)), \"\");\nstatic_assert(GMOCK_PP_IS_BEGIN_PARENS((sss)ss), \"\");\nstatic_assert(!GMOCK_PP_IS_ENCLOSED_PARENS(sss), \"\");\nstatic_assert(!GMOCK_PP_IS_ENCLOSED_PARENS(sss()), \"\");\nstatic_assert(!GMOCK_PP_IS_ENCLOSED_PARENS(sss() sss), \"\");\nstatic_assert(!GMOCK_PP_IS_ENCLOSED_PARENS((sss)ss), \"\");\nstatic_assert(GMOCK_PP_REMOVE_PARENS((1 + 1)) * 2 == 3, \"\");\nstatic_assert(GMOCK_PP_INC(4) == 5, \"\");\n\ntemplate <class... Args>\nstruct Test {\n  static constexpr int kArgs = sizeof...(Args);\n};\n#define GMOCK_PP_INTERNAL_TYPE_TEST(_i, _Data, _element) \\\n  GMOCK_PP_COMMA_IF(_i) _element\nstatic_assert(Test<GMOCK_PP_FOR_EACH(GMOCK_PP_INTERNAL_TYPE_TEST, ~,\n                                     (int, float, double, char))>::kArgs == 4,\n              \"\");\n#define GMOCK_PP_INTERNAL_VAR_TEST_1(_x) 1\n#define GMOCK_PP_INTERNAL_VAR_TEST_2(_x, _y) 2\n#define GMOCK_PP_INTERNAL_VAR_TEST_3(_x, _y, _z) 3\n\n#define GMOCK_PP_INTERNAL_VAR_TEST(...) \\\n  GMOCK_PP_VARIADIC_CALL(GMOCK_PP_INTERNAL_VAR_TEST_, __VA_ARGS__)\nstatic_assert(GMOCK_PP_INTERNAL_VAR_TEST(x, y) == 2, \"\");\nstatic_assert(GMOCK_PP_INTERNAL_VAR_TEST(silly) == 1, \"\");\nstatic_assert(GMOCK_PP_INTERNAL_VAR_TEST(x, y, z) == 3, \"\");\n\n// TODO(iserna): The following asserts fail in --config=lexan.\n#define GMOCK_PP_INTERNAL_IS_EMPTY_TEST_1\nstatic_assert(GMOCK_PP_IS_EMPTY(GMOCK_PP_INTERNAL_IS_EMPTY_TEST_1), \"\");\nstatic_assert(GMOCK_PP_IS_EMPTY(), \"\");\nstatic_assert(GMOCK_PP_IS_ENCLOSED_PARENS((sss)), \"\");\nstatic_assert(GMOCK_PP_IS_EMPTY(GMOCK_PP_TAIL(1)), \"\");\nstatic_assert(GMOCK_PP_NARG0() == 0, \"\");\n\n}  // namespace gmockpp\n}  // namespace internal\n}  // namespace testing\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock-spec-builders_test.cc",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file tests the spec builder syntax.\n\n#include \"gmock/gmock-spec-builders.h\"\n\n#include <memory>\n#include <ostream>  // NOLINT\n#include <sstream>\n#include <string>\n#include <type_traits>\n\n#include \"gmock/gmock.h\"\n#include \"gmock/internal/gmock-port.h\"\n#include \"gtest/gtest-spi.h\"\n#include \"gtest/gtest.h\"\n#include \"gtest/internal/gtest-port.h\"\n\nnamespace testing {\nnamespace {\n\nusing ::testing::internal::FormatFileLocation;\nusing ::testing::internal::kAllow;\nusing ::testing::internal::kErrorVerbosity;\nusing ::testing::internal::kFail;\nusing ::testing::internal::kInfoVerbosity;\nusing ::testing::internal::kWarn;\nusing ::testing::internal::kWarningVerbosity;\n\n#if GTEST_HAS_STREAM_REDIRECTION\nusing ::testing::internal::CaptureStdout;\nusing ::testing::internal::GetCapturedStdout;\n#endif\n\nclass Incomplete;\n\nclass MockIncomplete {\n public:\n  // This line verifies that a mock method can take a by-reference\n  // argument of an incomplete type.\n  MOCK_METHOD1(ByRefFunc, void(const Incomplete& x));\n};\n\n// Tells Google Mock how to print a value of type Incomplete.\nvoid PrintTo(const Incomplete& x, ::std::ostream* os);\n\nTEST(MockMethodTest, CanInstantiateWithIncompleteArgType) {\n  // Even though this mock class contains a mock method that takes\n  // by-reference an argument whose type is incomplete, we can still\n  // use the mock, as long as Google Mock knows how to print the\n  // argument.\n  MockIncomplete incomplete;\n  EXPECT_CALL(incomplete, ByRefFunc(_)).Times(AnyNumber());\n}\n\n// The definition of the printer for the argument type doesn't have to\n// be visible where the mock is used.\nvoid PrintTo(const Incomplete& /* x */, ::std::ostream* os) {\n  *os << \"incomplete\";\n}\n\nclass Result {};\n\n// A type that's not default constructible.\nclass NonDefaultConstructible {\n public:\n  explicit NonDefaultConstructible(int /* dummy */) {}\n};\n\nclass MockA {\n public:\n  MockA() {}\n\n  MOCK_METHOD1(DoA, void(int n));\n  MOCK_METHOD1(ReturnResult, Result(int n));\n  MOCK_METHOD0(ReturnNonDefaultConstructible, NonDefaultConstructible());\n  MOCK_METHOD2(Binary, bool(int x, int y));\n  MOCK_METHOD2(ReturnInt, int(int x, int y));\n\n private:\n  MockA(const MockA&) = delete;\n  MockA& operator=(const MockA&) = delete;\n};\n\nclass MockB {\n public:\n  MockB() {}\n\n  MOCK_CONST_METHOD0(DoB, int());  // NOLINT\n  MOCK_METHOD1(DoB, int(int n));   // NOLINT\n\n private:\n  MockB(const MockB&) = delete;\n  MockB& operator=(const MockB&) = delete;\n};\n\nclass ReferenceHoldingMock {\n public:\n  ReferenceHoldingMock() {}\n\n  MOCK_METHOD1(AcceptReference, void(std::shared_ptr<MockA>*));\n\n private:\n  ReferenceHoldingMock(const ReferenceHoldingMock&) = delete;\n  ReferenceHoldingMock& operator=(const ReferenceHoldingMock&) = delete;\n};\n\n// Tests that EXPECT_CALL and ON_CALL compile in a presence of macro\n// redefining a mock method name. This could happen, for example, when\n// the tested code #includes Win32 API headers which define many APIs\n// as macros, e.g. #define TextOut TextOutW.\n\n#define Method MethodW\n\nclass CC {\n public:\n  virtual ~CC() {}\n  virtual int Method() = 0;\n};\nclass MockCC : public CC {\n public:\n  MockCC() {}\n\n  MOCK_METHOD0(Method, int());\n\n private:\n  MockCC(const MockCC&) = delete;\n  MockCC& operator=(const MockCC&) = delete;\n};\n\n// Tests that a method with expanded name compiles.\nTEST(OnCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {\n  MockCC cc;\n  ON_CALL(cc, Method());\n}\n\n// Tests that the method with expanded name not only compiles but runs\n// and returns a correct value, too.\nTEST(OnCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {\n  MockCC cc;\n  ON_CALL(cc, Method()).WillByDefault(Return(42));\n  EXPECT_EQ(42, cc.Method());\n}\n\n// Tests that a method with expanded name compiles.\nTEST(ExpectCallSyntaxTest, CompilesWithMethodNameExpandedFromMacro) {\n  MockCC cc;\n  EXPECT_CALL(cc, Method());\n  cc.Method();\n}\n\n// Tests that it works, too.\nTEST(ExpectCallSyntaxTest, WorksWithMethodNameExpandedFromMacro) {\n  MockCC cc;\n  EXPECT_CALL(cc, Method()).WillOnce(Return(42));\n  EXPECT_EQ(42, cc.Method());\n}\n\n#undef Method  // Done with macro redefinition tests.\n\n// Tests that ON_CALL evaluates its arguments exactly once as promised\n// by Google Mock.\nTEST(OnCallSyntaxTest, EvaluatesFirstArgumentOnce) {\n  MockA a;\n  MockA* pa = &a;\n\n  ON_CALL(*pa++, DoA(_));\n  EXPECT_EQ(&a + 1, pa);\n}\n\nTEST(OnCallSyntaxTest, EvaluatesSecondArgumentOnce) {\n  MockA a;\n  int n = 0;\n\n  ON_CALL(a, DoA(n++));\n  EXPECT_EQ(1, n);\n}\n\n// Tests that the syntax of ON_CALL() is enforced at run time.\n\nTEST(OnCallSyntaxTest, WithIsOptional) {\n  MockA a;\n\n  ON_CALL(a, DoA(5)).WillByDefault(Return());\n  ON_CALL(a, DoA(_)).With(_).WillByDefault(Return());\n}\n\nTEST(OnCallSyntaxTest, WithCanAppearAtMostOnce) {\n  MockA a;\n\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        ON_CALL(a, ReturnResult(_))\n            .With(_)\n            .With(_)\n            .WillByDefault(Return(Result()));\n      },\n      \".With() cannot appear more than once in an ON_CALL()\");\n}\n\nTEST(OnCallSyntaxTest, WillByDefaultIsMandatory) {\n  MockA a;\n\n  EXPECT_DEATH_IF_SUPPORTED(\n      {\n        ON_CALL(a, DoA(5));\n        a.DoA(5);\n      },\n      \"\");\n}\n\nTEST(OnCallSyntaxTest, WillByDefaultCanAppearAtMostOnce) {\n  MockA a;\n\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        ON_CALL(a, DoA(5)).WillByDefault(Return()).WillByDefault(Return());\n      },\n      \".WillByDefault() must appear exactly once in an ON_CALL()\");\n}\n\n// Tests that EXPECT_CALL evaluates its arguments exactly once as\n// promised by Google Mock.\nTEST(ExpectCallSyntaxTest, EvaluatesFirstArgumentOnce) {\n  MockA a;\n  MockA* pa = &a;\n\n  EXPECT_CALL(*pa++, DoA(_));\n  a.DoA(0);\n  EXPECT_EQ(&a + 1, pa);\n}\n\nTEST(ExpectCallSyntaxTest, EvaluatesSecondArgumentOnce) {\n  MockA a;\n  int n = 0;\n\n  EXPECT_CALL(a, DoA(n++));\n  a.DoA(0);\n  EXPECT_EQ(1, n);\n}\n\n// Tests that the syntax of EXPECT_CALL() is enforced at run time.\n\nTEST(ExpectCallSyntaxTest, WithIsOptional) {\n  MockA a;\n\n  EXPECT_CALL(a, DoA(5)).Times(0);\n  EXPECT_CALL(a, DoA(6)).With(_).Times(0);\n}\n\nTEST(ExpectCallSyntaxTest, WithCanAppearAtMostOnce) {\n  MockA a;\n\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_CALL(a, DoA(6)).With(_).With(_);\n      },\n      \".With() cannot appear more than once in an EXPECT_CALL()\");\n\n  a.DoA(6);\n}\n\nTEST(ExpectCallSyntaxTest, WithMustBeFirstClause) {\n  MockA a;\n\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_CALL(a, DoA(1)).Times(1).With(_);\n      },\n      \".With() must be the first clause in an EXPECT_CALL()\");\n\n  a.DoA(1);\n\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_CALL(a, DoA(2)).WillOnce(Return()).With(_);\n      },\n      \".With() must be the first clause in an EXPECT_CALL()\");\n\n  a.DoA(2);\n}\n\nTEST(ExpectCallSyntaxTest, TimesCanBeInferred) {\n  MockA a;\n\n  EXPECT_CALL(a, DoA(1)).WillOnce(Return());\n\n  EXPECT_CALL(a, DoA(2)).WillOnce(Return()).WillRepeatedly(Return());\n\n  a.DoA(1);\n  a.DoA(2);\n  a.DoA(2);\n}\n\nTEST(ExpectCallSyntaxTest, TimesCanAppearAtMostOnce) {\n  MockA a;\n\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_CALL(a, DoA(1)).Times(1).Times(2);\n      },\n      \".Times() cannot appear more than once in an EXPECT_CALL()\");\n\n  a.DoA(1);\n  a.DoA(1);\n}\n\nTEST(ExpectCallSyntaxTest, TimesMustBeBeforeInSequence) {\n  MockA a;\n  Sequence s;\n\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_CALL(a, DoA(1)).InSequence(s).Times(1);\n      },\n      \".Times() may only appear *before* \");\n\n  a.DoA(1);\n}\n\nTEST(ExpectCallSyntaxTest, InSequenceIsOptional) {\n  MockA a;\n  Sequence s;\n\n  EXPECT_CALL(a, DoA(1));\n  EXPECT_CALL(a, DoA(2)).InSequence(s);\n\n  a.DoA(1);\n  a.DoA(2);\n}\n\nTEST(ExpectCallSyntaxTest, InSequenceCanAppearMultipleTimes) {\n  MockA a;\n  Sequence s1, s2;\n\n  EXPECT_CALL(a, DoA(1)).InSequence(s1, s2).InSequence(s1);\n\n  a.DoA(1);\n}\n\nTEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeAfter) {\n  MockA a;\n  Sequence s;\n\n  Expectation e = EXPECT_CALL(a, DoA(1)).Times(AnyNumber());\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_CALL(a, DoA(2)).After(e).InSequence(s);\n      },\n      \".InSequence() cannot appear after \");\n\n  a.DoA(2);\n}\n\nTEST(ExpectCallSyntaxTest, InSequenceMustBeBeforeWillOnce) {\n  MockA a;\n  Sequence s;\n\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_CALL(a, DoA(1)).WillOnce(Return()).InSequence(s);\n      },\n      \".InSequence() cannot appear after \");\n\n  a.DoA(1);\n}\n\nTEST(ExpectCallSyntaxTest, AfterMustBeBeforeWillOnce) {\n  MockA a;\n\n  Expectation e = EXPECT_CALL(a, DoA(1));\n  EXPECT_NONFATAL_FAILURE(\n      { EXPECT_CALL(a, DoA(2)).WillOnce(Return()).After(e); },\n      \".After() cannot appear after \");\n\n  a.DoA(1);\n  a.DoA(2);\n}\n\nTEST(ExpectCallSyntaxTest, WillIsOptional) {\n  MockA a;\n\n  EXPECT_CALL(a, DoA(1));\n  EXPECT_CALL(a, DoA(2)).WillOnce(Return());\n\n  a.DoA(1);\n  a.DoA(2);\n}\n\nTEST(ExpectCallSyntaxTest, WillCanAppearMultipleTimes) {\n  MockA a;\n\n  EXPECT_CALL(a, DoA(1))\n      .Times(AnyNumber())\n      .WillOnce(Return())\n      .WillOnce(Return())\n      .WillOnce(Return());\n}\n\nTEST(ExpectCallSyntaxTest, WillMustBeBeforeWillRepeatedly) {\n  MockA a;\n\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_CALL(a, DoA(1)).WillRepeatedly(Return()).WillOnce(Return());\n      },\n      \".WillOnce() cannot appear after \");\n\n  a.DoA(1);\n}\n\nTEST(ExpectCallSyntaxTest, WillRepeatedlyIsOptional) {\n  MockA a;\n\n  EXPECT_CALL(a, DoA(1)).WillOnce(Return());\n  EXPECT_CALL(a, DoA(2)).WillOnce(Return()).WillRepeatedly(Return());\n\n  a.DoA(1);\n  a.DoA(2);\n  a.DoA(2);\n}\n\nTEST(ExpectCallSyntaxTest, WillRepeatedlyCannotAppearMultipleTimes) {\n  MockA a;\n\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_CALL(a, DoA(1)).WillRepeatedly(Return()).WillRepeatedly(\n            Return());\n      },\n      \".WillRepeatedly() cannot appear more than once in an \"\n      \"EXPECT_CALL()\");\n}\n\nTEST(ExpectCallSyntaxTest, WillRepeatedlyMustBeBeforeRetiresOnSaturation) {\n  MockA a;\n\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_CALL(a, DoA(1)).RetiresOnSaturation().WillRepeatedly(Return());\n      },\n      \".WillRepeatedly() cannot appear after \");\n}\n\nTEST(ExpectCallSyntaxTest, RetiresOnSaturationIsOptional) {\n  MockA a;\n\n  EXPECT_CALL(a, DoA(1));\n  EXPECT_CALL(a, DoA(1)).RetiresOnSaturation();\n\n  a.DoA(1);\n  a.DoA(1);\n}\n\nTEST(ExpectCallSyntaxTest, RetiresOnSaturationCannotAppearMultipleTimes) {\n  MockA a;\n\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_CALL(a, DoA(1)).RetiresOnSaturation().RetiresOnSaturation();\n      },\n      \".RetiresOnSaturation() cannot appear more than once\");\n\n  a.DoA(1);\n}\n\nTEST(ExpectCallSyntaxTest, DefaultCardinalityIsOnce) {\n  {\n    MockA a;\n    EXPECT_CALL(a, DoA(1));\n    a.DoA(1);\n  }\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        MockA a;\n        EXPECT_CALL(a, DoA(1));\n      },\n      \"to be called once\");\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        MockA a;\n        EXPECT_CALL(a, DoA(1));\n        a.DoA(1);\n        a.DoA(1);\n      },\n      \"to be called once\");\n}\n\n#if GTEST_HAS_STREAM_REDIRECTION\n\n// Tests that Google Mock doesn't print a warning when the number of\n// WillOnce() is adequate.\nTEST(ExpectCallSyntaxTest, DoesNotWarnOnAdequateActionCount) {\n  CaptureStdout();\n  {\n    MockB b;\n\n    // It's always fine to omit WillOnce() entirely.\n    EXPECT_CALL(b, DoB()).Times(0);\n    EXPECT_CALL(b, DoB(1)).Times(AtMost(1));\n    EXPECT_CALL(b, DoB(2)).Times(1).WillRepeatedly(Return(1));\n\n    // It's fine for the number of WillOnce()s to equal the upper bound.\n    EXPECT_CALL(b, DoB(3))\n        .Times(Between(1, 2))\n        .WillOnce(Return(1))\n        .WillOnce(Return(2));\n\n    // It's fine for the number of WillOnce()s to be smaller than the\n    // upper bound when there is a WillRepeatedly().\n    EXPECT_CALL(b, DoB(4)).Times(AtMost(3)).WillOnce(Return(1)).WillRepeatedly(\n        Return(2));\n\n    // Satisfies the above expectations.\n    b.DoB(2);\n    b.DoB(3);\n  }\n  EXPECT_STREQ(\"\", GetCapturedStdout().c_str());\n}\n\n// Tests that Google Mock warns on having too many actions in an\n// expectation compared to its cardinality.\nTEST(ExpectCallSyntaxTest, WarnsOnTooManyActions) {\n  CaptureStdout();\n  {\n    MockB b;\n\n    // Warns when the number of WillOnce()s is larger than the upper bound.\n    EXPECT_CALL(b, DoB()).Times(0).WillOnce(Return(1));  // #1\n    EXPECT_CALL(b, DoB()).Times(AtMost(1)).WillOnce(Return(1)).WillOnce(\n        Return(2));  // #2\n    EXPECT_CALL(b, DoB(1))\n        .Times(1)\n        .WillOnce(Return(1))\n        .WillOnce(Return(2))\n        .RetiresOnSaturation();  // #3\n\n    // Warns when the number of WillOnce()s equals the upper bound and\n    // there is a WillRepeatedly().\n    EXPECT_CALL(b, DoB()).Times(0).WillRepeatedly(Return(1));  // #4\n    EXPECT_CALL(b, DoB(2)).Times(1).WillOnce(Return(1)).WillRepeatedly(\n        Return(2));  // #5\n\n    // Satisfies the above expectations.\n    b.DoB(1);\n    b.DoB(2);\n  }\n  const std::string output = GetCapturedStdout();\n  EXPECT_PRED_FORMAT2(IsSubstring,\n                      \"Too many actions specified in EXPECT_CALL(b, DoB())...\\n\"\n                      \"Expected to be never called, but has 1 WillOnce().\",\n                      output);  // #1\n  EXPECT_PRED_FORMAT2(IsSubstring,\n                      \"Too many actions specified in EXPECT_CALL(b, DoB())...\\n\"\n                      \"Expected to be called at most once, \"\n                      \"but has 2 WillOnce()s.\",\n                      output);  // #2\n  EXPECT_PRED_FORMAT2(\n      IsSubstring,\n      \"Too many actions specified in EXPECT_CALL(b, DoB(1))...\\n\"\n      \"Expected to be called once, but has 2 WillOnce()s.\",\n      output);  // #3\n  EXPECT_PRED_FORMAT2(IsSubstring,\n                      \"Too many actions specified in EXPECT_CALL(b, DoB())...\\n\"\n                      \"Expected to be never called, but has 0 WillOnce()s \"\n                      \"and a WillRepeatedly().\",\n                      output);  // #4\n  EXPECT_PRED_FORMAT2(\n      IsSubstring,\n      \"Too many actions specified in EXPECT_CALL(b, DoB(2))...\\n\"\n      \"Expected to be called once, but has 1 WillOnce() \"\n      \"and a WillRepeatedly().\",\n      output);  // #5\n}\n\n// Tests that Google Mock warns on having too few actions in an\n// expectation compared to its cardinality.\nTEST(ExpectCallSyntaxTest, WarnsOnTooFewActions) {\n  MockB b;\n\n  EXPECT_CALL(b, DoB()).Times(Between(2, 3)).WillOnce(Return(1));\n\n  CaptureStdout();\n  b.DoB();\n  const std::string output = GetCapturedStdout();\n  EXPECT_PRED_FORMAT2(IsSubstring,\n                      \"Too few actions specified in EXPECT_CALL(b, DoB())...\\n\"\n                      \"Expected to be called between 2 and 3 times, \"\n                      \"but has only 1 WillOnce().\",\n                      output);\n  b.DoB();\n}\n\nTEST(ExpectCallSyntaxTest, WarningIsErrorWithFlag) {\n  int original_behavior = GMOCK_FLAG_GET(default_mock_behavior);\n\n  GMOCK_FLAG_SET(default_mock_behavior, kAllow);\n  CaptureStdout();\n  {\n    MockA a;\n    a.DoA(0);\n  }\n  std::string output = GetCapturedStdout();\n  EXPECT_TRUE(output.empty()) << output;\n\n  GMOCK_FLAG_SET(default_mock_behavior, kWarn);\n  CaptureStdout();\n  {\n    MockA a;\n    a.DoA(0);\n  }\n  std::string warning_output = GetCapturedStdout();\n  EXPECT_PRED_FORMAT2(IsSubstring, \"GMOCK WARNING\", warning_output);\n  EXPECT_PRED_FORMAT2(IsSubstring, \"Uninteresting mock function call\",\n                      warning_output);\n\n  GMOCK_FLAG_SET(default_mock_behavior, kFail);\n  EXPECT_NONFATAL_FAILURE(\n      {\n        MockA a;\n        a.DoA(0);\n      },\n      \"Uninteresting mock function call\");\n\n  // Out of bounds values are converted to kWarn\n  GMOCK_FLAG_SET(default_mock_behavior, -1);\n  CaptureStdout();\n  {\n    MockA a;\n    a.DoA(0);\n  }\n  warning_output = GetCapturedStdout();\n  EXPECT_PRED_FORMAT2(IsSubstring, \"GMOCK WARNING\", warning_output);\n  EXPECT_PRED_FORMAT2(IsSubstring, \"Uninteresting mock function call\",\n                      warning_output);\n  GMOCK_FLAG_SET(default_mock_behavior, 3);\n  CaptureStdout();\n  {\n    MockA a;\n    a.DoA(0);\n  }\n  warning_output = GetCapturedStdout();\n  EXPECT_PRED_FORMAT2(IsSubstring, \"GMOCK WARNING\", warning_output);\n  EXPECT_PRED_FORMAT2(IsSubstring, \"Uninteresting mock function call\",\n                      warning_output);\n\n  GMOCK_FLAG_SET(default_mock_behavior, original_behavior);\n}\n\n#endif  // GTEST_HAS_STREAM_REDIRECTION\n\n// Tests the semantics of ON_CALL().\n\n// Tests that the built-in default action is taken when no ON_CALL()\n// is specified.\nTEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCall) {\n  MockB b;\n  EXPECT_CALL(b, DoB());\n\n  EXPECT_EQ(0, b.DoB());\n}\n\n// Tests that the built-in default action is taken when no ON_CALL()\n// matches the invocation.\nTEST(OnCallTest, TakesBuiltInDefaultActionWhenNoOnCallMatches) {\n  MockB b;\n  ON_CALL(b, DoB(1)).WillByDefault(Return(1));\n  EXPECT_CALL(b, DoB(_));\n\n  EXPECT_EQ(0, b.DoB(2));\n}\n\n// Tests that the last matching ON_CALL() action is taken.\nTEST(OnCallTest, PicksLastMatchingOnCall) {\n  MockB b;\n  ON_CALL(b, DoB(_)).WillByDefault(Return(3));\n  ON_CALL(b, DoB(2)).WillByDefault(Return(2));\n  ON_CALL(b, DoB(1)).WillByDefault(Return(1));\n  EXPECT_CALL(b, DoB(_));\n\n  EXPECT_EQ(2, b.DoB(2));\n}\n\n// Tests the semantics of EXPECT_CALL().\n\n// Tests that any call is allowed when no EXPECT_CALL() is specified.\nTEST(ExpectCallTest, AllowsAnyCallWhenNoSpec) {\n  MockB b;\n  EXPECT_CALL(b, DoB());\n  // There is no expectation on DoB(int).\n\n  b.DoB();\n\n  // DoB(int) can be called any number of times.\n  b.DoB(1);\n  b.DoB(2);\n}\n\n// Tests that the last matching EXPECT_CALL() fires.\nTEST(ExpectCallTest, PicksLastMatchingExpectCall) {\n  MockB b;\n  EXPECT_CALL(b, DoB(_)).WillRepeatedly(Return(2));\n  EXPECT_CALL(b, DoB(1)).WillRepeatedly(Return(1));\n\n  EXPECT_EQ(1, b.DoB(1));\n}\n\n// Tests lower-bound violation.\nTEST(ExpectCallTest, CatchesTooFewCalls) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        MockB b;\n        EXPECT_CALL(b, DoB(5)).Times(AtLeast(2));\n\n        b.DoB(5);\n      },\n      \"Actual function call count doesn't match EXPECT_CALL(b, DoB(5))...\\n\"\n      \"         Expected: to be called at least twice\\n\"\n      \"           Actual: called once - unsatisfied and active\");\n}\n\n// Tests that the cardinality can be inferred when no Times(...) is\n// specified.\nTEST(ExpectCallTest, InfersCardinalityWhenThereIsNoWillRepeatedly) {\n  {\n    MockB b;\n    EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2));\n\n    EXPECT_EQ(1, b.DoB());\n    EXPECT_EQ(2, b.DoB());\n  }\n\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        MockB b;\n        EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2));\n\n        EXPECT_EQ(1, b.DoB());\n      },\n      \"to be called twice\");\n\n  {  // NOLINT\n    MockB b;\n    EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2));\n\n    EXPECT_EQ(1, b.DoB());\n    EXPECT_EQ(2, b.DoB());\n    EXPECT_NONFATAL_FAILURE(b.DoB(), \"to be called twice\");\n  }\n}\n\nTEST(ExpectCallTest, InfersCardinality1WhenThereIsWillRepeatedly) {\n  {\n    MockB b;\n    EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));\n\n    EXPECT_EQ(1, b.DoB());\n  }\n\n  {  // NOLINT\n    MockB b;\n    EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));\n\n    EXPECT_EQ(1, b.DoB());\n    EXPECT_EQ(2, b.DoB());\n    EXPECT_EQ(2, b.DoB());\n  }\n\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        MockB b;\n        EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));\n      },\n      \"to be called at least once\");\n}\n\n#if defined(__cplusplus) && __cplusplus >= 201703L\n\n// It should be possible to return a non-moveable type from a mock action in\n// C++17 and above, where it's guaranteed that such a type can be initialized\n// from a prvalue returned from a function.\nTEST(ExpectCallTest, NonMoveableType) {\n  // Define a non-moveable result type.\n  struct Result {\n    explicit Result(int x_in) : x(x_in) {}\n    Result(Result&&) = delete;\n\n    int x;\n  };\n\n  static_assert(!std::is_move_constructible_v<Result>);\n  static_assert(!std::is_copy_constructible_v<Result>);\n\n  static_assert(!std::is_move_assignable_v<Result>);\n  static_assert(!std::is_copy_assignable_v<Result>);\n\n  // We should be able to use a callable that returns that result as both a\n  // OnceAction and an Action, whether the callable ignores arguments or not.\n  const auto return_17 = [] { return Result(17); };\n\n  static_cast<void>(OnceAction<Result()>{return_17});\n  static_cast<void>(Action<Result()>{return_17});\n\n  static_cast<void>(OnceAction<Result(int)>{return_17});\n  static_cast<void>(Action<Result(int)>{return_17});\n\n  // It should be possible to return the result end to end through an\n  // EXPECT_CALL statement, with both WillOnce and WillRepeatedly.\n  MockFunction<Result()> mock;\n  EXPECT_CALL(mock, Call)   //\n      .WillOnce(return_17)  //\n      .WillRepeatedly(return_17);\n\n  EXPECT_EQ(17, mock.AsStdFunction()().x);\n  EXPECT_EQ(17, mock.AsStdFunction()().x);\n  EXPECT_EQ(17, mock.AsStdFunction()().x);\n}\n\n#endif  // C++17 and above\n\n// Tests that the n-th action is taken for the n-th matching\n// invocation.\nTEST(ExpectCallTest, NthMatchTakesNthAction) {\n  MockB b;\n  EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillOnce(Return(2)).WillOnce(\n      Return(3));\n\n  EXPECT_EQ(1, b.DoB());\n  EXPECT_EQ(2, b.DoB());\n  EXPECT_EQ(3, b.DoB());\n}\n\n// Tests that the WillRepeatedly() action is taken when the WillOnce(...)\n// list is exhausted.\nTEST(ExpectCallTest, TakesRepeatedActionWhenWillListIsExhausted) {\n  MockB b;\n  EXPECT_CALL(b, DoB()).WillOnce(Return(1)).WillRepeatedly(Return(2));\n\n  EXPECT_EQ(1, b.DoB());\n  EXPECT_EQ(2, b.DoB());\n  EXPECT_EQ(2, b.DoB());\n}\n\n#if GTEST_HAS_STREAM_REDIRECTION\n\n// Tests that the default action is taken when the WillOnce(...) list is\n// exhausted and there is no WillRepeatedly().\nTEST(ExpectCallTest, TakesDefaultActionWhenWillListIsExhausted) {\n  MockB b;\n  EXPECT_CALL(b, DoB(_)).Times(1);\n  EXPECT_CALL(b, DoB())\n      .Times(AnyNumber())\n      .WillOnce(Return(1))\n      .WillOnce(Return(2));\n\n  CaptureStdout();\n  EXPECT_EQ(0, b.DoB(1));  // Shouldn't generate a warning as the\n                           // expectation has no action clause at all.\n  EXPECT_EQ(1, b.DoB());\n  EXPECT_EQ(2, b.DoB());\n  const std::string output1 = GetCapturedStdout();\n  EXPECT_STREQ(\"\", output1.c_str());\n\n  CaptureStdout();\n  EXPECT_EQ(0, b.DoB());\n  EXPECT_EQ(0, b.DoB());\n  const std::string output2 = GetCapturedStdout();\n  EXPECT_THAT(output2.c_str(),\n              HasSubstr(\"Actions ran out in EXPECT_CALL(b, DoB())...\\n\"\n                        \"Called 3 times, but only 2 WillOnce()s are specified\"\n                        \" - returning default value.\"));\n  EXPECT_THAT(output2.c_str(),\n              HasSubstr(\"Actions ran out in EXPECT_CALL(b, DoB())...\\n\"\n                        \"Called 4 times, but only 2 WillOnce()s are specified\"\n                        \" - returning default value.\"));\n}\n\nTEST(FunctionMockerMessageTest, ReportsExpectCallLocationForExhausedActions) {\n  MockB b;\n  std::string expect_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);\n  EXPECT_CALL(b, DoB()).Times(AnyNumber()).WillOnce(Return(1));\n\n  EXPECT_EQ(1, b.DoB());\n\n  CaptureStdout();\n  EXPECT_EQ(0, b.DoB());\n  const std::string output = GetCapturedStdout();\n  // The warning message should contain the call location.\n  EXPECT_PRED_FORMAT2(IsSubstring, expect_call_location, output);\n}\n\nTEST(FunctionMockerMessageTest,\n     ReportsDefaultActionLocationOfUninterestingCallsForNaggyMock) {\n  std::string on_call_location;\n  CaptureStdout();\n  {\n    NaggyMock<MockB> b;\n    on_call_location = FormatFileLocation(__FILE__, __LINE__ + 1);\n    ON_CALL(b, DoB(_)).WillByDefault(Return(0));\n    b.DoB(0);\n  }\n  EXPECT_PRED_FORMAT2(IsSubstring, on_call_location, GetCapturedStdout());\n}\n\n#endif  // GTEST_HAS_STREAM_REDIRECTION\n\n// Tests that an uninteresting call performs the default action.\nTEST(UninterestingCallTest, DoesDefaultAction) {\n  // When there is an ON_CALL() statement, the action specified by it\n  // should be taken.\n  MockA a;\n  ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));\n  EXPECT_TRUE(a.Binary(1, 2));\n\n  // When there is no ON_CALL(), the default value for the return type\n  // should be returned.\n  MockB b;\n  EXPECT_EQ(0, b.DoB());\n}\n\n// Tests that an unexpected call performs the default action.\nTEST(UnexpectedCallTest, DoesDefaultAction) {\n  // When there is an ON_CALL() statement, the action specified by it\n  // should be taken.\n  MockA a;\n  ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));\n  EXPECT_CALL(a, Binary(0, 0));\n  a.Binary(0, 0);\n  bool result = false;\n  EXPECT_NONFATAL_FAILURE(result = a.Binary(1, 2),\n                          \"Unexpected mock function call\");\n  EXPECT_TRUE(result);\n\n  // When there is no ON_CALL(), the default value for the return type\n  // should be returned.\n  MockB b;\n  EXPECT_CALL(b, DoB(0)).Times(0);\n  int n = -1;\n  EXPECT_NONFATAL_FAILURE(n = b.DoB(1), \"Unexpected mock function call\");\n  EXPECT_EQ(0, n);\n}\n\n// Tests that when an unexpected void function generates the right\n// failure message.\nTEST(UnexpectedCallTest, GeneratesFailureForVoidFunction) {\n  // First, tests the message when there is only one EXPECT_CALL().\n  MockA a1;\n  EXPECT_CALL(a1, DoA(1));\n  a1.DoA(1);\n  // Ideally we should match the failure message against a regex, but\n  // EXPECT_NONFATAL_FAILURE doesn't support that, so we test for\n  // multiple sub-strings instead.\n  EXPECT_NONFATAL_FAILURE(\n      a1.DoA(9),\n      \"Unexpected mock function call - returning directly.\\n\"\n      \"    Function call: DoA(9)\\n\"\n      \"Google Mock tried the following 1 expectation, but it didn't match:\");\n  EXPECT_NONFATAL_FAILURE(\n      a1.DoA(9),\n      \"  Expected arg #0: is equal to 1\\n\"\n      \"           Actual: 9\\n\"\n      \"         Expected: to be called once\\n\"\n      \"           Actual: called once - saturated and active\");\n\n  // Next, tests the message when there are more than one EXPECT_CALL().\n  MockA a2;\n  EXPECT_CALL(a2, DoA(1));\n  EXPECT_CALL(a2, DoA(3));\n  a2.DoA(1);\n  EXPECT_NONFATAL_FAILURE(\n      a2.DoA(2),\n      \"Unexpected mock function call - returning directly.\\n\"\n      \"    Function call: DoA(2)\\n\"\n      \"Google Mock tried the following 2 expectations, but none matched:\");\n  EXPECT_NONFATAL_FAILURE(\n      a2.DoA(2),\n      \"tried expectation #0: EXPECT_CALL(a2, DoA(1))...\\n\"\n      \"  Expected arg #0: is equal to 1\\n\"\n      \"           Actual: 2\\n\"\n      \"         Expected: to be called once\\n\"\n      \"           Actual: called once - saturated and active\");\n  EXPECT_NONFATAL_FAILURE(\n      a2.DoA(2),\n      \"tried expectation #1: EXPECT_CALL(a2, DoA(3))...\\n\"\n      \"  Expected arg #0: is equal to 3\\n\"\n      \"           Actual: 2\\n\"\n      \"         Expected: to be called once\\n\"\n      \"           Actual: never called - unsatisfied and active\");\n  a2.DoA(3);\n}\n\n// Tests that an unexpected non-void function generates the right\n// failure message.\nTEST(UnexpectedCallTest, GeneartesFailureForNonVoidFunction) {\n  MockB b1;\n  EXPECT_CALL(b1, DoB(1));\n  b1.DoB(1);\n  EXPECT_NONFATAL_FAILURE(\n      b1.DoB(2),\n      \"Unexpected mock function call - returning default value.\\n\"\n      \"    Function call: DoB(2)\\n\"\n      \"          Returns: 0\\n\"\n      \"Google Mock tried the following 1 expectation, but it didn't match:\");\n  EXPECT_NONFATAL_FAILURE(\n      b1.DoB(2),\n      \"  Expected arg #0: is equal to 1\\n\"\n      \"           Actual: 2\\n\"\n      \"         Expected: to be called once\\n\"\n      \"           Actual: called once - saturated and active\");\n}\n\n// Tests that Google Mock explains that an retired expectation doesn't\n// match the call.\nTEST(UnexpectedCallTest, RetiredExpectation) {\n  MockB b;\n  EXPECT_CALL(b, DoB(1)).RetiresOnSaturation();\n\n  b.DoB(1);\n  EXPECT_NONFATAL_FAILURE(b.DoB(1),\n                          \"         Expected: the expectation is active\\n\"\n                          \"           Actual: it is retired\");\n}\n\n// Tests that Google Mock explains that an expectation that doesn't\n// match the arguments doesn't match the call.\nTEST(UnexpectedCallTest, UnmatchedArguments) {\n  MockB b;\n  EXPECT_CALL(b, DoB(1));\n\n  EXPECT_NONFATAL_FAILURE(b.DoB(2),\n                          \"  Expected arg #0: is equal to 1\\n\"\n                          \"           Actual: 2\\n\");\n  b.DoB(1);\n}\n\n// Tests that Google Mock explains that an expectation with\n// unsatisfied pre-requisites doesn't match the call.\nTEST(UnexpectedCallTest, UnsatisifiedPrerequisites) {\n  Sequence s1, s2;\n  MockB b;\n  EXPECT_CALL(b, DoB(1)).InSequence(s1);\n  EXPECT_CALL(b, DoB(2)).Times(AnyNumber()).InSequence(s1);\n  EXPECT_CALL(b, DoB(3)).InSequence(s2);\n  EXPECT_CALL(b, DoB(4)).InSequence(s1, s2);\n\n  ::testing::TestPartResultArray failures;\n  {\n    ::testing::ScopedFakeTestPartResultReporter reporter(&failures);\n    b.DoB(4);\n    // Now 'failures' contains the Google Test failures generated by\n    // the above statement.\n  }\n\n  // There should be one non-fatal failure.\n  ASSERT_EQ(1, failures.size());\n  const ::testing::TestPartResult& r = failures.GetTestPartResult(0);\n  EXPECT_EQ(::testing::TestPartResult::kNonFatalFailure, r.type());\n\n  // Verifies that the failure message contains the two unsatisfied\n  // pre-requisites but not the satisfied one.\n#if GTEST_USES_PCRE\n  EXPECT_THAT(\n      r.message(),\n      ContainsRegex(\n          // PCRE has trouble using (.|\\n) to match any character, but\n          // supports the (?s) prefix for using . to match any character.\n          \"(?s)the following immediate pre-requisites are not satisfied:\\n\"\n          \".*: pre-requisite #0\\n\"\n          \".*: pre-requisite #1\"));\n#elif GTEST_USES_POSIX_RE\n  EXPECT_THAT(r.message(),\n              ContainsRegex(\n                  // POSIX RE doesn't understand the (?s) prefix, but has no\n                  // trouble with (.|\\n).\n                  \"the following immediate pre-requisites are not satisfied:\\n\"\n                  \"(.|\\n)*: pre-requisite #0\\n\"\n                  \"(.|\\n)*: pre-requisite #1\"));\n#else\n  // We can only use Google Test's own simple regex.\n  EXPECT_THAT(r.message(),\n              ContainsRegex(\n                  \"the following immediate pre-requisites are not satisfied:\"));\n  EXPECT_THAT(r.message(), ContainsRegex(\": pre-requisite #0\"));\n  EXPECT_THAT(r.message(), ContainsRegex(\": pre-requisite #1\"));\n#endif  // GTEST_USES_PCRE\n\n  b.DoB(1);\n  b.DoB(3);\n  b.DoB(4);\n}\n\nTEST(UndefinedReturnValueTest,\n     ReturnValueIsMandatoryWhenNotDefaultConstructible) {\n  MockA a;\n  // FIXME: We should really verify the output message,\n  // but we cannot yet due to that EXPECT_DEATH only captures stderr\n  // while Google Mock logs to stdout.\n#if GTEST_HAS_EXCEPTIONS\n  EXPECT_ANY_THROW(a.ReturnNonDefaultConstructible());\n#else\n  EXPECT_DEATH_IF_SUPPORTED(a.ReturnNonDefaultConstructible(), \"\");\n#endif\n}\n\n// Tests that an excessive call (one whose arguments match the\n// matchers but is called too many times) performs the default action.\nTEST(ExcessiveCallTest, DoesDefaultAction) {\n  // When there is an ON_CALL() statement, the action specified by it\n  // should be taken.\n  MockA a;\n  ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));\n  EXPECT_CALL(a, Binary(0, 0));\n  a.Binary(0, 0);\n  bool result = false;\n  EXPECT_NONFATAL_FAILURE(result = a.Binary(0, 0),\n                          \"Mock function called more times than expected\");\n  EXPECT_TRUE(result);\n\n  // When there is no ON_CALL(), the default value for the return type\n  // should be returned.\n  MockB b;\n  EXPECT_CALL(b, DoB(0)).Times(0);\n  int n = -1;\n  EXPECT_NONFATAL_FAILURE(n = b.DoB(0),\n                          \"Mock function called more times than expected\");\n  EXPECT_EQ(0, n);\n}\n\n// Tests that when a void function is called too many times,\n// the failure message contains the argument values.\nTEST(ExcessiveCallTest, GeneratesFailureForVoidFunction) {\n  MockA a;\n  EXPECT_CALL(a, DoA(_)).Times(0);\n  EXPECT_NONFATAL_FAILURE(\n      a.DoA(9),\n      \"Mock function called more times than expected - returning directly.\\n\"\n      \"    Function call: DoA(9)\\n\"\n      \"         Expected: to be never called\\n\"\n      \"           Actual: called once - over-saturated and active\");\n}\n\n// Tests that when a non-void function is called too many times, the\n// failure message contains the argument values and the return value.\nTEST(ExcessiveCallTest, GeneratesFailureForNonVoidFunction) {\n  MockB b;\n  EXPECT_CALL(b, DoB(_));\n  b.DoB(1);\n  EXPECT_NONFATAL_FAILURE(\n      b.DoB(2),\n      \"Mock function called more times than expected - \"\n      \"returning default value.\\n\"\n      \"    Function call: DoB(2)\\n\"\n      \"          Returns: 0\\n\"\n      \"         Expected: to be called once\\n\"\n      \"           Actual: called twice - over-saturated and active\");\n}\n\n// Tests using sequences.\n\nTEST(InSequenceTest, AllExpectationInScopeAreInSequence) {\n  MockA a;\n  {\n    InSequence dummy;\n\n    EXPECT_CALL(a, DoA(1));\n    EXPECT_CALL(a, DoA(2));\n  }\n\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        a.DoA(2);\n      },\n      \"Unexpected mock function call\");\n\n  a.DoA(1);\n  a.DoA(2);\n}\n\nTEST(InSequenceTest, NestedInSequence) {\n  MockA a;\n  {\n    InSequence dummy;\n\n    EXPECT_CALL(a, DoA(1));\n    {\n      InSequence dummy2;\n\n      EXPECT_CALL(a, DoA(2));\n      EXPECT_CALL(a, DoA(3));\n    }\n  }\n\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        a.DoA(1);\n        a.DoA(3);\n      },\n      \"Unexpected mock function call\");\n\n  a.DoA(2);\n  a.DoA(3);\n}\n\nTEST(InSequenceTest, ExpectationsOutOfScopeAreNotAffected) {\n  MockA a;\n  {\n    InSequence dummy;\n\n    EXPECT_CALL(a, DoA(1));\n    EXPECT_CALL(a, DoA(2));\n  }\n  EXPECT_CALL(a, DoA(3));\n\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        a.DoA(2);\n      },\n      \"Unexpected mock function call\");\n\n  a.DoA(3);\n  a.DoA(1);\n  a.DoA(2);\n}\n\n// Tests that any order is allowed when no sequence is used.\nTEST(SequenceTest, AnyOrderIsOkByDefault) {\n  {\n    MockA a;\n    MockB b;\n\n    EXPECT_CALL(a, DoA(1));\n    EXPECT_CALL(b, DoB()).Times(AnyNumber());\n\n    a.DoA(1);\n    b.DoB();\n  }\n\n  {  // NOLINT\n    MockA a;\n    MockB b;\n\n    EXPECT_CALL(a, DoA(1));\n    EXPECT_CALL(b, DoB()).Times(AnyNumber());\n\n    b.DoB();\n    a.DoA(1);\n  }\n}\n\n// Tests that the calls must be in strict order when a complete order\n// is specified.\nTEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo1) {\n  MockA a;\n  ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));\n\n  Sequence s;\n  EXPECT_CALL(a, ReturnResult(1)).InSequence(s);\n  EXPECT_CALL(a, ReturnResult(2)).InSequence(s);\n  EXPECT_CALL(a, ReturnResult(3)).InSequence(s);\n\n  a.ReturnResult(1);\n\n  // May only be called after a.ReturnResult(2).\n  EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), \"Unexpected mock function call\");\n\n  a.ReturnResult(2);\n  a.ReturnResult(3);\n}\n\n// Tests that the calls must be in strict order when a complete order\n// is specified.\nTEST(SequenceTest, CallsMustBeInStrictOrderWhenSaidSo2) {\n  MockA a;\n  ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));\n\n  Sequence s;\n  EXPECT_CALL(a, ReturnResult(1)).InSequence(s);\n  EXPECT_CALL(a, ReturnResult(2)).InSequence(s);\n\n  // May only be called after a.ReturnResult(1).\n  EXPECT_NONFATAL_FAILURE(a.ReturnResult(2), \"Unexpected mock function call\");\n\n  a.ReturnResult(1);\n  a.ReturnResult(2);\n}\n\n// Tests specifying a DAG using multiple sequences.\nclass PartialOrderTest : public testing::Test {\n protected:\n  PartialOrderTest() {\n    ON_CALL(a_, ReturnResult(_)).WillByDefault(Return(Result()));\n\n    // Specifies this partial ordering:\n    //\n    // a.ReturnResult(1) ==>\n    //                       a.ReturnResult(2) * n  ==>  a.ReturnResult(3)\n    // b.DoB() * 2       ==>\n    Sequence x, y;\n    EXPECT_CALL(a_, ReturnResult(1)).InSequence(x);\n    EXPECT_CALL(b_, DoB()).Times(2).InSequence(y);\n    EXPECT_CALL(a_, ReturnResult(2)).Times(AnyNumber()).InSequence(x, y);\n    EXPECT_CALL(a_, ReturnResult(3)).InSequence(x);\n  }\n\n  MockA a_;\n  MockB b_;\n};\n\nTEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag1) {\n  a_.ReturnResult(1);\n  b_.DoB();\n\n  // May only be called after the second DoB().\n  EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), \"Unexpected mock function call\");\n\n  b_.DoB();\n  a_.ReturnResult(3);\n}\n\nTEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag2) {\n  // May only be called after ReturnResult(1).\n  EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), \"Unexpected mock function call\");\n\n  a_.ReturnResult(1);\n  b_.DoB();\n  b_.DoB();\n  a_.ReturnResult(3);\n}\n\nTEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag3) {\n  // May only be called last.\n  EXPECT_NONFATAL_FAILURE(a_.ReturnResult(3), \"Unexpected mock function call\");\n\n  a_.ReturnResult(1);\n  b_.DoB();\n  b_.DoB();\n  a_.ReturnResult(3);\n}\n\nTEST_F(PartialOrderTest, CallsMustConformToSpecifiedDag4) {\n  a_.ReturnResult(1);\n  b_.DoB();\n  b_.DoB();\n  a_.ReturnResult(3);\n\n  // May only be called before ReturnResult(3).\n  EXPECT_NONFATAL_FAILURE(a_.ReturnResult(2), \"Unexpected mock function call\");\n}\n\nTEST(SequenceTest, Retirement) {\n  MockA a;\n  Sequence s;\n\n  EXPECT_CALL(a, DoA(1)).InSequence(s);\n  EXPECT_CALL(a, DoA(_)).InSequence(s).RetiresOnSaturation();\n  EXPECT_CALL(a, DoA(1)).InSequence(s);\n\n  a.DoA(1);\n  a.DoA(2);\n  a.DoA(1);\n}\n\n// Tests Expectation.\n\nTEST(ExpectationTest, ConstrutorsWork) {\n  MockA a;\n  Expectation e1;  // Default ctor.\n\n  // Ctor from various forms of EXPECT_CALL.\n  Expectation e2 = EXPECT_CALL(a, DoA(2));\n  Expectation e3 = EXPECT_CALL(a, DoA(3)).With(_);\n  {\n    Sequence s;\n    Expectation e4 = EXPECT_CALL(a, DoA(4)).Times(1);\n    Expectation e5 = EXPECT_CALL(a, DoA(5)).InSequence(s);\n  }\n  Expectation e6 = EXPECT_CALL(a, DoA(6)).After(e2);\n  Expectation e7 = EXPECT_CALL(a, DoA(7)).WillOnce(Return());\n  Expectation e8 = EXPECT_CALL(a, DoA(8)).WillRepeatedly(Return());\n  Expectation e9 = EXPECT_CALL(a, DoA(9)).RetiresOnSaturation();\n\n  Expectation e10 = e2;  // Copy ctor.\n\n  EXPECT_THAT(e1, Ne(e2));\n  EXPECT_THAT(e2, Eq(e10));\n\n  a.DoA(2);\n  a.DoA(3);\n  a.DoA(4);\n  a.DoA(5);\n  a.DoA(6);\n  a.DoA(7);\n  a.DoA(8);\n  a.DoA(9);\n}\n\nTEST(ExpectationTest, AssignmentWorks) {\n  MockA a;\n  Expectation e1;\n  Expectation e2 = EXPECT_CALL(a, DoA(1));\n\n  EXPECT_THAT(e1, Ne(e2));\n\n  e1 = e2;\n  EXPECT_THAT(e1, Eq(e2));\n\n  a.DoA(1);\n}\n\n// Tests ExpectationSet.\n\nTEST(ExpectationSetTest, MemberTypesAreCorrect) {\n  ::testing::StaticAssertTypeEq<Expectation, ExpectationSet::value_type>();\n}\n\nTEST(ExpectationSetTest, ConstructorsWork) {\n  MockA a;\n\n  Expectation e1;\n  const Expectation e2;\n  ExpectationSet es1;                           // Default ctor.\n  ExpectationSet es2 = EXPECT_CALL(a, DoA(1));  // Ctor from EXPECT_CALL.\n  ExpectationSet es3 = e1;                      // Ctor from Expectation.\n  ExpectationSet es4(e1);    // Ctor from Expectation; alternative syntax.\n  ExpectationSet es5 = e2;   // Ctor from const Expectation.\n  ExpectationSet es6(e2);    // Ctor from const Expectation; alternative syntax.\n  ExpectationSet es7 = es2;  // Copy ctor.\n\n  EXPECT_EQ(0, es1.size());\n  EXPECT_EQ(1, es2.size());\n  EXPECT_EQ(1, es3.size());\n  EXPECT_EQ(1, es4.size());\n  EXPECT_EQ(1, es5.size());\n  EXPECT_EQ(1, es6.size());\n  EXPECT_EQ(1, es7.size());\n\n  EXPECT_THAT(es3, Ne(es2));\n  EXPECT_THAT(es4, Eq(es3));\n  EXPECT_THAT(es5, Eq(es4));\n  EXPECT_THAT(es6, Eq(es5));\n  EXPECT_THAT(es7, Eq(es2));\n  a.DoA(1);\n}\n\nTEST(ExpectationSetTest, AssignmentWorks) {\n  ExpectationSet es1;\n  ExpectationSet es2 = Expectation();\n\n  es1 = es2;\n  EXPECT_EQ(1, es1.size());\n  EXPECT_THAT(*(es1.begin()), Eq(Expectation()));\n  EXPECT_THAT(es1, Eq(es2));\n}\n\nTEST(ExpectationSetTest, InsertionWorks) {\n  ExpectationSet es1;\n  Expectation e1;\n  es1 += e1;\n  EXPECT_EQ(1, es1.size());\n  EXPECT_THAT(*(es1.begin()), Eq(e1));\n\n  MockA a;\n  Expectation e2 = EXPECT_CALL(a, DoA(1));\n  es1 += e2;\n  EXPECT_EQ(2, es1.size());\n\n  ExpectationSet::const_iterator it1 = es1.begin();\n  ExpectationSet::const_iterator it2 = it1;\n  ++it2;\n  EXPECT_TRUE(*it1 == e1 || *it2 == e1);  // e1 must be in the set.\n  EXPECT_TRUE(*it1 == e2 || *it2 == e2);  // e2 must be in the set too.\n  a.DoA(1);\n}\n\nTEST(ExpectationSetTest, SizeWorks) {\n  ExpectationSet es;\n  EXPECT_EQ(0, es.size());\n\n  es += Expectation();\n  EXPECT_EQ(1, es.size());\n\n  MockA a;\n  es += EXPECT_CALL(a, DoA(1));\n  EXPECT_EQ(2, es.size());\n\n  a.DoA(1);\n}\n\nTEST(ExpectationSetTest, IsEnumerable) {\n  ExpectationSet es;\n  EXPECT_TRUE(es.begin() == es.end());\n\n  es += Expectation();\n  ExpectationSet::const_iterator it = es.begin();\n  EXPECT_TRUE(it != es.end());\n  EXPECT_THAT(*it, Eq(Expectation()));\n  ++it;\n  EXPECT_TRUE(it == es.end());\n}\n\n// Tests the .After() clause.\n\nTEST(AfterTest, SucceedsWhenPartialOrderIsSatisfied) {\n  MockA a;\n  ExpectationSet es;\n  es += EXPECT_CALL(a, DoA(1));\n  es += EXPECT_CALL(a, DoA(2));\n  EXPECT_CALL(a, DoA(3)).After(es);\n\n  a.DoA(1);\n  a.DoA(2);\n  a.DoA(3);\n}\n\nTEST(AfterTest, SucceedsWhenTotalOrderIsSatisfied) {\n  MockA a;\n  MockB b;\n  // The following also verifies that const Expectation objects work\n  // too.  Do not remove the const modifiers.\n  const Expectation e1 = EXPECT_CALL(a, DoA(1));\n  const Expectation e2 = EXPECT_CALL(b, DoB()).Times(2).After(e1);\n  EXPECT_CALL(a, DoA(2)).After(e2);\n\n  a.DoA(1);\n  b.DoB();\n  b.DoB();\n  a.DoA(2);\n}\n\n// Calls must be in strict order when specified so using .After().\nTEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo1) {\n  MockA a;\n  MockB b;\n\n  // Define ordering:\n  //   a.DoA(1) ==> b.DoB() ==> a.DoA(2)\n  Expectation e1 = EXPECT_CALL(a, DoA(1));\n  Expectation e2 = EXPECT_CALL(b, DoB()).After(e1);\n  EXPECT_CALL(a, DoA(2)).After(e2);\n\n  a.DoA(1);\n\n  // May only be called after DoB().\n  EXPECT_NONFATAL_FAILURE(a.DoA(2), \"Unexpected mock function call\");\n\n  b.DoB();\n  a.DoA(2);\n}\n\n// Calls must be in strict order when specified so using .After().\nTEST(AfterTest, CallsMustBeInStrictOrderWhenSpecifiedSo2) {\n  MockA a;\n  MockB b;\n\n  // Define ordering:\n  //   a.DoA(1) ==> b.DoB() * 2 ==> a.DoA(2)\n  Expectation e1 = EXPECT_CALL(a, DoA(1));\n  Expectation e2 = EXPECT_CALL(b, DoB()).Times(2).After(e1);\n  EXPECT_CALL(a, DoA(2)).After(e2);\n\n  a.DoA(1);\n  b.DoB();\n\n  // May only be called after the second DoB().\n  EXPECT_NONFATAL_FAILURE(a.DoA(2), \"Unexpected mock function call\");\n\n  b.DoB();\n  a.DoA(2);\n}\n\n// Calls must satisfy the partial order when specified so.\nTEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo) {\n  MockA a;\n  ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));\n\n  // Define ordering:\n  //   a.DoA(1) ==>\n  //   a.DoA(2) ==> a.ReturnResult(3)\n  Expectation e = EXPECT_CALL(a, DoA(1));\n  const ExpectationSet es = EXPECT_CALL(a, DoA(2));\n  EXPECT_CALL(a, ReturnResult(3)).After(e, es);\n\n  // May only be called last.\n  EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), \"Unexpected mock function call\");\n\n  a.DoA(2);\n  a.DoA(1);\n  a.ReturnResult(3);\n}\n\n// Calls must satisfy the partial order when specified so.\nTEST(AfterTest, CallsMustSatisfyPartialOrderWhenSpecifiedSo2) {\n  MockA a;\n\n  // Define ordering:\n  //   a.DoA(1) ==>\n  //   a.DoA(2) ==> a.DoA(3)\n  Expectation e = EXPECT_CALL(a, DoA(1));\n  const ExpectationSet es = EXPECT_CALL(a, DoA(2));\n  EXPECT_CALL(a, DoA(3)).After(e, es);\n\n  a.DoA(2);\n\n  // May only be called last.\n  EXPECT_NONFATAL_FAILURE(a.DoA(3), \"Unexpected mock function call\");\n\n  a.DoA(1);\n  a.DoA(3);\n}\n\n// .After() can be combined with .InSequence().\nTEST(AfterTest, CanBeUsedWithInSequence) {\n  MockA a;\n  Sequence s;\n  Expectation e = EXPECT_CALL(a, DoA(1));\n  EXPECT_CALL(a, DoA(2)).InSequence(s);\n  EXPECT_CALL(a, DoA(3)).InSequence(s).After(e);\n\n  a.DoA(1);\n\n  // May only be after DoA(2).\n  EXPECT_NONFATAL_FAILURE(a.DoA(3), \"Unexpected mock function call\");\n\n  a.DoA(2);\n  a.DoA(3);\n}\n\n// .After() can be called multiple times.\nTEST(AfterTest, CanBeCalledManyTimes) {\n  MockA a;\n  Expectation e1 = EXPECT_CALL(a, DoA(1));\n  Expectation e2 = EXPECT_CALL(a, DoA(2));\n  Expectation e3 = EXPECT_CALL(a, DoA(3));\n  EXPECT_CALL(a, DoA(4)).After(e1).After(e2).After(e3);\n\n  a.DoA(3);\n  a.DoA(1);\n  a.DoA(2);\n  a.DoA(4);\n}\n\n// .After() accepts up to 5 arguments.\nTEST(AfterTest, AcceptsUpToFiveArguments) {\n  MockA a;\n  Expectation e1 = EXPECT_CALL(a, DoA(1));\n  Expectation e2 = EXPECT_CALL(a, DoA(2));\n  Expectation e3 = EXPECT_CALL(a, DoA(3));\n  ExpectationSet es1 = EXPECT_CALL(a, DoA(4));\n  ExpectationSet es2 = EXPECT_CALL(a, DoA(5));\n  EXPECT_CALL(a, DoA(6)).After(e1, e2, e3, es1, es2);\n\n  a.DoA(5);\n  a.DoA(2);\n  a.DoA(4);\n  a.DoA(1);\n  a.DoA(3);\n  a.DoA(6);\n}\n\n// .After() allows input to contain duplicated Expectations.\nTEST(AfterTest, AcceptsDuplicatedInput) {\n  MockA a;\n  ON_CALL(a, ReturnResult(_)).WillByDefault(Return(Result()));\n\n  // Define ordering:\n  //   DoA(1) ==>\n  //   DoA(2) ==> ReturnResult(3)\n  Expectation e1 = EXPECT_CALL(a, DoA(1));\n  Expectation e2 = EXPECT_CALL(a, DoA(2));\n  ExpectationSet es;\n  es += e1;\n  es += e2;\n  EXPECT_CALL(a, ReturnResult(3)).After(e1, e2, es, e1);\n\n  a.DoA(1);\n\n  // May only be after DoA(2).\n  EXPECT_NONFATAL_FAILURE(a.ReturnResult(3), \"Unexpected mock function call\");\n\n  a.DoA(2);\n  a.ReturnResult(3);\n}\n\n// An Expectation added to an ExpectationSet after it has been used in\n// an .After() has no effect.\nTEST(AfterTest, ChangesToExpectationSetHaveNoEffectAfterwards) {\n  MockA a;\n  ExpectationSet es1 = EXPECT_CALL(a, DoA(1));\n  Expectation e2 = EXPECT_CALL(a, DoA(2));\n  EXPECT_CALL(a, DoA(3)).After(es1);\n  es1 += e2;\n\n  a.DoA(1);\n  a.DoA(3);\n  a.DoA(2);\n}\n\n// Tests that Google Mock correctly handles calls to mock functions\n// after a mock object owning one of their pre-requisites has died.\n\n// Tests that calls that satisfy the original spec are successful.\nTEST(DeletingMockEarlyTest, Success1) {\n  MockB* const b1 = new MockB;\n  MockA* const a = new MockA;\n  MockB* const b2 = new MockB;\n\n  {\n    InSequence dummy;\n    EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1));\n    EXPECT_CALL(*a, Binary(_, _))\n        .Times(AnyNumber())\n        .WillRepeatedly(Return(true));\n    EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2));\n  }\n\n  EXPECT_EQ(1, b1->DoB(1));\n  delete b1;\n  // a's pre-requisite has died.\n  EXPECT_TRUE(a->Binary(0, 1));\n  delete b2;\n  // a's successor has died.\n  EXPECT_TRUE(a->Binary(1, 2));\n  delete a;\n}\n\n// Tests that calls that satisfy the original spec are successful.\nTEST(DeletingMockEarlyTest, Success2) {\n  MockB* const b1 = new MockB;\n  MockA* const a = new MockA;\n  MockB* const b2 = new MockB;\n\n  {\n    InSequence dummy;\n    EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1));\n    EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());\n    EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2));\n  }\n\n  delete a;  // a is trivially satisfied.\n  EXPECT_EQ(1, b1->DoB(1));\n  EXPECT_EQ(2, b2->DoB(2));\n  delete b1;\n  delete b2;\n}\n\n// Tests that it's OK to delete a mock object itself in its action.\n\n// Suppresses warning on unreferenced formal parameter in MSVC with\n// -W4.\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 4100)\n#endif\n\nACTION_P(Delete, ptr) { delete ptr; }\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\nTEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningVoid) {\n  MockA* const a = new MockA;\n  EXPECT_CALL(*a, DoA(_)).WillOnce(Delete(a));\n  a->DoA(42);  // This will cause a to be deleted.\n}\n\nTEST(DeletingMockEarlyTest, CanDeleteSelfInActionReturningValue) {\n  MockA* const a = new MockA;\n  EXPECT_CALL(*a, ReturnResult(_)).WillOnce(DoAll(Delete(a), Return(Result())));\n  a->ReturnResult(42);  // This will cause a to be deleted.\n}\n\n// Tests that calls that violate the original spec yield failures.\nTEST(DeletingMockEarlyTest, Failure1) {\n  MockB* const b1 = new MockB;\n  MockA* const a = new MockA;\n  MockB* const b2 = new MockB;\n\n  {\n    InSequence dummy;\n    EXPECT_CALL(*b1, DoB(_)).WillOnce(Return(1));\n    EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());\n    EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber()).WillRepeatedly(Return(2));\n  }\n\n  delete a;  // a is trivially satisfied.\n  EXPECT_NONFATAL_FAILURE({ b2->DoB(2); }, \"Unexpected mock function call\");\n  EXPECT_EQ(1, b1->DoB(1));\n  delete b1;\n  delete b2;\n}\n\n// Tests that calls that violate the original spec yield failures.\nTEST(DeletingMockEarlyTest, Failure2) {\n  MockB* const b1 = new MockB;\n  MockA* const a = new MockA;\n  MockB* const b2 = new MockB;\n\n  {\n    InSequence dummy;\n    EXPECT_CALL(*b1, DoB(_));\n    EXPECT_CALL(*a, Binary(_, _)).Times(AnyNumber());\n    EXPECT_CALL(*b2, DoB(_)).Times(AnyNumber());\n  }\n\n  EXPECT_NONFATAL_FAILURE(delete b1, \"Actual: never called\");\n  EXPECT_NONFATAL_FAILURE(a->Binary(0, 1), \"Unexpected mock function call\");\n  EXPECT_NONFATAL_FAILURE(b2->DoB(1), \"Unexpected mock function call\");\n  delete a;\n  delete b2;\n}\n\nclass EvenNumberCardinality : public CardinalityInterface {\n public:\n  // Returns true if and only if call_count calls will satisfy this\n  // cardinality.\n  bool IsSatisfiedByCallCount(int call_count) const override {\n    return call_count % 2 == 0;\n  }\n\n  // Returns true if and only if call_count calls will saturate this\n  // cardinality.\n  bool IsSaturatedByCallCount(int /* call_count */) const override {\n    return false;\n  }\n\n  // Describes self to an ostream.\n  void DescribeTo(::std::ostream* os) const override {\n    *os << \"called even number of times\";\n  }\n};\n\nCardinality EvenNumber() { return Cardinality(new EvenNumberCardinality); }\n\nTEST(ExpectationBaseTest,\n     AllPrerequisitesAreSatisfiedWorksForNonMonotonicCardinality) {\n  MockA* a = new MockA;\n  Sequence s;\n\n  EXPECT_CALL(*a, DoA(1)).Times(EvenNumber()).InSequence(s);\n  EXPECT_CALL(*a, DoA(2)).Times(AnyNumber()).InSequence(s);\n  EXPECT_CALL(*a, DoA(3)).Times(AnyNumber());\n\n  a->DoA(3);\n  a->DoA(1);\n  EXPECT_NONFATAL_FAILURE(a->DoA(2), \"Unexpected mock function call\");\n  EXPECT_NONFATAL_FAILURE(delete a, \"to be called even number of times\");\n}\n\n// The following tests verify the message generated when a mock\n// function is called.\n\nstruct Printable {};\n\ninline void operator<<(::std::ostream& os, const Printable&) {\n  os << \"Printable\";\n}\n\nstruct Unprintable {\n  Unprintable() : value(0) {}\n  int value;\n};\n\nclass MockC {\n public:\n  MockC() {}\n\n  MOCK_METHOD6(VoidMethod, void(bool cond, int n, std::string s, void* p,\n                                const Printable& x, Unprintable y));\n  MOCK_METHOD0(NonVoidMethod, int());  // NOLINT\n\n private:\n  MockC(const MockC&) = delete;\n  MockC& operator=(const MockC&) = delete;\n};\n\nclass VerboseFlagPreservingFixture : public testing::Test {\n protected:\n  VerboseFlagPreservingFixture()\n      : saved_verbose_flag_(GMOCK_FLAG_GET(verbose)) {}\n\n  ~VerboseFlagPreservingFixture() override {\n    GMOCK_FLAG_SET(verbose, saved_verbose_flag_);\n  }\n\n private:\n  const std::string saved_verbose_flag_;\n\n  VerboseFlagPreservingFixture(const VerboseFlagPreservingFixture&) = delete;\n  VerboseFlagPreservingFixture& operator=(const VerboseFlagPreservingFixture&) =\n      delete;\n};\n\n#if GTEST_HAS_STREAM_REDIRECTION\n\n// Tests that an uninteresting mock function call on a naggy mock\n// generates a warning without the stack trace when\n// --gmock_verbose=warning is specified.\nTEST(FunctionCallMessageTest,\n     UninterestingCallOnNaggyMockGeneratesNoStackTraceWhenVerboseWarning) {\n  GMOCK_FLAG_SET(verbose, kWarningVerbosity);\n  NaggyMock<MockC> c;\n  CaptureStdout();\n  c.VoidMethod(false, 5, \"Hi\", nullptr, Printable(), Unprintable());\n  const std::string output = GetCapturedStdout();\n  EXPECT_PRED_FORMAT2(IsSubstring, \"GMOCK WARNING\", output);\n  EXPECT_PRED_FORMAT2(IsNotSubstring, \"Stack trace:\", output);\n}\n\n// Tests that an uninteresting mock function call on a naggy mock\n// generates a warning containing the stack trace when\n// --gmock_verbose=info is specified.\nTEST(FunctionCallMessageTest,\n     UninterestingCallOnNaggyMockGeneratesFyiWithStackTraceWhenVerboseInfo) {\n  GMOCK_FLAG_SET(verbose, kInfoVerbosity);\n  NaggyMock<MockC> c;\n  CaptureStdout();\n  c.VoidMethod(false, 5, \"Hi\", nullptr, Printable(), Unprintable());\n  const std::string output = GetCapturedStdout();\n  EXPECT_PRED_FORMAT2(IsSubstring, \"GMOCK WARNING\", output);\n  EXPECT_PRED_FORMAT2(IsSubstring, \"Stack trace:\", output);\n\n#ifndef NDEBUG\n\n  // We check the stack trace content in dbg-mode only, as opt-mode\n  // may inline the call we are interested in seeing.\n\n  // Verifies that a void mock function's name appears in the stack\n  // trace.\n  EXPECT_PRED_FORMAT2(IsSubstring, \"VoidMethod(\", output);\n\n  // Verifies that a non-void mock function's name appears in the\n  // stack trace.\n  CaptureStdout();\n  c.NonVoidMethod();\n  const std::string output2 = GetCapturedStdout();\n  EXPECT_PRED_FORMAT2(IsSubstring, \"NonVoidMethod(\", output2);\n\n#endif  // NDEBUG\n}\n\n// Tests that an uninteresting mock function call on a naggy mock\n// causes the function arguments and return value to be printed.\nTEST(FunctionCallMessageTest,\n     UninterestingCallOnNaggyMockPrintsArgumentsAndReturnValue) {\n  // A non-void mock function.\n  NaggyMock<MockB> b;\n  CaptureStdout();\n  b.DoB();\n  const std::string output1 = GetCapturedStdout();\n  EXPECT_PRED_FORMAT2(\n      IsSubstring,\n      \"Uninteresting mock function call - returning default value.\\n\"\n      \"    Function call: DoB()\\n\"\n      \"          Returns: 0\\n\",\n      output1.c_str());\n  // Makes sure the return value is printed.\n\n  // A void mock function.\n  NaggyMock<MockC> c;\n  CaptureStdout();\n  c.VoidMethod(false, 5, \"Hi\", nullptr, Printable(), Unprintable());\n  const std::string output2 = GetCapturedStdout();\n  EXPECT_THAT(\n      output2.c_str(),\n      ContainsRegex(\"Uninteresting mock function call - returning directly\\\\.\\n\"\n                    \"    Function call: VoidMethod\"\n                    \"\\\\(false, 5, \\\"Hi\\\", NULL, @.+ \"\n                    \"Printable, 4-byte object <00-00 00-00>\\\\)\"));\n  // A void function has no return value to print.\n}\n\n// Tests how the --gmock_verbose flag affects Google Mock's output.\n\nclass GMockVerboseFlagTest : public VerboseFlagPreservingFixture {\n public:\n  // Verifies that the given Google Mock output is correct.  (When\n  // should_print is true, the output should match the given regex and\n  // contain the given function name in the stack trace.  When it's\n  // false, the output should be empty.)\n  void VerifyOutput(const std::string& output, bool should_print,\n                    const std::string& expected_substring,\n                    const std::string& function_name) {\n    if (should_print) {\n      EXPECT_THAT(output.c_str(), HasSubstr(expected_substring));\n#ifndef NDEBUG\n      // We check the stack trace content in dbg-mode only, as opt-mode\n      // may inline the call we are interested in seeing.\n      EXPECT_THAT(output.c_str(), HasSubstr(function_name));\n#else\n      // Suppresses 'unused function parameter' warnings.\n      static_cast<void>(function_name);\n#endif  // NDEBUG\n    } else {\n      EXPECT_STREQ(\"\", output.c_str());\n    }\n  }\n\n  // Tests how the flag affects expected calls.\n  void TestExpectedCall(bool should_print) {\n    MockA a;\n    EXPECT_CALL(a, DoA(5));\n    EXPECT_CALL(a, Binary(_, 1)).WillOnce(Return(true));\n\n    // A void-returning function.\n    CaptureStdout();\n    a.DoA(5);\n    VerifyOutput(GetCapturedStdout(), should_print,\n                 \"Mock function call matches EXPECT_CALL(a, DoA(5))...\\n\"\n                 \"    Function call: DoA(5)\\n\"\n                 \"Stack trace:\\n\",\n                 \"DoA\");\n\n    // A non-void-returning function.\n    CaptureStdout();\n    a.Binary(2, 1);\n    VerifyOutput(GetCapturedStdout(), should_print,\n                 \"Mock function call matches EXPECT_CALL(a, Binary(_, 1))...\\n\"\n                 \"    Function call: Binary(2, 1)\\n\"\n                 \"          Returns: true\\n\"\n                 \"Stack trace:\\n\",\n                 \"Binary\");\n  }\n\n  // Tests how the flag affects uninteresting calls on a naggy mock.\n  void TestUninterestingCallOnNaggyMock(bool should_print) {\n    NaggyMock<MockA> a;\n    const std::string note =\n        \"NOTE: You can safely ignore the above warning unless this \"\n        \"call should not happen.  Do not suppress it by blindly adding \"\n        \"an EXPECT_CALL() if you don't mean to enforce the call.  \"\n        \"See \"\n        \"https://github.com/google/googletest/blob/master/docs/\"\n        \"gmock_cook_book.md#\"\n        \"knowing-when-to-expect for details.\";\n\n    // A void-returning function.\n    CaptureStdout();\n    a.DoA(5);\n    VerifyOutput(GetCapturedStdout(), should_print,\n                 \"\\nGMOCK WARNING:\\n\"\n                 \"Uninteresting mock function call - returning directly.\\n\"\n                 \"    Function call: DoA(5)\\n\" +\n                     note,\n                 \"DoA\");\n\n    // A non-void-returning function.\n    CaptureStdout();\n    a.Binary(2, 1);\n    VerifyOutput(GetCapturedStdout(), should_print,\n                 \"\\nGMOCK WARNING:\\n\"\n                 \"Uninteresting mock function call - returning default value.\\n\"\n                 \"    Function call: Binary(2, 1)\\n\"\n                 \"          Returns: false\\n\" +\n                     note,\n                 \"Binary\");\n  }\n};\n\n// Tests that --gmock_verbose=info causes both expected and\n// uninteresting calls to be reported.\nTEST_F(GMockVerboseFlagTest, Info) {\n  GMOCK_FLAG_SET(verbose, kInfoVerbosity);\n  TestExpectedCall(true);\n  TestUninterestingCallOnNaggyMock(true);\n}\n\n// Tests that --gmock_verbose=warning causes uninteresting calls to be\n// reported.\nTEST_F(GMockVerboseFlagTest, Warning) {\n  GMOCK_FLAG_SET(verbose, kWarningVerbosity);\n  TestExpectedCall(false);\n  TestUninterestingCallOnNaggyMock(true);\n}\n\n// Tests that --gmock_verbose=warning causes neither expected nor\n// uninteresting calls to be reported.\nTEST_F(GMockVerboseFlagTest, Error) {\n  GMOCK_FLAG_SET(verbose, kErrorVerbosity);\n  TestExpectedCall(false);\n  TestUninterestingCallOnNaggyMock(false);\n}\n\n// Tests that --gmock_verbose=SOME_INVALID_VALUE has the same effect\n// as --gmock_verbose=warning.\nTEST_F(GMockVerboseFlagTest, InvalidFlagIsTreatedAsWarning) {\n  GMOCK_FLAG_SET(verbose, \"invalid\");  // Treated as \"warning\".\n  TestExpectedCall(false);\n  TestUninterestingCallOnNaggyMock(true);\n}\n\n#endif  // GTEST_HAS_STREAM_REDIRECTION\n\n// A helper class that generates a failure when printed.  We use it to\n// ensure that Google Mock doesn't print a value (even to an internal\n// buffer) when it is not supposed to do so.\nclass PrintMeNot {};\n\nvoid PrintTo(PrintMeNot /* dummy */, ::std::ostream* /* os */) {\n  ADD_FAILURE() << \"Google Mock is printing a value that shouldn't be \"\n                << \"printed even to an internal buffer.\";\n}\n\nclass LogTestHelper {\n public:\n  LogTestHelper() {}\n\n  MOCK_METHOD1(Foo, PrintMeNot(PrintMeNot));\n\n private:\n  LogTestHelper(const LogTestHelper&) = delete;\n  LogTestHelper& operator=(const LogTestHelper&) = delete;\n};\n\nclass GMockLogTest : public VerboseFlagPreservingFixture {\n protected:\n  LogTestHelper helper_;\n};\n\nTEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsWarning) {\n  GMOCK_FLAG_SET(verbose, kWarningVerbosity);\n  EXPECT_CALL(helper_, Foo(_)).WillOnce(Return(PrintMeNot()));\n  helper_.Foo(PrintMeNot());  // This is an expected call.\n}\n\nTEST_F(GMockLogTest, DoesNotPrintGoodCallInternallyIfVerbosityIsError) {\n  GMOCK_FLAG_SET(verbose, kErrorVerbosity);\n  EXPECT_CALL(helper_, Foo(_)).WillOnce(Return(PrintMeNot()));\n  helper_.Foo(PrintMeNot());  // This is an expected call.\n}\n\nTEST_F(GMockLogTest, DoesNotPrintWarningInternallyIfVerbosityIsError) {\n  GMOCK_FLAG_SET(verbose, kErrorVerbosity);\n  ON_CALL(helper_, Foo(_)).WillByDefault(Return(PrintMeNot()));\n  helper_.Foo(PrintMeNot());  // This should generate a warning.\n}\n\n// Tests Mock::AllowLeak().\n\nTEST(AllowLeakTest, AllowsLeakingUnusedMockObject) {\n  MockA* a = new MockA;\n  Mock::AllowLeak(a);\n}\n\nTEST(AllowLeakTest, CanBeCalledBeforeOnCall) {\n  MockA* a = new MockA;\n  Mock::AllowLeak(a);\n  ON_CALL(*a, DoA(_)).WillByDefault(Return());\n  a->DoA(0);\n}\n\nTEST(AllowLeakTest, CanBeCalledAfterOnCall) {\n  MockA* a = new MockA;\n  ON_CALL(*a, DoA(_)).WillByDefault(Return());\n  Mock::AllowLeak(a);\n}\n\nTEST(AllowLeakTest, CanBeCalledBeforeExpectCall) {\n  MockA* a = new MockA;\n  Mock::AllowLeak(a);\n  EXPECT_CALL(*a, DoA(_));\n  a->DoA(0);\n}\n\nTEST(AllowLeakTest, CanBeCalledAfterExpectCall) {\n  MockA* a = new MockA;\n  EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());\n  Mock::AllowLeak(a);\n}\n\nTEST(AllowLeakTest, WorksWhenBothOnCallAndExpectCallArePresent) {\n  MockA* a = new MockA;\n  ON_CALL(*a, DoA(_)).WillByDefault(Return());\n  EXPECT_CALL(*a, DoA(_)).Times(AnyNumber());\n  Mock::AllowLeak(a);\n}\n\n// Tests that we can verify and clear a mock object's expectations\n// when none of its methods has expectations.\nTEST(VerifyAndClearExpectationsTest, NoMethodHasExpectations) {\n  MockB b;\n  ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));\n\n  // There should be no expectations on the methods now, so we can\n  // freely call them.\n  EXPECT_EQ(0, b.DoB());\n  EXPECT_EQ(0, b.DoB(1));\n}\n\n// Tests that we can verify and clear a mock object's expectations\n// when some, but not all, of its methods have expectations *and* the\n// verification succeeds.\nTEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndSucceed) {\n  MockB b;\n  EXPECT_CALL(b, DoB()).WillOnce(Return(1));\n  b.DoB();\n  ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));\n\n  // There should be no expectations on the methods now, so we can\n  // freely call them.\n  EXPECT_EQ(0, b.DoB());\n  EXPECT_EQ(0, b.DoB(1));\n}\n\n// Tests that we can verify and clear a mock object's expectations\n// when some, but not all, of its methods have expectations *and* the\n// verification fails.\nTEST(VerifyAndClearExpectationsTest, SomeMethodsHaveExpectationsAndFail) {\n  MockB b;\n  EXPECT_CALL(b, DoB()).WillOnce(Return(1));\n  bool result = true;\n  EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),\n                          \"Actual: never called\");\n  ASSERT_FALSE(result);\n\n  // There should be no expectations on the methods now, so we can\n  // freely call them.\n  EXPECT_EQ(0, b.DoB());\n  EXPECT_EQ(0, b.DoB(1));\n}\n\n// Tests that we can verify and clear a mock object's expectations\n// when all of its methods have expectations.\nTEST(VerifyAndClearExpectationsTest, AllMethodsHaveExpectations) {\n  MockB b;\n  EXPECT_CALL(b, DoB()).WillOnce(Return(1));\n  EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));\n  b.DoB();\n  b.DoB(1);\n  ASSERT_TRUE(Mock::VerifyAndClearExpectations(&b));\n\n  // There should be no expectations on the methods now, so we can\n  // freely call them.\n  EXPECT_EQ(0, b.DoB());\n  EXPECT_EQ(0, b.DoB(1));\n}\n\n// Tests that we can verify and clear a mock object's expectations\n// when a method has more than one expectation.\nTEST(VerifyAndClearExpectationsTest, AMethodHasManyExpectations) {\n  MockB b;\n  EXPECT_CALL(b, DoB(0)).WillOnce(Return(1));\n  EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));\n  b.DoB(1);\n  bool result = true;\n  EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClearExpectations(&b),\n                          \"Actual: never called\");\n  ASSERT_FALSE(result);\n\n  // There should be no expectations on the methods now, so we can\n  // freely call them.\n  EXPECT_EQ(0, b.DoB());\n  EXPECT_EQ(0, b.DoB(1));\n}\n\n// Tests that we can call VerifyAndClearExpectations() on the same\n// mock object multiple times.\nTEST(VerifyAndClearExpectationsTest, CanCallManyTimes) {\n  MockB b;\n  EXPECT_CALL(b, DoB());\n  b.DoB();\n  Mock::VerifyAndClearExpectations(&b);\n\n  EXPECT_CALL(b, DoB(_)).WillOnce(Return(1));\n  b.DoB(1);\n  Mock::VerifyAndClearExpectations(&b);\n  Mock::VerifyAndClearExpectations(&b);\n\n  // There should be no expectations on the methods now, so we can\n  // freely call them.\n  EXPECT_EQ(0, b.DoB());\n  EXPECT_EQ(0, b.DoB(1));\n}\n\n// Tests that we can clear a mock object's default actions when none\n// of its methods has default actions.\nTEST(VerifyAndClearTest, NoMethodHasDefaultActions) {\n  MockB b;\n  // If this crashes or generates a failure, the test will catch it.\n  Mock::VerifyAndClear(&b);\n  EXPECT_EQ(0, b.DoB());\n}\n\n// Tests that we can clear a mock object's default actions when some,\n// but not all of its methods have default actions.\nTEST(VerifyAndClearTest, SomeMethodsHaveDefaultActions) {\n  MockB b;\n  ON_CALL(b, DoB()).WillByDefault(Return(1));\n\n  Mock::VerifyAndClear(&b);\n\n  // Verifies that the default action of int DoB() was removed.\n  EXPECT_EQ(0, b.DoB());\n}\n\n// Tests that we can clear a mock object's default actions when all of\n// its methods have default actions.\nTEST(VerifyAndClearTest, AllMethodsHaveDefaultActions) {\n  MockB b;\n  ON_CALL(b, DoB()).WillByDefault(Return(1));\n  ON_CALL(b, DoB(_)).WillByDefault(Return(2));\n\n  Mock::VerifyAndClear(&b);\n\n  // Verifies that the default action of int DoB() was removed.\n  EXPECT_EQ(0, b.DoB());\n\n  // Verifies that the default action of int DoB(int) was removed.\n  EXPECT_EQ(0, b.DoB(0));\n}\n\n// Tests that we can clear a mock object's default actions when a\n// method has more than one ON_CALL() set on it.\nTEST(VerifyAndClearTest, AMethodHasManyDefaultActions) {\n  MockB b;\n  ON_CALL(b, DoB(0)).WillByDefault(Return(1));\n  ON_CALL(b, DoB(_)).WillByDefault(Return(2));\n\n  Mock::VerifyAndClear(&b);\n\n  // Verifies that the default actions (there are two) of int DoB(int)\n  // were removed.\n  EXPECT_EQ(0, b.DoB(0));\n  EXPECT_EQ(0, b.DoB(1));\n}\n\n// Tests that we can call VerifyAndClear() on a mock object multiple\n// times.\nTEST(VerifyAndClearTest, CanCallManyTimes) {\n  MockB b;\n  ON_CALL(b, DoB()).WillByDefault(Return(1));\n  Mock::VerifyAndClear(&b);\n  Mock::VerifyAndClear(&b);\n\n  ON_CALL(b, DoB(_)).WillByDefault(Return(1));\n  Mock::VerifyAndClear(&b);\n\n  EXPECT_EQ(0, b.DoB());\n  EXPECT_EQ(0, b.DoB(1));\n}\n\n// Tests that VerifyAndClear() works when the verification succeeds.\nTEST(VerifyAndClearTest, Success) {\n  MockB b;\n  ON_CALL(b, DoB()).WillByDefault(Return(1));\n  EXPECT_CALL(b, DoB(1)).WillOnce(Return(2));\n\n  b.DoB();\n  b.DoB(1);\n  ASSERT_TRUE(Mock::VerifyAndClear(&b));\n\n  // There should be no expectations on the methods now, so we can\n  // freely call them.\n  EXPECT_EQ(0, b.DoB());\n  EXPECT_EQ(0, b.DoB(1));\n}\n\n// Tests that VerifyAndClear() works when the verification fails.\nTEST(VerifyAndClearTest, Failure) {\n  MockB b;\n  ON_CALL(b, DoB(_)).WillByDefault(Return(1));\n  EXPECT_CALL(b, DoB()).WillOnce(Return(2));\n\n  b.DoB(1);\n  bool result = true;\n  EXPECT_NONFATAL_FAILURE(result = Mock::VerifyAndClear(&b),\n                          \"Actual: never called\");\n  ASSERT_FALSE(result);\n\n  // There should be no expectations on the methods now, so we can\n  // freely call them.\n  EXPECT_EQ(0, b.DoB());\n  EXPECT_EQ(0, b.DoB(1));\n}\n\n// Tests that VerifyAndClear() works when the default actions and\n// expectations are set on a const mock object.\nTEST(VerifyAndClearTest, Const) {\n  MockB b;\n  ON_CALL(Const(b), DoB()).WillByDefault(Return(1));\n\n  EXPECT_CALL(Const(b), DoB()).WillOnce(DoDefault()).WillOnce(Return(2));\n\n  b.DoB();\n  b.DoB();\n  ASSERT_TRUE(Mock::VerifyAndClear(&b));\n\n  // There should be no expectations on the methods now, so we can\n  // freely call them.\n  EXPECT_EQ(0, b.DoB());\n  EXPECT_EQ(0, b.DoB(1));\n}\n\n// Tests that we can set default actions and expectations on a mock\n// object after VerifyAndClear() has been called on it.\nTEST(VerifyAndClearTest, CanSetDefaultActionsAndExpectationsAfterwards) {\n  MockB b;\n  ON_CALL(b, DoB()).WillByDefault(Return(1));\n  EXPECT_CALL(b, DoB(_)).WillOnce(Return(2));\n  b.DoB(1);\n\n  Mock::VerifyAndClear(&b);\n\n  EXPECT_CALL(b, DoB()).WillOnce(Return(3));\n  ON_CALL(b, DoB(_)).WillByDefault(Return(4));\n\n  EXPECT_EQ(3, b.DoB());\n  EXPECT_EQ(4, b.DoB(1));\n}\n\n// Tests that calling VerifyAndClear() on one mock object does not\n// affect other mock objects (either of the same type or not).\nTEST(VerifyAndClearTest, DoesNotAffectOtherMockObjects) {\n  MockA a;\n  MockB b1;\n  MockB b2;\n\n  ON_CALL(a, Binary(_, _)).WillByDefault(Return(true));\n  EXPECT_CALL(a, Binary(_, _)).WillOnce(DoDefault()).WillOnce(Return(false));\n\n  ON_CALL(b1, DoB()).WillByDefault(Return(1));\n  EXPECT_CALL(b1, DoB(_)).WillOnce(Return(2));\n\n  ON_CALL(b2, DoB()).WillByDefault(Return(3));\n  EXPECT_CALL(b2, DoB(_));\n\n  b2.DoB(0);\n  Mock::VerifyAndClear(&b2);\n\n  // Verifies that the default actions and expectations of a and b1\n  // are still in effect.\n  EXPECT_TRUE(a.Binary(0, 0));\n  EXPECT_FALSE(a.Binary(0, 0));\n\n  EXPECT_EQ(1, b1.DoB());\n  EXPECT_EQ(2, b1.DoB(0));\n}\n\nTEST(VerifyAndClearTest,\n     DestroyingChainedMocksDoesNotDeadlockThroughExpectations) {\n  std::shared_ptr<MockA> a(new MockA);\n  ReferenceHoldingMock test_mock;\n\n  // EXPECT_CALL stores a reference to a inside test_mock.\n  EXPECT_CALL(test_mock, AcceptReference(_))\n      .WillRepeatedly(SetArgPointee<0>(a));\n\n  // Throw away the reference to the mock that we have in a. After this, the\n  // only reference to it is stored by test_mock.\n  a.reset();\n\n  // When test_mock goes out of scope, it destroys the last remaining reference\n  // to the mock object originally pointed to by a. This will cause the MockA\n  // destructor to be called from inside the ReferenceHoldingMock destructor.\n  // The state of all mocks is protected by a single global lock, but there\n  // should be no deadlock.\n}\n\nTEST(VerifyAndClearTest,\n     DestroyingChainedMocksDoesNotDeadlockThroughDefaultAction) {\n  std::shared_ptr<MockA> a(new MockA);\n  ReferenceHoldingMock test_mock;\n\n  // ON_CALL stores a reference to a inside test_mock.\n  ON_CALL(test_mock, AcceptReference(_)).WillByDefault(SetArgPointee<0>(a));\n\n  // Throw away the reference to the mock that we have in a. After this, the\n  // only reference to it is stored by test_mock.\n  a.reset();\n\n  // When test_mock goes out of scope, it destroys the last remaining reference\n  // to the mock object originally pointed to by a. This will cause the MockA\n  // destructor to be called from inside the ReferenceHoldingMock destructor.\n  // The state of all mocks is protected by a single global lock, but there\n  // should be no deadlock.\n}\n\n// Tests that a mock function's action can call a mock function\n// (either the same function or a different one) either as an explicit\n// action or as a default action without causing a dead lock.  It\n// verifies that the action is not performed inside the critical\n// section.\nTEST(SynchronizationTest, CanCallMockMethodInAction) {\n  MockA a;\n  MockC c;\n  ON_CALL(a, DoA(_)).WillByDefault(\n      IgnoreResult(InvokeWithoutArgs(&c, &MockC::NonVoidMethod)));\n  EXPECT_CALL(a, DoA(1));\n  EXPECT_CALL(a, DoA(1))\n      .WillOnce(Invoke(&a, &MockA::DoA))\n      .RetiresOnSaturation();\n  EXPECT_CALL(c, NonVoidMethod());\n\n  a.DoA(1);\n  // This will match the second EXPECT_CALL() and trigger another a.DoA(1),\n  // which will in turn match the first EXPECT_CALL() and trigger a call to\n  // c.NonVoidMethod() that was specified by the ON_CALL() since the first\n  // EXPECT_CALL() did not specify an action.\n}\n\nTEST(ParameterlessExpectationsTest, CanSetExpectationsWithoutMatchers) {\n  MockA a;\n  int do_a_arg0 = 0;\n  ON_CALL(a, DoA).WillByDefault(SaveArg<0>(&do_a_arg0));\n  int do_a_47_arg0 = 0;\n  ON_CALL(a, DoA(47)).WillByDefault(SaveArg<0>(&do_a_47_arg0));\n\n  a.DoA(17);\n  EXPECT_THAT(do_a_arg0, 17);\n  EXPECT_THAT(do_a_47_arg0, 0);\n  a.DoA(47);\n  EXPECT_THAT(do_a_arg0, 17);\n  EXPECT_THAT(do_a_47_arg0, 47);\n\n  ON_CALL(a, Binary).WillByDefault(Return(true));\n  ON_CALL(a, Binary(_, 14)).WillByDefault(Return(false));\n  EXPECT_THAT(a.Binary(14, 17), true);\n  EXPECT_THAT(a.Binary(17, 14), false);\n}\n\nTEST(ParameterlessExpectationsTest, CanSetExpectationsForOverloadedMethods) {\n  MockB b;\n  ON_CALL(b, DoB()).WillByDefault(Return(9));\n  ON_CALL(b, DoB(5)).WillByDefault(Return(11));\n\n  EXPECT_THAT(b.DoB(), 9);\n  EXPECT_THAT(b.DoB(1), 0);  // default value\n  EXPECT_THAT(b.DoB(5), 11);\n}\n\nstruct MockWithConstMethods {\n public:\n  MOCK_CONST_METHOD1(Foo, int(int));\n  MOCK_CONST_METHOD2(Bar, int(int, const char*));\n};\n\nTEST(ParameterlessExpectationsTest, CanSetExpectationsForConstMethods) {\n  MockWithConstMethods mock;\n  ON_CALL(mock, Foo).WillByDefault(Return(7));\n  ON_CALL(mock, Bar).WillByDefault(Return(33));\n\n  EXPECT_THAT(mock.Foo(17), 7);\n  EXPECT_THAT(mock.Bar(27, \"purple\"), 33);\n}\n\nclass MockConstOverload {\n public:\n  MOCK_METHOD1(Overloaded, int(int));\n  MOCK_CONST_METHOD1(Overloaded, int(int));\n};\n\nTEST(ParameterlessExpectationsTest,\n     CanSetExpectationsForConstOverloadedMethods) {\n  MockConstOverload mock;\n  ON_CALL(mock, Overloaded(_)).WillByDefault(Return(7));\n  ON_CALL(mock, Overloaded(5)).WillByDefault(Return(9));\n  ON_CALL(Const(mock), Overloaded(5)).WillByDefault(Return(11));\n  ON_CALL(Const(mock), Overloaded(7)).WillByDefault(Return(13));\n\n  EXPECT_THAT(mock.Overloaded(1), 7);\n  EXPECT_THAT(mock.Overloaded(5), 9);\n  EXPECT_THAT(mock.Overloaded(7), 7);\n\n  const MockConstOverload& const_mock = mock;\n  EXPECT_THAT(const_mock.Overloaded(1), 0);\n  EXPECT_THAT(const_mock.Overloaded(5), 11);\n  EXPECT_THAT(const_mock.Overloaded(7), 13);\n}\n\n}  // namespace\n}  // namespace testing\n\n// Allows the user to define their own main and then invoke gmock_main\n// from it. This might be necessary on some platforms which require\n// specific setup and teardown.\n#if GMOCK_RENAME_MAIN\nint gmock_main(int argc, char** argv) {\n#else\nint main(int argc, char** argv) {\n#endif  // GMOCK_RENAME_MAIN\n  testing::InitGoogleMock(&argc, argv);\n  // Ensures that the tests pass no matter what value of\n  // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.\n  GMOCK_FLAG_SET(catch_leaked_mocks, true);\n  GMOCK_FLAG_SET(verbose, testing::internal::kWarningVerbosity);\n\n  return RUN_ALL_TESTS();\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock_all_test.cc",
    "content": "// Copyright 2009, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// Tests for Google C++ Mocking Framework (Google Mock)\n//\n// Some users use a build system that Google Mock doesn't support directly,\n// yet they still want to build and run Google Mock's own tests.  This file\n// includes most such tests, making it easier for these users to maintain\n// their build scripts (they just need to build this file, even though the\n// below list of actual *_test.cc files might change).\n#include \"test/gmock-actions_test.cc\"\n#include \"test/gmock-cardinalities_test.cc\"\n#include \"test/gmock-internal-utils_test.cc\"\n#include \"test/gmock-matchers-arithmetic_test.cc\"\n#include \"test/gmock-matchers-comparisons_test.cc\"\n#include \"test/gmock-matchers-containers_test.cc\"\n#include \"test/gmock-matchers-misc_test.cc\"\n#include \"test/gmock-more-actions_test.cc\"\n#include \"test/gmock-nice-strict_test.cc\"\n#include \"test/gmock-port_test.cc\"\n#include \"test/gmock-spec-builders_test.cc\"\n#include \"test/gmock_test.cc\"\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock_ex_test.cc",
    "content": "// Copyright 2013, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Tests Google Mock's functionality that depends on exceptions.\n\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n\n#if GTEST_HAS_EXCEPTIONS\nnamespace {\n\nusing testing::HasSubstr;\n\nusing testing::internal::GoogleTestFailureException;\n\n// A type that cannot be default constructed.\nclass NonDefaultConstructible {\n public:\n  explicit NonDefaultConstructible(int /* dummy */) {}\n};\n\nclass MockFoo {\n public:\n  // A mock method that returns a user-defined type.  Google Mock\n  // doesn't know what the default value for this type is.\n  MOCK_METHOD0(GetNonDefaultConstructible, NonDefaultConstructible());\n};\n\nTEST(DefaultValueTest, ThrowsRuntimeErrorWhenNoDefaultValue) {\n  MockFoo mock;\n  try {\n    // No expectation is set on this method, so Google Mock must\n    // return the default value.  However, since Google Mock knows\n    // nothing about the return type, it doesn't know what to return,\n    // and has to throw (when exceptions are enabled) or abort\n    // (otherwise).\n    mock.GetNonDefaultConstructible();\n    FAIL() << \"GetNonDefaultConstructible()'s return type has no default \"\n           << \"value, so Google Mock should have thrown.\";\n  } catch (const GoogleTestFailureException& /* unused */) {\n    FAIL() << \"Google Test does not try to catch an exception of type \"\n           << \"GoogleTestFailureException, which is used for reporting \"\n           << \"a failure to other testing frameworks.  Google Mock should \"\n           << \"not throw a GoogleTestFailureException as it will kill the \"\n           << \"entire test program instead of just the current TEST.\";\n  } catch (const std::exception& ex) {\n    EXPECT_THAT(ex.what(), HasSubstr(\"has no default value\"));\n  }\n}\n\n}  // unnamed namespace\n#endif\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock_leak_test.py",
    "content": "#!/usr/bin/env python\n#\n# Copyright 2009, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Tests that leaked mock objects can be caught be Google Mock.\"\"\"\n\nfrom googlemock.test import gmock_test_utils\n\nPROGRAM_PATH = gmock_test_utils.GetTestExecutablePath('gmock_leak_test_')\nTEST_WITH_EXPECT_CALL = [PROGRAM_PATH, '--gtest_filter=*ExpectCall*']\nTEST_WITH_ON_CALL = [PROGRAM_PATH, '--gtest_filter=*OnCall*']\nTEST_MULTIPLE_LEAKS = [PROGRAM_PATH, '--gtest_filter=*MultipleLeaked*']\n\nenviron = gmock_test_utils.environ\nSetEnvVar = gmock_test_utils.SetEnvVar\n\n# Tests in this file run a Google-Test-based test program and expect it\n# to terminate prematurely.  Therefore they are incompatible with\n# the premature-exit-file protocol by design.  Unset the\n# premature-exit filepath to prevent Google Test from creating\n# the file.\nSetEnvVar(gmock_test_utils.PREMATURE_EXIT_FILE_ENV_VAR, None)\n\n\nclass GMockLeakTest(gmock_test_utils.TestCase):\n\n  def testCatchesLeakedMockByDefault(self):\n    self.assertNotEqual(\n        0,\n        gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL,\n                                    env=environ).exit_code)\n    self.assertNotEqual(\n        0,\n        gmock_test_utils.Subprocess(TEST_WITH_ON_CALL,\n                                    env=environ).exit_code)\n\n  def testDoesNotCatchLeakedMockWhenDisabled(self):\n    self.assertEquals(\n        0,\n        gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL +\n                                    ['--gmock_catch_leaked_mocks=0'],\n                                    env=environ).exit_code)\n    self.assertEquals(\n        0,\n        gmock_test_utils.Subprocess(TEST_WITH_ON_CALL +\n                                    ['--gmock_catch_leaked_mocks=0'],\n                                    env=environ).exit_code)\n\n  def testCatchesLeakedMockWhenEnabled(self):\n    self.assertNotEqual(\n        0,\n        gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL +\n                                    ['--gmock_catch_leaked_mocks'],\n                                    env=environ).exit_code)\n    self.assertNotEqual(\n        0,\n        gmock_test_utils.Subprocess(TEST_WITH_ON_CALL +\n                                    ['--gmock_catch_leaked_mocks'],\n                                    env=environ).exit_code)\n\n  def testCatchesLeakedMockWhenEnabledWithExplictFlagValue(self):\n    self.assertNotEqual(\n        0,\n        gmock_test_utils.Subprocess(TEST_WITH_EXPECT_CALL +\n                                    ['--gmock_catch_leaked_mocks=1'],\n                                    env=environ).exit_code)\n\n  def testCatchesMultipleLeakedMocks(self):\n    self.assertNotEqual(\n        0,\n        gmock_test_utils.Subprocess(TEST_MULTIPLE_LEAKS +\n                                    ['--gmock_catch_leaked_mocks'],\n                                    env=environ).exit_code)\n\n\nif __name__ == '__main__':\n  gmock_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock_leak_test_.cc",
    "content": "// Copyright 2009, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This program is for verifying that a leaked mock object can be\n// caught by Google Mock's leak detector.\n\n#include \"gmock/gmock.h\"\n\nnamespace {\n\nusing ::testing::Return;\n\nclass FooInterface {\n public:\n  virtual ~FooInterface() {}\n  virtual void DoThis() = 0;\n};\n\nclass MockFoo : public FooInterface {\n public:\n  MockFoo() {}\n\n  MOCK_METHOD0(DoThis, void());\n\n private:\n  MockFoo(const MockFoo&) = delete;\n  MockFoo& operator=(const MockFoo&) = delete;\n};\n\nTEST(LeakTest, LeakedMockWithExpectCallCausesFailureWhenLeakCheckingIsEnabled) {\n  MockFoo* foo = new MockFoo;\n\n  EXPECT_CALL(*foo, DoThis());\n  foo->DoThis();\n\n  // In order to test the leak detector, we deliberately leak foo.\n\n  // Makes sure Google Mock's leak detector can change the exit code\n  // to 1 even when the code is already exiting with 0.\n  exit(0);\n}\n\nTEST(LeakTest, LeakedMockWithOnCallCausesFailureWhenLeakCheckingIsEnabled) {\n  MockFoo* foo = new MockFoo;\n\n  ON_CALL(*foo, DoThis()).WillByDefault(Return());\n\n  // In order to test the leak detector, we deliberately leak foo.\n\n  // Makes sure Google Mock's leak detector can change the exit code\n  // to 1 even when the code is already exiting with 0.\n  exit(0);\n}\n\nTEST(LeakTest, CatchesMultipleLeakedMockObjects) {\n  MockFoo* foo1 = new MockFoo;\n  MockFoo* foo2 = new MockFoo;\n\n  ON_CALL(*foo1, DoThis()).WillByDefault(Return());\n  EXPECT_CALL(*foo2, DoThis());\n  foo2->DoThis();\n\n  // In order to test the leak detector, we deliberately leak foo1 and\n  // foo2.\n\n  // Makes sure Google Mock's leak detector can change the exit code\n  // to 1 even when the code is already exiting with 0.\n  exit(0);\n}\n\n}  // namespace\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock_link2_test.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file is for verifying that various Google Mock constructs do not\n// produce linker errors when instantiated in different translation units.\n// Please see gmock_link_test.h for details.\n\n#define LinkTest LinkTest2\n\n#include \"test/gmock_link_test.h\"\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock_link_test.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file is for verifying that various Google Mock constructs do not\n// produce linker errors when instantiated in different translation units.\n// Please see gmock_link_test.h for details.\n\n#define LinkTest LinkTest1\n\n#include \"test/gmock_link_test.h\"\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock_link_test.h",
    "content": "// Copyright 2009, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file tests that:\n// a. A header file defining a mock class can be included in multiple\n//    translation units without causing a link error.\n// b. Actions and matchers can be instantiated with identical template\n//    arguments in different translation units without causing link\n//    errors.\n//    The following constructs are currently tested:\n//    Actions:\n//      Return()\n//      Return(value)\n//      ReturnNull\n//      ReturnRef\n//      Assign\n//      SetArgPointee\n//      SetArrayArgument\n//      SetErrnoAndReturn\n//      Invoke(function)\n//      Invoke(object, method)\n//      InvokeWithoutArgs(function)\n//      InvokeWithoutArgs(object, method)\n//      InvokeArgument\n//      WithArg\n//      WithArgs\n//      WithoutArgs\n//      DoAll\n//      DoDefault\n//      IgnoreResult\n//      Throw\n//      ACTION()-generated\n//      ACTION_P()-generated\n//      ACTION_P2()-generated\n//    Matchers:\n//      _\n//      A\n//      An\n//      Eq\n//      Gt, Lt, Ge, Le, Ne\n//      NotNull\n//      Ref\n//      TypedEq\n//      DoubleEq\n//      FloatEq\n//      NanSensitiveDoubleEq\n//      NanSensitiveFloatEq\n//      ContainsRegex\n//      MatchesRegex\n//      EndsWith\n//      HasSubstr\n//      StartsWith\n//      StrCaseEq\n//      StrCaseNe\n//      StrEq\n//      StrNe\n//      ElementsAre\n//      ElementsAreArray\n//      ContainerEq\n//      Field\n//      Property\n//      ResultOf(function)\n//      ResultOf(callback)\n//      Pointee\n//      Truly(predicate)\n//      AddressSatisfies\n//      AllOf\n//      AnyOf\n//      Not\n//      MatcherCast<T>\n//\n//  Please note: this test does not verify the functioning of these\n//  constructs, only that the programs using them will link successfully.\n//\n// Implementation note:\n// This test requires identical definitions of Interface and Mock to be\n// included in different translation units.  We achieve this by writing\n// them in this header and #including it in gmock_link_test.cc and\n// gmock_link2_test.cc.  Because the symbols generated by the compiler for\n// those constructs must be identical in both translation units,\n// definitions of Interface and Mock tests MUST be kept in the SAME\n// NON-ANONYMOUS namespace in this file.  The test fixture class LinkTest\n// is defined as LinkTest1 in gmock_link_test.cc and as LinkTest2 in\n// gmock_link2_test.cc to avoid producing linker errors.\n\n#ifndef GOOGLEMOCK_TEST_GMOCK_LINK_TEST_H_\n#define GOOGLEMOCK_TEST_GMOCK_LINK_TEST_H_\n\n#include \"gmock/gmock.h\"\n\n#if !GTEST_OS_WINDOWS_MOBILE\n#include <errno.h>\n#endif\n\n#include <iostream>\n#include <vector>\n\n#include \"gtest/gtest.h\"\n#include \"gtest/internal/gtest-port.h\"\n\nusing testing::_;\nusing testing::A;\nusing testing::Action;\nusing testing::AllOf;\nusing testing::AnyOf;\nusing testing::Assign;\nusing testing::ContainerEq;\nusing testing::DoAll;\nusing testing::DoDefault;\nusing testing::DoubleEq;\nusing testing::ElementsAre;\nusing testing::ElementsAreArray;\nusing testing::EndsWith;\nusing testing::Eq;\nusing testing::Field;\nusing testing::FloatEq;\nusing testing::Ge;\nusing testing::Gt;\nusing testing::HasSubstr;\nusing testing::IgnoreResult;\nusing testing::Invoke;\nusing testing::InvokeArgument;\nusing testing::InvokeWithoutArgs;\nusing testing::IsNull;\nusing testing::IsSubsetOf;\nusing testing::IsSupersetOf;\nusing testing::Le;\nusing testing::Lt;\nusing testing::Matcher;\nusing testing::MatcherCast;\nusing testing::NanSensitiveDoubleEq;\nusing testing::NanSensitiveFloatEq;\nusing testing::Ne;\nusing testing::Not;\nusing testing::NotNull;\nusing testing::Pointee;\nusing testing::Property;\nusing testing::Ref;\nusing testing::ResultOf;\nusing testing::Return;\nusing testing::ReturnNull;\nusing testing::ReturnRef;\nusing testing::SetArgPointee;\nusing testing::SetArrayArgument;\nusing testing::StartsWith;\nusing testing::StrCaseEq;\nusing testing::StrCaseNe;\nusing testing::StrEq;\nusing testing::StrNe;\nusing testing::Truly;\nusing testing::TypedEq;\nusing testing::WithArg;\nusing testing::WithArgs;\nusing testing::WithoutArgs;\n\n#if !GTEST_OS_WINDOWS_MOBILE\nusing testing::SetErrnoAndReturn;\n#endif\n\n#if GTEST_HAS_EXCEPTIONS\nusing testing::Throw;\n#endif\n\nusing testing::ContainsRegex;\nusing testing::MatchesRegex;\n\nclass Interface {\n public:\n  virtual ~Interface() {}\n  virtual void VoidFromString(char* str) = 0;\n  virtual char* StringFromString(char* str) = 0;\n  virtual int IntFromString(char* str) = 0;\n  virtual int& IntRefFromString(char* str) = 0;\n  virtual void VoidFromFunc(void (*func)(char* str)) = 0;\n  virtual void VoidFromIntRef(int& n) = 0;  // NOLINT\n  virtual void VoidFromFloat(float n) = 0;\n  virtual void VoidFromDouble(double n) = 0;\n  virtual void VoidFromVector(const std::vector<int>& v) = 0;\n};\n\nclass Mock : public Interface {\n public:\n  Mock() {}\n\n  MOCK_METHOD1(VoidFromString, void(char* str));\n  MOCK_METHOD1(StringFromString, char*(char* str));\n  MOCK_METHOD1(IntFromString, int(char* str));\n  MOCK_METHOD1(IntRefFromString, int&(char* str));\n  MOCK_METHOD1(VoidFromFunc, void(void (*func)(char* str)));\n  MOCK_METHOD1(VoidFromIntRef, void(int& n));  // NOLINT\n  MOCK_METHOD1(VoidFromFloat, void(float n));\n  MOCK_METHOD1(VoidFromDouble, void(double n));\n  MOCK_METHOD1(VoidFromVector, void(const std::vector<int>& v));\n\n private:\n  Mock(const Mock&) = delete;\n  Mock& operator=(const Mock&) = delete;\n};\n\nclass InvokeHelper {\n public:\n  static void StaticVoidFromVoid() {}\n  void VoidFromVoid() {}\n  static void StaticVoidFromString(char* /* str */) {}\n  void VoidFromString(char* /* str */) {}\n  static int StaticIntFromString(char* /* str */) { return 1; }\n  static bool StaticBoolFromString(const char* /* str */) { return true; }\n};\n\nclass FieldHelper {\n public:\n  explicit FieldHelper(int a_field) : field_(a_field) {}\n  int field() const { return field_; }\n  int field_;  // NOLINT -- need external access to field_ to test\n               //           the Field matcher.\n};\n\n// Tests the linkage of the ReturnVoid action.\nTEST(LinkTest, TestReturnVoid) {\n  Mock mock;\n\n  EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Return());\n  mock.VoidFromString(nullptr);\n}\n\n// Tests the linkage of the Return action.\nTEST(LinkTest, TestReturn) {\n  Mock mock;\n  char ch = 'x';\n\n  EXPECT_CALL(mock, StringFromString(_)).WillOnce(Return(&ch));\n  mock.StringFromString(nullptr);\n}\n\n// Tests the linkage of the ReturnNull action.\nTEST(LinkTest, TestReturnNull) {\n  Mock mock;\n\n  EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Return());\n  mock.VoidFromString(nullptr);\n}\n\n// Tests the linkage of the ReturnRef action.\nTEST(LinkTest, TestReturnRef) {\n  Mock mock;\n  int n = 42;\n\n  EXPECT_CALL(mock, IntRefFromString(_)).WillOnce(ReturnRef(n));\n  mock.IntRefFromString(nullptr);\n}\n\n// Tests the linkage of the Assign action.\nTEST(LinkTest, TestAssign) {\n  Mock mock;\n  char ch = 'x';\n\n  EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Assign(&ch, 'y'));\n  mock.VoidFromString(nullptr);\n}\n\n// Tests the linkage of the SetArgPointee action.\nTEST(LinkTest, TestSetArgPointee) {\n  Mock mock;\n  char ch = 'x';\n\n  EXPECT_CALL(mock, VoidFromString(_)).WillOnce(SetArgPointee<0>('y'));\n  mock.VoidFromString(&ch);\n}\n\n// Tests the linkage of the SetArrayArgument action.\nTEST(LinkTest, TestSetArrayArgument) {\n  Mock mock;\n  char ch = 'x';\n  char ch2 = 'y';\n\n  EXPECT_CALL(mock, VoidFromString(_))\n      .WillOnce(SetArrayArgument<0>(&ch2, &ch2 + 1));\n  mock.VoidFromString(&ch);\n}\n\n#if !GTEST_OS_WINDOWS_MOBILE\n\n// Tests the linkage of the SetErrnoAndReturn action.\nTEST(LinkTest, TestSetErrnoAndReturn) {\n  Mock mock;\n\n  int saved_errno = errno;\n  EXPECT_CALL(mock, IntFromString(_)).WillOnce(SetErrnoAndReturn(1, -1));\n  mock.IntFromString(nullptr);\n  errno = saved_errno;\n}\n\n#endif  // !GTEST_OS_WINDOWS_MOBILE\n\n// Tests the linkage of the Invoke(function) and Invoke(object, method) actions.\nTEST(LinkTest, TestInvoke) {\n  Mock mock;\n  InvokeHelper test_invoke_helper;\n\n  EXPECT_CALL(mock, VoidFromString(_))\n      .WillOnce(Invoke(&InvokeHelper::StaticVoidFromString))\n      .WillOnce(Invoke(&test_invoke_helper, &InvokeHelper::VoidFromString));\n  mock.VoidFromString(nullptr);\n  mock.VoidFromString(nullptr);\n}\n\n// Tests the linkage of the InvokeWithoutArgs action.\nTEST(LinkTest, TestInvokeWithoutArgs) {\n  Mock mock;\n  InvokeHelper test_invoke_helper;\n\n  EXPECT_CALL(mock, VoidFromString(_))\n      .WillOnce(InvokeWithoutArgs(&InvokeHelper::StaticVoidFromVoid))\n      .WillOnce(\n          InvokeWithoutArgs(&test_invoke_helper, &InvokeHelper::VoidFromVoid));\n  mock.VoidFromString(nullptr);\n  mock.VoidFromString(nullptr);\n}\n\n// Tests the linkage of the InvokeArgument action.\nTEST(LinkTest, TestInvokeArgument) {\n  Mock mock;\n  char ch = 'x';\n\n  EXPECT_CALL(mock, VoidFromFunc(_)).WillOnce(InvokeArgument<0>(&ch));\n  mock.VoidFromFunc(InvokeHelper::StaticVoidFromString);\n}\n\n// Tests the linkage of the WithArg action.\nTEST(LinkTest, TestWithArg) {\n  Mock mock;\n\n  EXPECT_CALL(mock, VoidFromString(_))\n      .WillOnce(WithArg<0>(Invoke(&InvokeHelper::StaticVoidFromString)));\n  mock.VoidFromString(nullptr);\n}\n\n// Tests the linkage of the WithArgs action.\nTEST(LinkTest, TestWithArgs) {\n  Mock mock;\n\n  EXPECT_CALL(mock, VoidFromString(_))\n      .WillOnce(WithArgs<0>(Invoke(&InvokeHelper::StaticVoidFromString)));\n  mock.VoidFromString(nullptr);\n}\n\n// Tests the linkage of the WithoutArgs action.\nTEST(LinkTest, TestWithoutArgs) {\n  Mock mock;\n\n  EXPECT_CALL(mock, VoidFromString(_)).WillOnce(WithoutArgs(Return()));\n  mock.VoidFromString(nullptr);\n}\n\n// Tests the linkage of the DoAll action.\nTEST(LinkTest, TestDoAll) {\n  Mock mock;\n  char ch = 'x';\n\n  EXPECT_CALL(mock, VoidFromString(_))\n      .WillOnce(DoAll(SetArgPointee<0>('y'), Return()));\n  mock.VoidFromString(&ch);\n}\n\n// Tests the linkage of the DoDefault action.\nTEST(LinkTest, TestDoDefault) {\n  Mock mock;\n  char ch = 'x';\n\n  ON_CALL(mock, VoidFromString(_)).WillByDefault(Return());\n  EXPECT_CALL(mock, VoidFromString(_)).WillOnce(DoDefault());\n  mock.VoidFromString(&ch);\n}\n\n// Tests the linkage of the IgnoreResult action.\nTEST(LinkTest, TestIgnoreResult) {\n  Mock mock;\n\n  EXPECT_CALL(mock, VoidFromString(_)).WillOnce(IgnoreResult(Return(42)));\n  mock.VoidFromString(nullptr);\n}\n\n#if GTEST_HAS_EXCEPTIONS\n// Tests the linkage of the Throw action.\nTEST(LinkTest, TestThrow) {\n  Mock mock;\n\n  EXPECT_CALL(mock, VoidFromString(_)).WillOnce(Throw(42));\n  EXPECT_THROW(mock.VoidFromString(nullptr), int);\n}\n#endif  // GTEST_HAS_EXCEPTIONS\n\n// The ACTION*() macros trigger warning C4100 (unreferenced formal\n// parameter) in MSVC with -W4.  Unfortunately they cannot be fixed in\n// the macro definition, as the warnings are generated when the macro\n// is expanded and macro expansion cannot contain #pragma.  Therefore\n// we suppress them here.\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 4100)\n#endif\n\n// Tests the linkage of actions created using ACTION macro.\nnamespace {\nACTION(Return1) { return 1; }\n}  // namespace\n\nTEST(LinkTest, TestActionMacro) {\n  Mock mock;\n\n  EXPECT_CALL(mock, IntFromString(_)).WillOnce(Return1());\n  mock.IntFromString(nullptr);\n}\n\n// Tests the linkage of actions created using ACTION_P macro.\nnamespace {\nACTION_P(ReturnArgument, ret_value) { return ret_value; }\n}  // namespace\n\nTEST(LinkTest, TestActionPMacro) {\n  Mock mock;\n\n  EXPECT_CALL(mock, IntFromString(_)).WillOnce(ReturnArgument(42));\n  mock.IntFromString(nullptr);\n}\n\n// Tests the linkage of actions created using ACTION_P2 macro.\nnamespace {\nACTION_P2(ReturnEqualsEitherOf, first, second) {\n  return arg0 == first || arg0 == second;\n}\n}  // namespace\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\nTEST(LinkTest, TestActionP2Macro) {\n  Mock mock;\n  char ch = 'x';\n\n  EXPECT_CALL(mock, IntFromString(_))\n      .WillOnce(ReturnEqualsEitherOf(\"one\", \"two\"));\n  mock.IntFromString(&ch);\n}\n\n// Tests the linkage of the \"_\" matcher.\nTEST(LinkTest, TestMatcherAnything) {\n  Mock mock;\n\n  ON_CALL(mock, VoidFromString(_)).WillByDefault(Return());\n}\n\n// Tests the linkage of the A matcher.\nTEST(LinkTest, TestMatcherA) {\n  Mock mock;\n\n  ON_CALL(mock, VoidFromString(A<char*>())).WillByDefault(Return());\n}\n\n// Tests the linkage of the Eq and the \"bare value\" matcher.\nTEST(LinkTest, TestMatchersEq) {\n  Mock mock;\n  const char* p = \"x\";\n\n  ON_CALL(mock, VoidFromString(Eq(p))).WillByDefault(Return());\n  ON_CALL(mock, VoidFromString(const_cast<char*>(\"y\"))).WillByDefault(Return());\n}\n\n// Tests the linkage of the Lt, Gt, Le, Ge, and Ne matchers.\nTEST(LinkTest, TestMatchersRelations) {\n  Mock mock;\n\n  ON_CALL(mock, VoidFromFloat(Lt(1.0f))).WillByDefault(Return());\n  ON_CALL(mock, VoidFromFloat(Gt(1.0f))).WillByDefault(Return());\n  ON_CALL(mock, VoidFromFloat(Le(1.0f))).WillByDefault(Return());\n  ON_CALL(mock, VoidFromFloat(Ge(1.0f))).WillByDefault(Return());\n  ON_CALL(mock, VoidFromFloat(Ne(1.0f))).WillByDefault(Return());\n}\n\n// Tests the linkage of the NotNull matcher.\nTEST(LinkTest, TestMatcherNotNull) {\n  Mock mock;\n\n  ON_CALL(mock, VoidFromString(NotNull())).WillByDefault(Return());\n}\n\n// Tests the linkage of the IsNull matcher.\nTEST(LinkTest, TestMatcherIsNull) {\n  Mock mock;\n\n  ON_CALL(mock, VoidFromString(IsNull())).WillByDefault(Return());\n}\n\n// Tests the linkage of the Ref matcher.\nTEST(LinkTest, TestMatcherRef) {\n  Mock mock;\n  int a = 0;\n\n  ON_CALL(mock, VoidFromIntRef(Ref(a))).WillByDefault(Return());\n}\n\n// Tests the linkage of the TypedEq matcher.\nTEST(LinkTest, TestMatcherTypedEq) {\n  Mock mock;\n  long a = 0;\n\n  ON_CALL(mock, VoidFromIntRef(TypedEq<int&>(a))).WillByDefault(Return());\n}\n\n// Tests the linkage of the FloatEq, DoubleEq, NanSensitiveFloatEq and\n// NanSensitiveDoubleEq matchers.\nTEST(LinkTest, TestMatchersFloatingPoint) {\n  Mock mock;\n  float a = 0;\n\n  ON_CALL(mock, VoidFromFloat(FloatEq(a))).WillByDefault(Return());\n  ON_CALL(mock, VoidFromDouble(DoubleEq(a))).WillByDefault(Return());\n  ON_CALL(mock, VoidFromFloat(NanSensitiveFloatEq(a))).WillByDefault(Return());\n  ON_CALL(mock, VoidFromDouble(NanSensitiveDoubleEq(a)))\n      .WillByDefault(Return());\n}\n\n// Tests the linkage of the ContainsRegex matcher.\nTEST(LinkTest, TestMatcherContainsRegex) {\n  Mock mock;\n\n  ON_CALL(mock, VoidFromString(ContainsRegex(\".*\"))).WillByDefault(Return());\n}\n\n// Tests the linkage of the MatchesRegex matcher.\nTEST(LinkTest, TestMatcherMatchesRegex) {\n  Mock mock;\n\n  ON_CALL(mock, VoidFromString(MatchesRegex(\".*\"))).WillByDefault(Return());\n}\n\n// Tests the linkage of the StartsWith, EndsWith, and HasSubstr matchers.\nTEST(LinkTest, TestMatchersSubstrings) {\n  Mock mock;\n\n  ON_CALL(mock, VoidFromString(StartsWith(\"a\"))).WillByDefault(Return());\n  ON_CALL(mock, VoidFromString(EndsWith(\"c\"))).WillByDefault(Return());\n  ON_CALL(mock, VoidFromString(HasSubstr(\"b\"))).WillByDefault(Return());\n}\n\n// Tests the linkage of the StrEq, StrNe, StrCaseEq, and StrCaseNe matchers.\nTEST(LinkTest, TestMatchersStringEquality) {\n  Mock mock;\n  ON_CALL(mock, VoidFromString(StrEq(\"a\"))).WillByDefault(Return());\n  ON_CALL(mock, VoidFromString(StrNe(\"a\"))).WillByDefault(Return());\n  ON_CALL(mock, VoidFromString(StrCaseEq(\"a\"))).WillByDefault(Return());\n  ON_CALL(mock, VoidFromString(StrCaseNe(\"a\"))).WillByDefault(Return());\n}\n\n// Tests the linkage of the ElementsAre matcher.\nTEST(LinkTest, TestMatcherElementsAre) {\n  Mock mock;\n\n  ON_CALL(mock, VoidFromVector(ElementsAre('a', _))).WillByDefault(Return());\n}\n\n// Tests the linkage of the ElementsAreArray matcher.\nTEST(LinkTest, TestMatcherElementsAreArray) {\n  Mock mock;\n  char arr[] = {'a', 'b'};\n\n  ON_CALL(mock, VoidFromVector(ElementsAreArray(arr))).WillByDefault(Return());\n}\n\n// Tests the linkage of the IsSubsetOf matcher.\nTEST(LinkTest, TestMatcherIsSubsetOf) {\n  Mock mock;\n  char arr[] = {'a', 'b'};\n\n  ON_CALL(mock, VoidFromVector(IsSubsetOf(arr))).WillByDefault(Return());\n}\n\n// Tests the linkage of the IsSupersetOf matcher.\nTEST(LinkTest, TestMatcherIsSupersetOf) {\n  Mock mock;\n  char arr[] = {'a', 'b'};\n\n  ON_CALL(mock, VoidFromVector(IsSupersetOf(arr))).WillByDefault(Return());\n}\n\n// Tests the linkage of the ContainerEq matcher.\nTEST(LinkTest, TestMatcherContainerEq) {\n  Mock mock;\n  std::vector<int> v;\n\n  ON_CALL(mock, VoidFromVector(ContainerEq(v))).WillByDefault(Return());\n}\n\n// Tests the linkage of the Field matcher.\nTEST(LinkTest, TestMatcherField) {\n  FieldHelper helper(0);\n\n  Matcher<const FieldHelper&> m = Field(&FieldHelper::field_, Eq(0));\n  EXPECT_TRUE(m.Matches(helper));\n\n  Matcher<const FieldHelper*> m2 = Field(&FieldHelper::field_, Eq(0));\n  EXPECT_TRUE(m2.Matches(&helper));\n}\n\n// Tests the linkage of the Property matcher.\nTEST(LinkTest, TestMatcherProperty) {\n  FieldHelper helper(0);\n\n  Matcher<const FieldHelper&> m = Property(&FieldHelper::field, Eq(0));\n  EXPECT_TRUE(m.Matches(helper));\n\n  Matcher<const FieldHelper*> m2 = Property(&FieldHelper::field, Eq(0));\n  EXPECT_TRUE(m2.Matches(&helper));\n}\n\n// Tests the linkage of the ResultOf matcher.\nTEST(LinkTest, TestMatcherResultOf) {\n  Matcher<char*> m = ResultOf(&InvokeHelper::StaticIntFromString, Eq(1));\n  EXPECT_TRUE(m.Matches(nullptr));\n}\n\n// Tests the linkage of the ResultOf matcher.\nTEST(LinkTest, TestMatcherPointee) {\n  int n = 1;\n\n  Matcher<int*> m = Pointee(Eq(1));\n  EXPECT_TRUE(m.Matches(&n));\n}\n\n// Tests the linkage of the Truly matcher.\nTEST(LinkTest, TestMatcherTruly) {\n  Matcher<const char*> m = Truly(&InvokeHelper::StaticBoolFromString);\n  EXPECT_TRUE(m.Matches(nullptr));\n}\n\n// Tests the linkage of the AllOf matcher.\nTEST(LinkTest, TestMatcherAllOf) {\n  Matcher<int> m = AllOf(_, Eq(1));\n  EXPECT_TRUE(m.Matches(1));\n}\n\n// Tests the linkage of the AnyOf matcher.\nTEST(LinkTest, TestMatcherAnyOf) {\n  Matcher<int> m = AnyOf(_, Eq(1));\n  EXPECT_TRUE(m.Matches(1));\n}\n\n// Tests the linkage of the Not matcher.\nTEST(LinkTest, TestMatcherNot) {\n  Matcher<int> m = Not(_);\n  EXPECT_FALSE(m.Matches(1));\n}\n\n// Tests the linkage of the MatcherCast<T>() function.\nTEST(LinkTest, TestMatcherCast) {\n  Matcher<const char*> m = MatcherCast<const char*>(_);\n  EXPECT_TRUE(m.Matches(nullptr));\n}\n\n#endif  // GOOGLEMOCK_TEST_GMOCK_LINK_TEST_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock_output_test.py",
    "content": "#!/usr/bin/env python\n#\n# Copyright 2008, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nr\"\"\"Tests the text output of Google C++ Mocking Framework.\n\nTo update the golden file:\ngmock_output_test.py --build_dir=BUILD/DIR --gengolden\nwhere BUILD/DIR contains the built gmock_output_test_ file.\ngmock_output_test.py --gengolden\ngmock_output_test.py\n\n\"\"\"\n\nfrom io import open    # pylint: disable=redefined-builtin, g-importing-member\nimport os\nimport re\nimport sys\nfrom googlemock.test import gmock_test_utils\n\n\n# The flag for generating the golden file\nGENGOLDEN_FLAG = '--gengolden'\n\nPROGRAM_PATH = gmock_test_utils.GetTestExecutablePath('gmock_output_test_')\nCOMMAND = [PROGRAM_PATH, '--gtest_stack_trace_depth=0', '--gtest_print_time=0']\nGOLDEN_NAME = 'gmock_output_test_golden.txt'\nGOLDEN_PATH = os.path.join(gmock_test_utils.GetSourceDir(), GOLDEN_NAME)\n\n\ndef ToUnixLineEnding(s):\n  \"\"\"Changes all Windows/Mac line endings in s to UNIX line endings.\"\"\"\n\n  return s.replace('\\r\\n', '\\n').replace('\\r', '\\n')\n\n\ndef RemoveReportHeaderAndFooter(output):\n  \"\"\"Removes Google Test result report's header and footer from the output.\"\"\"\n\n  output = re.sub(r'.*gtest_main.*\\n', '', output)\n  output = re.sub(r'\\[.*\\d+ tests.*\\n', '', output)\n  output = re.sub(r'\\[.* test environment .*\\n', '', output)\n  output = re.sub(r'\\[=+\\] \\d+ tests .* ran.*', '', output)\n  output = re.sub(r'.* FAILED TESTS\\n', '', output)\n  return output\n\n\ndef RemoveLocations(output):\n  \"\"\"Removes all file location info from a Google Test program's output.\n\n  Args:\n       output:  the output of a Google Test program.\n\n  Returns:\n       output with all file location info (in the form of\n       'DIRECTORY/FILE_NAME:LINE_NUMBER: 'or\n       'DIRECTORY\\\\FILE_NAME(LINE_NUMBER): ') replaced by\n       'FILE:#: '.\n  \"\"\"\n\n  return re.sub(r'.*[/\\\\](.+)(\\:\\d+|\\(\\d+\\))\\:', 'FILE:#:', output)\n\n\ndef NormalizeErrorMarker(output):\n  \"\"\"Normalizes the error marker, which is different on Windows vs on Linux.\"\"\"\n\n  return re.sub(r' error: ', ' Failure\\n', output)\n\n\ndef RemoveMemoryAddresses(output):\n  \"\"\"Removes memory addresses from the test output.\"\"\"\n\n  return re.sub(r'@\\w+', '@0x#', output)\n\n\ndef RemoveTestNamesOfLeakedMocks(output):\n  \"\"\"Removes the test names of leaked mock objects from the test output.\"\"\"\n\n  return re.sub(r'\\(used in test .+\\) ', '', output)\n\n\ndef GetLeakyTests(output):\n  \"\"\"Returns a list of test names that leak mock objects.\"\"\"\n\n  # findall() returns a list of all matches of the regex in output.\n  # For example, if '(used in test FooTest.Bar)' is in output, the\n  # list will contain 'FooTest.Bar'.\n  return re.findall(r'\\(used in test (.+)\\)', output)\n\n\ndef GetNormalizedOutputAndLeakyTests(output):\n  \"\"\"Normalizes the output of gmock_output_test_.\n\n  Args:\n    output: The test output.\n\n  Returns:\n    A tuple (the normalized test output, the list of test names that have\n    leaked mocks).\n  \"\"\"\n\n  output = ToUnixLineEnding(output)\n  output = RemoveReportHeaderAndFooter(output)\n  output = NormalizeErrorMarker(output)\n  output = RemoveLocations(output)\n  output = RemoveMemoryAddresses(output)\n  return (RemoveTestNamesOfLeakedMocks(output), GetLeakyTests(output))\n\n\ndef GetShellCommandOutput(cmd):\n  \"\"\"Runs a command in a sub-process, and returns its STDOUT in a string.\"\"\"\n\n  return gmock_test_utils.Subprocess(cmd, capture_stderr=False).output\n\n\ndef GetNormalizedCommandOutputAndLeakyTests(cmd):\n  \"\"\"Runs a command and returns its normalized output and a list of leaky tests.\n\n  Args:\n    cmd:  the shell command.\n  \"\"\"\n\n  # Disables exception pop-ups on Windows.\n  os.environ['GTEST_CATCH_EXCEPTIONS'] = '1'\n  return GetNormalizedOutputAndLeakyTests(GetShellCommandOutput(cmd))\n\n\nclass GMockOutputTest(gmock_test_utils.TestCase):\n\n  def testOutput(self):\n    (output, leaky_tests) = GetNormalizedCommandOutputAndLeakyTests(COMMAND)\n    golden_file = open(GOLDEN_PATH, 'rb')\n    golden = golden_file.read().decode('utf-8')\n    golden_file.close()\n\n    # The normalized output should match the golden file.\n    self.assertEqual(golden, output)\n\n    # The raw output should contain 2 leaked mock object errors for\n    # test GMockOutputTest.CatchesLeakedMocks.\n    self.assertEqual(['GMockOutputTest.CatchesLeakedMocks',\n                      'GMockOutputTest.CatchesLeakedMocks'],\n                     leaky_tests)\n\n\nif __name__ == '__main__':\n  if sys.argv[1:] == [GENGOLDEN_FLAG]:\n    (output, _) = GetNormalizedCommandOutputAndLeakyTests(COMMAND)\n    golden_file = open(GOLDEN_PATH, 'wb')\n    golden_file.write(output)\n    golden_file.close()\n    # Suppress the error \"googletest was imported but a call to its main()\n    # was never detected.\"\n    os._exit(0)\n  else:\n    gmock_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock_output_test_.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Tests Google Mock's output in various scenarios.  This ensures that\n// Google Mock's messages are readable and useful.\n\n#include <stdio.h>\n\n#include <string>\n\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n\n// Silence C4100 (unreferenced formal parameter)\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 4100)\n#endif\n\nusing testing::_;\nusing testing::AnyNumber;\nusing testing::Ge;\nusing testing::InSequence;\nusing testing::NaggyMock;\nusing testing::Ref;\nusing testing::Return;\nusing testing::Sequence;\nusing testing::Value;\n\nclass MockFoo {\n public:\n  MockFoo() {}\n\n  MOCK_METHOD3(Bar, char(const std::string& s, int i, double x));\n  MOCK_METHOD2(Bar2, bool(int x, int y));\n  MOCK_METHOD2(Bar3, void(int x, int y));\n\n private:\n  MockFoo(const MockFoo&) = delete;\n  MockFoo& operator=(const MockFoo&) = delete;\n};\n\nclass GMockOutputTest : public testing::Test {\n protected:\n  NaggyMock<MockFoo> foo_;\n};\n\nTEST_F(GMockOutputTest, ExpectedCall) {\n  GMOCK_FLAG_SET(verbose, \"info\");\n\n  EXPECT_CALL(foo_, Bar2(0, _));\n  foo_.Bar2(0, 0);  // Expected call\n\n  GMOCK_FLAG_SET(verbose, \"warning\");\n}\n\nTEST_F(GMockOutputTest, ExpectedCallToVoidFunction) {\n  GMOCK_FLAG_SET(verbose, \"info\");\n\n  EXPECT_CALL(foo_, Bar3(0, _));\n  foo_.Bar3(0, 0);  // Expected call\n\n  GMOCK_FLAG_SET(verbose, \"warning\");\n}\n\nTEST_F(GMockOutputTest, ExplicitActionsRunOut) {\n  EXPECT_CALL(foo_, Bar2(_, _)).Times(2).WillOnce(Return(false));\n  foo_.Bar2(2, 2);\n  foo_.Bar2(1, 1);  // Explicit actions in EXPECT_CALL run out.\n}\n\nTEST_F(GMockOutputTest, UnexpectedCall) {\n  EXPECT_CALL(foo_, Bar2(0, _));\n\n  foo_.Bar2(1, 0);  // Unexpected call\n  foo_.Bar2(0, 0);  // Expected call\n}\n\nTEST_F(GMockOutputTest, UnexpectedCallToVoidFunction) {\n  EXPECT_CALL(foo_, Bar3(0, _));\n\n  foo_.Bar3(1, 0);  // Unexpected call\n  foo_.Bar3(0, 0);  // Expected call\n}\n\nTEST_F(GMockOutputTest, ExcessiveCall) {\n  EXPECT_CALL(foo_, Bar2(0, _));\n\n  foo_.Bar2(0, 0);  // Expected call\n  foo_.Bar2(0, 1);  // Excessive call\n}\n\nTEST_F(GMockOutputTest, ExcessiveCallToVoidFunction) {\n  EXPECT_CALL(foo_, Bar3(0, _));\n\n  foo_.Bar3(0, 0);  // Expected call\n  foo_.Bar3(0, 1);  // Excessive call\n}\n\nTEST_F(GMockOutputTest, UninterestingCall) {\n  foo_.Bar2(0, 1);  // Uninteresting call\n}\n\nTEST_F(GMockOutputTest, UninterestingCallToVoidFunction) {\n  foo_.Bar3(0, 1);  // Uninteresting call\n}\n\nTEST_F(GMockOutputTest, RetiredExpectation) {\n  EXPECT_CALL(foo_, Bar2(_, _)).RetiresOnSaturation();\n  EXPECT_CALL(foo_, Bar2(0, 0));\n\n  foo_.Bar2(1, 1);\n  foo_.Bar2(1, 1);  // Matches a retired expectation\n  foo_.Bar2(0, 0);\n}\n\nTEST_F(GMockOutputTest, UnsatisfiedPrerequisite) {\n  {\n    InSequence s;\n    EXPECT_CALL(foo_, Bar(_, 0, _));\n    EXPECT_CALL(foo_, Bar2(0, 0));\n    EXPECT_CALL(foo_, Bar2(1, _));\n  }\n\n  foo_.Bar2(1, 0);  // Has one immediate unsatisfied pre-requisite\n  foo_.Bar(\"Hi\", 0, 0);\n  foo_.Bar2(0, 0);\n  foo_.Bar2(1, 0);\n}\n\nTEST_F(GMockOutputTest, UnsatisfiedPrerequisites) {\n  Sequence s1, s2;\n\n  EXPECT_CALL(foo_, Bar(_, 0, _)).InSequence(s1);\n  EXPECT_CALL(foo_, Bar2(0, 0)).InSequence(s2);\n  EXPECT_CALL(foo_, Bar2(1, _)).InSequence(s1, s2);\n\n  foo_.Bar2(1, 0);  // Has two immediate unsatisfied pre-requisites\n  foo_.Bar(\"Hi\", 0, 0);\n  foo_.Bar2(0, 0);\n  foo_.Bar2(1, 0);\n}\n\nTEST_F(GMockOutputTest, UnsatisfiedWith) {\n  EXPECT_CALL(foo_, Bar2(_, _)).With(Ge());\n}\n\nTEST_F(GMockOutputTest, UnsatisfiedExpectation) {\n  EXPECT_CALL(foo_, Bar(_, _, _));\n  EXPECT_CALL(foo_, Bar2(0, _)).Times(2);\n\n  foo_.Bar2(0, 1);\n}\n\nTEST_F(GMockOutputTest, MismatchArguments) {\n  const std::string s = \"Hi\";\n  EXPECT_CALL(foo_, Bar(Ref(s), _, Ge(0)));\n\n  foo_.Bar(\"Ho\", 0, -0.1);  // Mismatch arguments\n  foo_.Bar(s, 0, 0);\n}\n\nTEST_F(GMockOutputTest, MismatchWith) {\n  EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))).With(Ge());\n\n  foo_.Bar2(2, 3);  // Mismatch With()\n  foo_.Bar2(2, 1);\n}\n\nTEST_F(GMockOutputTest, MismatchArgumentsAndWith) {\n  EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1))).With(Ge());\n\n  foo_.Bar2(1, 3);  // Mismatch arguments and mismatch With()\n  foo_.Bar2(2, 1);\n}\n\nTEST_F(GMockOutputTest, UnexpectedCallWithDefaultAction) {\n  ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true));   // Default action #1\n  ON_CALL(foo_, Bar2(1, _)).WillByDefault(Return(false));  // Default action #2\n\n  EXPECT_CALL(foo_, Bar2(2, 2));\n  foo_.Bar2(1, 0);  // Unexpected call, takes default action #2.\n  foo_.Bar2(0, 0);  // Unexpected call, takes default action #1.\n  foo_.Bar2(2, 2);  // Expected call.\n}\n\nTEST_F(GMockOutputTest, ExcessiveCallWithDefaultAction) {\n  ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true));   // Default action #1\n  ON_CALL(foo_, Bar2(1, _)).WillByDefault(Return(false));  // Default action #2\n\n  EXPECT_CALL(foo_, Bar2(2, 2));\n  EXPECT_CALL(foo_, Bar2(1, 1));\n\n  foo_.Bar2(2, 2);  // Expected call.\n  foo_.Bar2(2, 2);  // Excessive call, takes default action #1.\n  foo_.Bar2(1, 1);  // Expected call.\n  foo_.Bar2(1, 1);  // Excessive call, takes default action #2.\n}\n\nTEST_F(GMockOutputTest, UninterestingCallWithDefaultAction) {\n  ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true));   // Default action #1\n  ON_CALL(foo_, Bar2(1, _)).WillByDefault(Return(false));  // Default action #2\n\n  foo_.Bar2(2, 2);  // Uninteresting call, takes default action #1.\n  foo_.Bar2(1, 1);  // Uninteresting call, takes default action #2.\n}\n\nTEST_F(GMockOutputTest, ExplicitActionsRunOutWithDefaultAction) {\n  ON_CALL(foo_, Bar2(_, _)).WillByDefault(Return(true));  // Default action #1\n\n  EXPECT_CALL(foo_, Bar2(_, _)).Times(2).WillOnce(Return(false));\n  foo_.Bar2(2, 2);\n  foo_.Bar2(1, 1);  // Explicit actions in EXPECT_CALL run out.\n}\n\nTEST_F(GMockOutputTest, CatchesLeakedMocks) {\n  MockFoo* foo1 = new MockFoo;\n  MockFoo* foo2 = new MockFoo;\n\n  // Invokes ON_CALL on foo1.\n  ON_CALL(*foo1, Bar(_, _, _)).WillByDefault(Return('a'));\n\n  // Invokes EXPECT_CALL on foo2.\n  EXPECT_CALL(*foo2, Bar2(_, _));\n  EXPECT_CALL(*foo2, Bar2(1, _));\n  EXPECT_CALL(*foo2, Bar3(_, _)).Times(AnyNumber());\n  foo2->Bar2(2, 1);\n  foo2->Bar2(1, 1);\n\n  // Both foo1 and foo2 are deliberately leaked.\n}\n\nMATCHER_P2(IsPair, first, second, \"\") {\n  return Value(arg.first, first) && Value(arg.second, second);\n}\n\nTEST_F(GMockOutputTest, PrintsMatcher) {\n  const testing::Matcher<int> m1 = Ge(48);\n  EXPECT_THAT((std::pair<int, bool>(42, true)), IsPair(m1, true));\n}\n\nvoid TestCatchesLeakedMocksInAdHocTests() {\n  MockFoo* foo = new MockFoo;\n\n  // Invokes EXPECT_CALL on foo.\n  EXPECT_CALL(*foo, Bar2(_, _));\n  foo->Bar2(2, 1);\n\n  // foo is deliberately leaked.\n}\n\nint main(int argc, char** argv) {\n  testing::InitGoogleMock(&argc, argv);\n  // Ensures that the tests pass no matter what value of\n  // --gmock_catch_leaked_mocks and --gmock_verbose the user specifies.\n  GMOCK_FLAG_SET(catch_leaked_mocks, true);\n  GMOCK_FLAG_SET(verbose, \"warning\");\n\n  TestCatchesLeakedMocksInAdHocTests();\n  return RUN_ALL_TESTS();\n}\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock_output_test_golden.txt",
    "content": "[ RUN      ] GMockOutputTest.ExpectedCall\n\nFILE:#: EXPECT_CALL(foo_, Bar2(0, _)) invoked\nStack trace:\n\nFILE:#: Mock function call matches EXPECT_CALL(foo_, Bar2(0, _))...\n    Function call: Bar2(0, 0)\n          Returns: false\nStack trace:\n[       OK ] GMockOutputTest.ExpectedCall\n[ RUN      ] GMockOutputTest.ExpectedCallToVoidFunction\n\nFILE:#: EXPECT_CALL(foo_, Bar3(0, _)) invoked\nStack trace:\n\nFILE:#: Mock function call matches EXPECT_CALL(foo_, Bar3(0, _))...\n    Function call: Bar3(0, 0)\nStack trace:\n[       OK ] GMockOutputTest.ExpectedCallToVoidFunction\n[ RUN      ] GMockOutputTest.ExplicitActionsRunOut\n\nGMOCK WARNING:\nFILE:#: Too few actions specified in EXPECT_CALL(foo_, Bar2(_, _))...\nExpected to be called twice, but has only 1 WillOnce().\nGMOCK WARNING:\nFILE:#: Actions ran out in EXPECT_CALL(foo_, Bar2(_, _))...\nCalled 2 times, but only 1 WillOnce() is specified - returning default value.\nStack trace:\n[       OK ] GMockOutputTest.ExplicitActionsRunOut\n[ RUN      ] GMockOutputTest.UnexpectedCall\nunknown file: Failure\n\nUnexpected mock function call - returning default value.\n    Function call: Bar2(1, 0)\n          Returns: false\nGoogle Mock tried the following 1 expectation, but it didn't match:\n\nFILE:#: EXPECT_CALL(foo_, Bar2(0, _))...\n  Expected arg #0: is equal to 0\n           Actual: 1\n         Expected: to be called once\n           Actual: never called - unsatisfied and active\n[  FAILED  ] GMockOutputTest.UnexpectedCall\n[ RUN      ] GMockOutputTest.UnexpectedCallToVoidFunction\nunknown file: Failure\n\nUnexpected mock function call - returning directly.\n    Function call: Bar3(1, 0)\nGoogle Mock tried the following 1 expectation, but it didn't match:\n\nFILE:#: EXPECT_CALL(foo_, Bar3(0, _))...\n  Expected arg #0: is equal to 0\n           Actual: 1\n         Expected: to be called once\n           Actual: never called - unsatisfied and active\n[  FAILED  ] GMockOutputTest.UnexpectedCallToVoidFunction\n[ RUN      ] GMockOutputTest.ExcessiveCall\nFILE:#: Failure\nMock function called more times than expected - returning default value.\n    Function call: Bar2(0, 1)\n          Returns: false\n         Expected: to be called once\n           Actual: called twice - over-saturated and active\n[  FAILED  ] GMockOutputTest.ExcessiveCall\n[ RUN      ] GMockOutputTest.ExcessiveCallToVoidFunction\nFILE:#: Failure\nMock function called more times than expected - returning directly.\n    Function call: Bar3(0, 1)\n         Expected: to be called once\n           Actual: called twice - over-saturated and active\n[  FAILED  ] GMockOutputTest.ExcessiveCallToVoidFunction\n[ RUN      ] GMockOutputTest.UninterestingCall\n\nGMOCK WARNING:\nUninteresting mock function call - returning default value.\n    Function call: Bar2(0, 1)\n          Returns: false\nNOTE: You can safely ignore the above warning unless this call should not happen.  Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call.  See https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md#knowing-when-to-expect for details.\n[       OK ] GMockOutputTest.UninterestingCall\n[ RUN      ] GMockOutputTest.UninterestingCallToVoidFunction\n\nGMOCK WARNING:\nUninteresting mock function call - returning directly.\n    Function call: Bar3(0, 1)\nNOTE: You can safely ignore the above warning unless this call should not happen.  Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call.  See https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md#knowing-when-to-expect for details.\n[       OK ] GMockOutputTest.UninterestingCallToVoidFunction\n[ RUN      ] GMockOutputTest.RetiredExpectation\nunknown file: Failure\n\nUnexpected mock function call - returning default value.\n    Function call: Bar2(1, 1)\n          Returns: false\nGoogle Mock tried the following 2 expectations, but none matched:\n\nFILE:#: tried expectation #0: EXPECT_CALL(foo_, Bar2(_, _))...\n         Expected: the expectation is active\n           Actual: it is retired\n         Expected: to be called once\n           Actual: called once - saturated and retired\nFILE:#: tried expectation #1: EXPECT_CALL(foo_, Bar2(0, 0))...\n  Expected arg #0: is equal to 0\n           Actual: 1\n  Expected arg #1: is equal to 0\n           Actual: 1\n         Expected: to be called once\n           Actual: never called - unsatisfied and active\n[  FAILED  ] GMockOutputTest.RetiredExpectation\n[ RUN      ] GMockOutputTest.UnsatisfiedPrerequisite\nunknown file: Failure\n\nUnexpected mock function call - returning default value.\n    Function call: Bar2(1, 0)\n          Returns: false\nGoogle Mock tried the following 2 expectations, but none matched:\n\nFILE:#: tried expectation #0: EXPECT_CALL(foo_, Bar2(0, 0))...\n  Expected arg #0: is equal to 0\n           Actual: 1\n         Expected: to be called once\n           Actual: never called - unsatisfied and active\nFILE:#: tried expectation #1: EXPECT_CALL(foo_, Bar2(1, _))...\n         Expected: all pre-requisites are satisfied\n           Actual: the following immediate pre-requisites are not satisfied:\nFILE:#: pre-requisite #0\n                   (end of pre-requisites)\n         Expected: to be called once\n           Actual: never called - unsatisfied and active\n[  FAILED  ] GMockOutputTest.UnsatisfiedPrerequisite\n[ RUN      ] GMockOutputTest.UnsatisfiedPrerequisites\nunknown file: Failure\n\nUnexpected mock function call - returning default value.\n    Function call: Bar2(1, 0)\n          Returns: false\nGoogle Mock tried the following 2 expectations, but none matched:\n\nFILE:#: tried expectation #0: EXPECT_CALL(foo_, Bar2(0, 0))...\n  Expected arg #0: is equal to 0\n           Actual: 1\n         Expected: to be called once\n           Actual: never called - unsatisfied and active\nFILE:#: tried expectation #1: EXPECT_CALL(foo_, Bar2(1, _))...\n         Expected: all pre-requisites are satisfied\n           Actual: the following immediate pre-requisites are not satisfied:\nFILE:#: pre-requisite #0\nFILE:#: pre-requisite #1\n                   (end of pre-requisites)\n         Expected: to be called once\n           Actual: never called - unsatisfied and active\n[  FAILED  ] GMockOutputTest.UnsatisfiedPrerequisites\n[ RUN      ] GMockOutputTest.UnsatisfiedWith\nFILE:#: Failure\nActual function call count doesn't match EXPECT_CALL(foo_, Bar2(_, _))...\n    Expected args: are a pair where the first >= the second\n         Expected: to be called once\n           Actual: never called - unsatisfied and active\n[  FAILED  ] GMockOutputTest.UnsatisfiedWith\n[ RUN      ] GMockOutputTest.UnsatisfiedExpectation\nFILE:#: Failure\nActual function call count doesn't match EXPECT_CALL(foo_, Bar2(0, _))...\n         Expected: to be called twice\n           Actual: called once - unsatisfied and active\nFILE:#: Failure\nActual function call count doesn't match EXPECT_CALL(foo_, Bar(_, _, _))...\n         Expected: to be called once\n           Actual: never called - unsatisfied and active\n[  FAILED  ] GMockOutputTest.UnsatisfiedExpectation\n[ RUN      ] GMockOutputTest.MismatchArguments\nunknown file: Failure\n\nUnexpected mock function call - returning default value.\n    Function call: Bar(@0x# \"Ho\", 0, -0.1)\n          Returns: '\\0'\nGoogle Mock tried the following 1 expectation, but it didn't match:\n\nFILE:#: EXPECT_CALL(foo_, Bar(Ref(s), _, Ge(0)))...\n  Expected arg #0: references the variable @0x# \"Hi\"\n           Actual: \"Ho\", which is located @0x#\n  Expected arg #2: is >= 0\n           Actual: -0.1\n         Expected: to be called once\n           Actual: never called - unsatisfied and active\n[  FAILED  ] GMockOutputTest.MismatchArguments\n[ RUN      ] GMockOutputTest.MismatchWith\nunknown file: Failure\n\nUnexpected mock function call - returning default value.\n    Function call: Bar2(2, 3)\n          Returns: false\nGoogle Mock tried the following 1 expectation, but it didn't match:\n\nFILE:#: EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1)))...\n    Expected args: are a pair where the first >= the second\n           Actual: don't match\n         Expected: to be called once\n           Actual: never called - unsatisfied and active\n[  FAILED  ] GMockOutputTest.MismatchWith\n[ RUN      ] GMockOutputTest.MismatchArgumentsAndWith\nunknown file: Failure\n\nUnexpected mock function call - returning default value.\n    Function call: Bar2(1, 3)\n          Returns: false\nGoogle Mock tried the following 1 expectation, but it didn't match:\n\nFILE:#: EXPECT_CALL(foo_, Bar2(Ge(2), Ge(1)))...\n  Expected arg #0: is >= 2\n           Actual: 1\n    Expected args: are a pair where the first >= the second\n           Actual: don't match\n         Expected: to be called once\n           Actual: never called - unsatisfied and active\n[  FAILED  ] GMockOutputTest.MismatchArgumentsAndWith\n[ RUN      ] GMockOutputTest.UnexpectedCallWithDefaultAction\nunknown file: Failure\n\nUnexpected mock function call - taking default action specified at:\nFILE:#:\n    Function call: Bar2(1, 0)\n          Returns: false\nGoogle Mock tried the following 1 expectation, but it didn't match:\n\nFILE:#: EXPECT_CALL(foo_, Bar2(2, 2))...\n  Expected arg #0: is equal to 2\n           Actual: 1\n  Expected arg #1: is equal to 2\n           Actual: 0\n         Expected: to be called once\n           Actual: never called - unsatisfied and active\nunknown file: Failure\n\nUnexpected mock function call - taking default action specified at:\nFILE:#:\n    Function call: Bar2(0, 0)\n          Returns: true\nGoogle Mock tried the following 1 expectation, but it didn't match:\n\nFILE:#: EXPECT_CALL(foo_, Bar2(2, 2))...\n  Expected arg #0: is equal to 2\n           Actual: 0\n  Expected arg #1: is equal to 2\n           Actual: 0\n         Expected: to be called once\n           Actual: never called - unsatisfied and active\n[  FAILED  ] GMockOutputTest.UnexpectedCallWithDefaultAction\n[ RUN      ] GMockOutputTest.ExcessiveCallWithDefaultAction\nFILE:#: Failure\nMock function called more times than expected - taking default action specified at:\nFILE:#:\n    Function call: Bar2(2, 2)\n          Returns: true\n         Expected: to be called once\n           Actual: called twice - over-saturated and active\nFILE:#: Failure\nMock function called more times than expected - taking default action specified at:\nFILE:#:\n    Function call: Bar2(1, 1)\n          Returns: false\n         Expected: to be called once\n           Actual: called twice - over-saturated and active\n[  FAILED  ] GMockOutputTest.ExcessiveCallWithDefaultAction\n[ RUN      ] GMockOutputTest.UninterestingCallWithDefaultAction\n\nGMOCK WARNING:\nUninteresting mock function call - taking default action specified at:\nFILE:#:\n    Function call: Bar2(2, 2)\n          Returns: true\nNOTE: You can safely ignore the above warning unless this call should not happen.  Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call.  See https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md#knowing-when-to-expect for details.\n\nGMOCK WARNING:\nUninteresting mock function call - taking default action specified at:\nFILE:#:\n    Function call: Bar2(1, 1)\n          Returns: false\nNOTE: You can safely ignore the above warning unless this call should not happen.  Do not suppress it by blindly adding an EXPECT_CALL() if you don't mean to enforce the call.  See https://github.com/google/googletest/blob/master/docs/gmock_cook_book.md#knowing-when-to-expect for details.\n[       OK ] GMockOutputTest.UninterestingCallWithDefaultAction\n[ RUN      ] GMockOutputTest.ExplicitActionsRunOutWithDefaultAction\n\nGMOCK WARNING:\nFILE:#: Too few actions specified in EXPECT_CALL(foo_, Bar2(_, _))...\nExpected to be called twice, but has only 1 WillOnce().\nGMOCK WARNING:\nFILE:#: Actions ran out in EXPECT_CALL(foo_, Bar2(_, _))...\nCalled 2 times, but only 1 WillOnce() is specified - taking default action specified at:\nFILE:#:\nStack trace:\n[       OK ] GMockOutputTest.ExplicitActionsRunOutWithDefaultAction\n[ RUN      ] GMockOutputTest.CatchesLeakedMocks\n[       OK ] GMockOutputTest.CatchesLeakedMocks\n[ RUN      ] GMockOutputTest.PrintsMatcher\nFILE:#: Failure\nValue of: (std::pair<int, bool>(42, true))\nExpected: is pair (first: is >= 48, second: true)\n  Actual: (42, true) (of type std::pair<int, bool>)\n[  FAILED  ] GMockOutputTest.PrintsMatcher\n[  FAILED  ] GMockOutputTest.UnexpectedCall\n[  FAILED  ] GMockOutputTest.UnexpectedCallToVoidFunction\n[  FAILED  ] GMockOutputTest.ExcessiveCall\n[  FAILED  ] GMockOutputTest.ExcessiveCallToVoidFunction\n[  FAILED  ] GMockOutputTest.RetiredExpectation\n[  FAILED  ] GMockOutputTest.UnsatisfiedPrerequisite\n[  FAILED  ] GMockOutputTest.UnsatisfiedPrerequisites\n[  FAILED  ] GMockOutputTest.UnsatisfiedWith\n[  FAILED  ] GMockOutputTest.UnsatisfiedExpectation\n[  FAILED  ] GMockOutputTest.MismatchArguments\n[  FAILED  ] GMockOutputTest.MismatchWith\n[  FAILED  ] GMockOutputTest.MismatchArgumentsAndWith\n[  FAILED  ] GMockOutputTest.UnexpectedCallWithDefaultAction\n[  FAILED  ] GMockOutputTest.ExcessiveCallWithDefaultAction\n[  FAILED  ] GMockOutputTest.PrintsMatcher\n\n\nFILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#.\nFILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#.\nFILE:#: ERROR: this mock object should be deleted but never is. Its address is @0x#.\nERROR: 3 leaked mock objects found at program exit. Expectations on a mock object are verified when the object is destructed. Leaking a mock means that its expectations aren't verified, which is usually a test bug. If you really intend to leak a mock, you can suppress this error using testing::Mock::AllowLeak(mock_object), or you may use a fake or stub instead of a mock.\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock_stress_test.cc",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Tests that Google Mock constructs can be used in a large number of\n// threads concurrently.\n\n#include \"gmock/gmock.h\"\n#include \"gtest/gtest.h\"\n\nnamespace testing {\nnamespace {\n\n// From gtest-port.h.\nusing ::testing::internal::ThreadWithParam;\n\n// The maximum number of test threads (not including helper threads)\n// to create.\nconst int kMaxTestThreads = 50;\n\n// How many times to repeat a task in a test thread.\nconst int kRepeat = 50;\n\nclass MockFoo {\n public:\n  MOCK_METHOD1(Bar, int(int n));                                   // NOLINT\n  MOCK_METHOD2(Baz, char(const char* s1, const std::string& s2));  // NOLINT\n};\n\n// Helper for waiting for the given thread to finish and then deleting it.\ntemplate <typename T>\nvoid JoinAndDelete(ThreadWithParam<T>* t) {\n  t->Join();\n  delete t;\n}\n\nstruct Dummy {};\n\n// Tests that different mock objects can be used in their respective\n// threads.  This should generate no Google Test failure.\nvoid TestConcurrentMockObjects(Dummy /* dummy */) {\n  // Creates a mock and does some typical operations on it.\n  MockFoo foo;\n  ON_CALL(foo, Bar(_)).WillByDefault(Return(1));\n  ON_CALL(foo, Baz(_, _)).WillByDefault(Return('b'));\n  ON_CALL(foo, Baz(_, \"you\")).WillByDefault(Return('a'));\n\n  EXPECT_CALL(foo, Bar(0)).Times(AtMost(3));\n  EXPECT_CALL(foo, Baz(_, _));\n  EXPECT_CALL(foo, Baz(\"hi\", \"you\"))\n      .WillOnce(Return('z'))\n      .WillRepeatedly(DoDefault());\n\n  EXPECT_EQ(1, foo.Bar(0));\n  EXPECT_EQ(1, foo.Bar(0));\n  EXPECT_EQ('z', foo.Baz(\"hi\", \"you\"));\n  EXPECT_EQ('a', foo.Baz(\"hi\", \"you\"));\n  EXPECT_EQ('b', foo.Baz(\"hi\", \"me\"));\n}\n\n// Tests invoking methods of the same mock object in multiple threads.\n\nstruct Helper1Param {\n  MockFoo* mock_foo;\n  int* count;\n};\n\nvoid Helper1(Helper1Param param) {\n  for (int i = 0; i < kRepeat; i++) {\n    const char ch = param.mock_foo->Baz(\"a\", \"b\");\n    if (ch == 'a') {\n      // It was an expected call.\n      (*param.count)++;\n    } else {\n      // It was an excessive call.\n      EXPECT_EQ('\\0', ch);\n    }\n\n    // An unexpected call.\n    EXPECT_EQ('\\0', param.mock_foo->Baz(\"x\", \"y\")) << \"Expected failure.\";\n\n    // An uninteresting call.\n    EXPECT_EQ(1, param.mock_foo->Bar(5));\n  }\n}\n\n// This should generate 3*kRepeat + 1 failures in total.\nvoid TestConcurrentCallsOnSameObject(Dummy /* dummy */) {\n  MockFoo foo;\n\n  ON_CALL(foo, Bar(_)).WillByDefault(Return(1));\n  EXPECT_CALL(foo, Baz(_, \"b\")).Times(kRepeat).WillRepeatedly(Return('a'));\n  EXPECT_CALL(foo, Baz(_, \"c\"));  // Expected to be unsatisfied.\n\n  // This chunk of code should generate kRepeat failures about\n  // excessive calls, and 2*kRepeat failures about unexpected calls.\n  int count1 = 0;\n  const Helper1Param param = {&foo, &count1};\n  ThreadWithParam<Helper1Param>* const t =\n      new ThreadWithParam<Helper1Param>(Helper1, param, nullptr);\n\n  int count2 = 0;\n  const Helper1Param param2 = {&foo, &count2};\n  Helper1(param2);\n  JoinAndDelete(t);\n\n  EXPECT_EQ(kRepeat, count1 + count2);\n\n  // foo's destructor should generate one failure about unsatisfied\n  // expectation.\n}\n\n// Tests using the same mock object in multiple threads when the\n// expectations are partially ordered.\n\nvoid Helper2(MockFoo* foo) {\n  for (int i = 0; i < kRepeat; i++) {\n    foo->Bar(2);\n    foo->Bar(3);\n  }\n}\n\n// This should generate no Google Test failures.\nvoid TestPartiallyOrderedExpectationsWithThreads(Dummy /* dummy */) {\n  MockFoo foo;\n  Sequence s1, s2;\n\n  {\n    InSequence dummy;\n    EXPECT_CALL(foo, Bar(0));\n    EXPECT_CALL(foo, Bar(1)).InSequence(s1, s2);\n  }\n\n  EXPECT_CALL(foo, Bar(2))\n      .Times(2 * kRepeat)\n      .InSequence(s1)\n      .RetiresOnSaturation();\n  EXPECT_CALL(foo, Bar(3)).Times(2 * kRepeat).InSequence(s2);\n\n  {\n    InSequence dummy;\n    EXPECT_CALL(foo, Bar(2)).InSequence(s1, s2);\n    EXPECT_CALL(foo, Bar(4));\n  }\n\n  foo.Bar(0);\n  foo.Bar(1);\n\n  ThreadWithParam<MockFoo*>* const t =\n      new ThreadWithParam<MockFoo*>(Helper2, &foo, nullptr);\n  Helper2(&foo);\n  JoinAndDelete(t);\n\n  foo.Bar(2);\n  foo.Bar(4);\n}\n\n// Tests using Google Mock constructs in many threads concurrently.\nTEST(StressTest, CanUseGMockWithThreads) {\n  void (*test_routines[])(Dummy dummy) = {\n      &TestConcurrentMockObjects,\n      &TestConcurrentCallsOnSameObject,\n      &TestPartiallyOrderedExpectationsWithThreads,\n  };\n\n  const int kRoutines = sizeof(test_routines) / sizeof(test_routines[0]);\n  const int kCopiesOfEachRoutine = kMaxTestThreads / kRoutines;\n  const int kTestThreads = kCopiesOfEachRoutine * kRoutines;\n  ThreadWithParam<Dummy>* threads[kTestThreads] = {};\n  for (int i = 0; i < kTestThreads; i++) {\n    // Creates a thread to run the test function.\n    threads[i] = new ThreadWithParam<Dummy>(test_routines[i % kRoutines],\n                                            Dummy(), nullptr);\n    GTEST_LOG_(INFO) << \"Thread #\" << i << \" running . . .\";\n  }\n\n  // At this point, we have many threads running.\n  for (int i = 0; i < kTestThreads; i++) {\n    JoinAndDelete(threads[i]);\n  }\n\n  // Ensures that the correct number of failures have been reported.\n  const TestInfo* const info = UnitTest::GetInstance()->current_test_info();\n  const TestResult& result = *info->result();\n  const int kExpectedFailures = (3 * kRepeat + 1) * kCopiesOfEachRoutine;\n  GTEST_CHECK_(kExpectedFailures == result.total_part_count())\n      << \"Expected \" << kExpectedFailures << \" failures, but got \"\n      << result.total_part_count();\n}\n\n}  // namespace\n}  // namespace testing\n\nint main(int argc, char** argv) {\n  testing::InitGoogleMock(&argc, argv);\n\n  const int exit_code = RUN_ALL_TESTS();  // Expected to fail.\n  GTEST_CHECK_(exit_code != 0) << \"RUN_ALL_TESTS() did not fail as expected\";\n\n  printf(\"\\nPASS\\n\");\n  return 0;\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock_test.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Mock - a framework for writing C++ mock classes.\n//\n// This file tests code in gmock.cc.\n\n#include \"gmock/gmock.h\"\n\n#include <string>\n\n#include \"gtest/gtest.h\"\n#include \"gtest/internal/custom/gtest.h\"\n\n#if !defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n\nusing testing::InitGoogleMock;\n\n// Verifies that calling InitGoogleMock() on argv results in new_argv,\n// and the gmock_verbose flag's value is set to expected_gmock_verbose.\ntemplate <typename Char, int M, int N>\nvoid TestInitGoogleMock(const Char* (&argv)[M], const Char* (&new_argv)[N],\n                        const ::std::string& expected_gmock_verbose) {\n  const ::std::string old_verbose = GMOCK_FLAG_GET(verbose);\n\n  int argc = M - 1;\n  InitGoogleMock(&argc, const_cast<Char**>(argv));\n  ASSERT_EQ(N - 1, argc) << \"The new argv has wrong number of elements.\";\n\n  for (int i = 0; i < N; i++) {\n    EXPECT_STREQ(new_argv[i], argv[i]);\n  }\n\n  EXPECT_EQ(expected_gmock_verbose, GMOCK_FLAG_GET(verbose));\n  GMOCK_FLAG_SET(verbose, old_verbose);  // Restores the gmock_verbose flag.\n}\n\nTEST(InitGoogleMockTest, ParsesInvalidCommandLine) {\n  const char* argv[] = {nullptr};\n\n  const char* new_argv[] = {nullptr};\n\n  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose));\n}\n\nTEST(InitGoogleMockTest, ParsesEmptyCommandLine) {\n  const char* argv[] = {\"foo.exe\", nullptr};\n\n  const char* new_argv[] = {\"foo.exe\", nullptr};\n\n  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose));\n}\n\nTEST(InitGoogleMockTest, ParsesSingleFlag) {\n  const char* argv[] = {\"foo.exe\", \"--gmock_verbose=info\", nullptr};\n\n  const char* new_argv[] = {\"foo.exe\", nullptr};\n\n  TestInitGoogleMock(argv, new_argv, \"info\");\n}\n\nTEST(InitGoogleMockTest, ParsesMultipleFlags) {\n  int old_default_behavior = GMOCK_FLAG_GET(default_mock_behavior);\n  const wchar_t* argv[] = {L\"foo.exe\", L\"--gmock_verbose=info\",\n                           L\"--gmock_default_mock_behavior=2\", nullptr};\n\n  const wchar_t* new_argv[] = {L\"foo.exe\", nullptr};\n\n  TestInitGoogleMock(argv, new_argv, \"info\");\n  EXPECT_EQ(2, GMOCK_FLAG_GET(default_mock_behavior));\n  EXPECT_NE(2, old_default_behavior);\n  GMOCK_FLAG_SET(default_mock_behavior, old_default_behavior);\n}\n\nTEST(InitGoogleMockTest, ParsesUnrecognizedFlag) {\n  const char* argv[] = {\"foo.exe\", \"--non_gmock_flag=blah\", nullptr};\n\n  const char* new_argv[] = {\"foo.exe\", \"--non_gmock_flag=blah\", nullptr};\n\n  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose));\n}\n\nTEST(InitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) {\n  const char* argv[] = {\"foo.exe\", \"--non_gmock_flag=blah\",\n                        \"--gmock_verbose=error\", nullptr};\n\n  const char* new_argv[] = {\"foo.exe\", \"--non_gmock_flag=blah\", nullptr};\n\n  TestInitGoogleMock(argv, new_argv, \"error\");\n}\n\nTEST(WideInitGoogleMockTest, ParsesInvalidCommandLine) {\n  const wchar_t* argv[] = {nullptr};\n\n  const wchar_t* new_argv[] = {nullptr};\n\n  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose));\n}\n\nTEST(WideInitGoogleMockTest, ParsesEmptyCommandLine) {\n  const wchar_t* argv[] = {L\"foo.exe\", nullptr};\n\n  const wchar_t* new_argv[] = {L\"foo.exe\", nullptr};\n\n  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose));\n}\n\nTEST(WideInitGoogleMockTest, ParsesSingleFlag) {\n  const wchar_t* argv[] = {L\"foo.exe\", L\"--gmock_verbose=info\", nullptr};\n\n  const wchar_t* new_argv[] = {L\"foo.exe\", nullptr};\n\n  TestInitGoogleMock(argv, new_argv, \"info\");\n}\n\nTEST(WideInitGoogleMockTest, ParsesMultipleFlags) {\n  int old_default_behavior = GMOCK_FLAG_GET(default_mock_behavior);\n  const wchar_t* argv[] = {L\"foo.exe\", L\"--gmock_verbose=info\",\n                           L\"--gmock_default_mock_behavior=2\", nullptr};\n\n  const wchar_t* new_argv[] = {L\"foo.exe\", nullptr};\n\n  TestInitGoogleMock(argv, new_argv, \"info\");\n  EXPECT_EQ(2, GMOCK_FLAG_GET(default_mock_behavior));\n  EXPECT_NE(2, old_default_behavior);\n  GMOCK_FLAG_SET(default_mock_behavior, old_default_behavior);\n}\n\nTEST(WideInitGoogleMockTest, ParsesUnrecognizedFlag) {\n  const wchar_t* argv[] = {L\"foo.exe\", L\"--non_gmock_flag=blah\", nullptr};\n\n  const wchar_t* new_argv[] = {L\"foo.exe\", L\"--non_gmock_flag=blah\", nullptr};\n\n  TestInitGoogleMock(argv, new_argv, GMOCK_FLAG_GET(verbose));\n}\n\nTEST(WideInitGoogleMockTest, ParsesGoogleMockFlagAndUnrecognizedFlag) {\n  const wchar_t* argv[] = {L\"foo.exe\", L\"--non_gmock_flag=blah\",\n                           L\"--gmock_verbose=error\", nullptr};\n\n  const wchar_t* new_argv[] = {L\"foo.exe\", L\"--non_gmock_flag=blah\", nullptr};\n\n  TestInitGoogleMock(argv, new_argv, \"error\");\n}\n\n#endif  // !defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n\n// Makes sure Google Mock flags can be accessed in code.\nTEST(FlagTest, IsAccessibleInCode) {\n  bool dummy =\n      GMOCK_FLAG_GET(catch_leaked_mocks) && GMOCK_FLAG_GET(verbose) == \"\";\n  (void)dummy;  // Avoids the \"unused local variable\" warning.\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googlemock/test/gmock_test_utils.py",
    "content": "# Copyright 2006, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Unit test utilities for Google C++ Mocking Framework.\"\"\"\n\nimport os\n\n# pylint: disable=C6204\nfrom googletest.test import gtest_test_utils\n\n\ndef GetSourceDir():\n  \"\"\"Returns the absolute path of the directory where the .py files are.\"\"\"\n\n  return gtest_test_utils.GetSourceDir()\n\n\ndef GetTestExecutablePath(executable_name):\n  \"\"\"Returns the absolute path of the test binary given its name.\n\n  The function will print a message and abort the program if the resulting file\n  doesn't exist.\n\n  Args:\n    executable_name: name of the test binary that the test script runs.\n\n  Returns:\n    The absolute path of the test binary.\n  \"\"\"\n\n  return gtest_test_utils.GetTestExecutablePath(executable_name)\n\n\ndef GetExitStatus(exit_code):\n  \"\"\"Returns the argument to exit(), or -1 if exit() wasn't called.\n\n  Args:\n    exit_code: the result value of os.system(command).\n  \"\"\"\n\n  if os.name == 'nt':\n    # On Windows, os.WEXITSTATUS() doesn't work and os.system() returns\n    # the argument to exit() directly.\n    return exit_code\n  else:\n    # On Unix, os.WEXITSTATUS() must be used to extract the exit status\n    # from the result of os.system().\n    if os.WIFEXITED(exit_code):\n      return os.WEXITSTATUS(exit_code)\n    else:\n      return -1\n\n\n# Suppresses the \"Invalid const name\" lint complaint\n# pylint: disable-msg=C6409\n\n# Exposes utilities from gtest_test_utils.\nSubprocess = gtest_test_utils.Subprocess\nTestCase = gtest_test_utils.TestCase\nenviron = gtest_test_utils.environ\nSetEnvVar = gtest_test_utils.SetEnvVar\nPREMATURE_EXIT_FILE_ENV_VAR = gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR\n\n# pylint: enable-msg=C6409\n\n\ndef Main():\n  \"\"\"Runs the unit test.\"\"\"\n\n  gtest_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/CMakeLists.txt",
    "content": "########################################################################\n# Note: CMake support is community-based. The maintainers do not use CMake\n# internally.\n#\n# CMake build script for Google Test.\n#\n# To run the tests for Google Test itself on Linux, use 'make test' or\n# ctest.  You can select which tests to run using 'ctest -R regex'.\n# For more options, run 'ctest --help'.\n\n# When other libraries are using a shared version of runtime libraries,\n# Google Test also has to use one.\noption(\n  gtest_force_shared_crt\n  \"Use shared (DLL) run-time lib even when Google Test is built as static lib.\"\n  OFF)\n\noption(gtest_build_tests \"Build all of gtest's own tests.\" OFF)\n\noption(gtest_build_samples \"Build gtest's sample programs.\" OFF)\n\noption(gtest_disable_pthreads \"Disable uses of pthreads in gtest.\" OFF)\n\noption(\n  gtest_hide_internal_symbols\n  \"Build gtest with internal symbols hidden in shared libraries.\"\n  OFF)\n\n# Defines pre_project_set_up_hermetic_build() and set_up_hermetic_build().\ninclude(cmake/hermetic_build.cmake OPTIONAL)\n\nif (COMMAND pre_project_set_up_hermetic_build)\n  pre_project_set_up_hermetic_build()\nendif()\n\n########################################################################\n#\n# Project-wide settings\n\n# Name of the project.\n#\n# CMake files in this project can refer to the root source directory\n# as ${gtest_SOURCE_DIR} and to the root binary directory as\n# ${gtest_BINARY_DIR}.\n# Language \"C\" is required for find_package(Threads).\n\n# Project version:\n\ncmake_minimum_required(VERSION 3.5)\ncmake_policy(SET CMP0048 NEW)\nproject(gtest VERSION ${GOOGLETEST_VERSION} LANGUAGES CXX C)\n\nif (POLICY CMP0063) # Visibility\n  cmake_policy(SET CMP0063 NEW)\nendif (POLICY CMP0063)\n\nif (COMMAND set_up_hermetic_build)\n  set_up_hermetic_build()\nendif()\n\n# These commands only run if this is the main project\nif(CMAKE_PROJECT_NAME STREQUAL \"gtest\" OR CMAKE_PROJECT_NAME STREQUAL \"googletest-distribution\")\n\n  # BUILD_SHARED_LIBS is a standard CMake variable, but we declare it here to\n  # make it prominent in the GUI.\n  option(BUILD_SHARED_LIBS \"Build shared libraries (DLLs).\" OFF)\n\nelse()\n\n  mark_as_advanced(\n    gtest_force_shared_crt\n    gtest_build_tests\n    gtest_build_samples\n    gtest_disable_pthreads\n    gtest_hide_internal_symbols)\n\nendif()\n\n\nif (gtest_hide_internal_symbols)\n  set(CMAKE_CXX_VISIBILITY_PRESET hidden)\n  set(CMAKE_VISIBILITY_INLINES_HIDDEN 1)\nendif()\n\n# Define helper functions and macros used by Google Test.\ninclude(cmake/internal_utils.cmake)\n\nconfig_compiler_and_linker()  # Defined in internal_utils.cmake.\n\n# Needed to set the namespace for both the export targets and the\n# alias libraries\nset(cmake_package_name GTest CACHE INTERNAL \"\")\n\n# Create the CMake package file descriptors.\nif (INSTALL_GTEST)\n  include(CMakePackageConfigHelpers)\n  set(targets_export_name ${cmake_package_name}Targets CACHE INTERNAL \"\")\n  set(generated_dir \"${CMAKE_CURRENT_BINARY_DIR}/generated\" CACHE INTERNAL \"\")\n  set(cmake_files_install_dir \"${CMAKE_INSTALL_LIBDIR}/cmake/${cmake_package_name}\")\n  set(version_file \"${generated_dir}/${cmake_package_name}ConfigVersion.cmake\")\n  write_basic_package_version_file(${version_file} VERSION ${GOOGLETEST_VERSION} COMPATIBILITY AnyNewerVersion)\n  install(EXPORT ${targets_export_name}\n    NAMESPACE ${cmake_package_name}::\n    DESTINATION ${cmake_files_install_dir})\n  set(config_file \"${generated_dir}/${cmake_package_name}Config.cmake\")\n  configure_package_config_file(\"${gtest_SOURCE_DIR}/cmake/Config.cmake.in\"\n    \"${config_file}\" INSTALL_DESTINATION ${cmake_files_install_dir})\n  install(FILES ${version_file} ${config_file}\n    DESTINATION ${cmake_files_install_dir})\nendif()\n\n# Where Google Test's .h files can be found.\nset(gtest_build_include_dirs\n  \"${gtest_SOURCE_DIR}/include\"\n  \"${gtest_SOURCE_DIR}\")\ninclude_directories(${gtest_build_include_dirs})\n\n########################################################################\n#\n# Defines the gtest & gtest_main libraries.  User tests should link\n# with one of them.\n\n# Google Test libraries.  We build them using more strict warnings than what\n# are used for other targets, to ensure that gtest can be compiled by a user\n# aggressive about warnings.\ncxx_library(gtest \"${cxx_strict}\" src/gtest-all.cc)\nset_target_properties(gtest PROPERTIES VERSION ${GOOGLETEST_VERSION})\ncxx_library(gtest_main \"${cxx_strict}\" src/gtest_main.cc)\nset_target_properties(gtest_main PROPERTIES VERSION ${GOOGLETEST_VERSION})\n# If the CMake version supports it, attach header directory information\n# to the targets for when we are part of a parent build (ie being pulled\n# in via add_subdirectory() rather than being a standalone build).\nif (DEFINED CMAKE_VERSION AND NOT \"${CMAKE_VERSION}\" VERSION_LESS \"2.8.11\")\n  string(REPLACE \";\" \"$<SEMICOLON>\" dirs \"${gtest_build_include_dirs}\")\n  target_include_directories(gtest SYSTEM INTERFACE\n    \"$<BUILD_INTERFACE:${dirs}>\"\n    \"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>\")\n  target_include_directories(gtest_main SYSTEM INTERFACE\n    \"$<BUILD_INTERFACE:${dirs}>\"\n    \"$<INSTALL_INTERFACE:$<INSTALL_PREFIX>/${CMAKE_INSTALL_INCLUDEDIR}>\")\nendif()\nif(CMAKE_SYSTEM_NAME MATCHES \"QNX\")\n  target_link_libraries(gtest PUBLIC regex)\nendif()\ntarget_link_libraries(gtest_main PUBLIC gtest)\n\n########################################################################\n#\n# Install rules\ninstall_project(gtest gtest_main)\n\n########################################################################\n#\n# Samples on how to link user tests with gtest or gtest_main.\n#\n# They are not built by default.  To build them, set the\n# gtest_build_samples option to ON.  You can do it by running ccmake\n# or specifying the -Dgtest_build_samples=ON flag when running cmake.\n\nif (gtest_build_samples)\n  cxx_executable(sample1_unittest samples gtest_main samples/sample1.cc)\n  cxx_executable(sample2_unittest samples gtest_main samples/sample2.cc)\n  cxx_executable(sample3_unittest samples gtest_main)\n  cxx_executable(sample4_unittest samples gtest_main samples/sample4.cc)\n  cxx_executable(sample5_unittest samples gtest_main samples/sample1.cc)\n  cxx_executable(sample6_unittest samples gtest_main)\n  cxx_executable(sample7_unittest samples gtest_main)\n  cxx_executable(sample8_unittest samples gtest_main)\n  cxx_executable(sample9_unittest samples gtest)\n  cxx_executable(sample10_unittest samples gtest)\nendif()\n\n########################################################################\n#\n# Google Test's own tests.\n#\n# You can skip this section if you aren't interested in testing\n# Google Test itself.\n#\n# The tests are not built by default.  To build them, set the\n# gtest_build_tests option to ON.  You can do it by running ccmake\n# or specifying the -Dgtest_build_tests=ON flag when running cmake.\n\nif (gtest_build_tests)\n  # This must be set in the root directory for the tests to be run by\n  # 'make test' or ctest.\n  enable_testing()\n\n  ############################################################\n  # C++ tests built with standard compiler flags.\n\n  cxx_test(googletest-death-test-test gtest_main)\n  cxx_test(gtest_environment_test gtest)\n  cxx_test(googletest-filepath-test gtest_main)\n  cxx_test(googletest-listener-test gtest_main)\n  cxx_test(gtest_main_unittest gtest_main)\n  cxx_test(googletest-message-test gtest_main)\n  cxx_test(gtest_no_test_unittest gtest)\n  cxx_test(googletest-options-test gtest_main)\n  cxx_test(googletest-param-test-test gtest\n    test/googletest-param-test2-test.cc)\n  cxx_test(googletest-port-test gtest_main)\n  cxx_test(gtest_pred_impl_unittest gtest_main)\n  cxx_test(gtest_premature_exit_test gtest\n    test/gtest_premature_exit_test.cc)\n  cxx_test(googletest-printers-test gtest_main)\n  cxx_test(gtest_prod_test gtest_main\n    test/production.cc)\n  cxx_test(gtest_repeat_test gtest)\n  cxx_test(gtest_sole_header_test gtest_main)\n  cxx_test(gtest_stress_test gtest)\n  cxx_test(googletest-test-part-test gtest_main)\n  cxx_test(gtest_throw_on_failure_ex_test gtest)\n  cxx_test(gtest-typed-test_test gtest_main\n    test/gtest-typed-test2_test.cc)\n  cxx_test(gtest_unittest gtest_main)\n  cxx_test(gtest-unittest-api_test gtest)\n  cxx_test(gtest_skip_in_environment_setup_test gtest_main)\n  cxx_test(gtest_skip_test gtest_main)\n\n  ############################################################\n  # C++ tests built with non-standard compiler flags.\n\n  # MSVC 7.1 does not support STL with exceptions disabled.\n  if (NOT MSVC OR MSVC_VERSION GREATER 1310)\n    cxx_library(gtest_no_exception \"${cxx_no_exception}\"\n      src/gtest-all.cc)\n    cxx_library(gtest_main_no_exception \"${cxx_no_exception}\"\n      src/gtest-all.cc src/gtest_main.cc)\n  endif()\n  cxx_library(gtest_main_no_rtti \"${cxx_no_rtti}\"\n    src/gtest-all.cc src/gtest_main.cc)\n\n  cxx_test_with_flags(gtest-death-test_ex_nocatch_test\n    \"${cxx_exception} -DGTEST_ENABLE_CATCH_EXCEPTIONS_=0\"\n    gtest test/googletest-death-test_ex_test.cc)\n  cxx_test_with_flags(gtest-death-test_ex_catch_test\n    \"${cxx_exception} -DGTEST_ENABLE_CATCH_EXCEPTIONS_=1\"\n    gtest test/googletest-death-test_ex_test.cc)\n\n  cxx_test_with_flags(gtest_no_rtti_unittest \"${cxx_no_rtti}\"\n    gtest_main_no_rtti test/gtest_unittest.cc)\n\n  cxx_shared_library(gtest_dll \"${cxx_default}\"\n    src/gtest-all.cc src/gtest_main.cc)\n\n  cxx_executable_with_flags(gtest_dll_test_ \"${cxx_default}\"\n    gtest_dll test/gtest_all_test.cc)\n  set_target_properties(gtest_dll_test_\n                        PROPERTIES\n                        COMPILE_DEFINITIONS \"GTEST_LINKED_AS_SHARED_LIBRARY=1\")\n\n  ############################################################\n  # Python tests.\n\n  cxx_executable(googletest-break-on-failure-unittest_ test gtest)\n  py_test(googletest-break-on-failure-unittest)\n\n  py_test(gtest_skip_check_output_test)\n  py_test(gtest_skip_environment_check_output_test)\n\n  # Visual Studio .NET 2003 does not support STL with exceptions disabled.\n  if (NOT MSVC OR MSVC_VERSION GREATER 1310)  # 1310 is Visual Studio .NET 2003\n    cxx_executable_with_flags(\n      googletest-catch-exceptions-no-ex-test_\n      \"${cxx_no_exception}\"\n      gtest_main_no_exception\n      test/googletest-catch-exceptions-test_.cc)\n  endif()\n\n  cxx_executable_with_flags(\n    googletest-catch-exceptions-ex-test_\n    \"${cxx_exception}\"\n    gtest_main\n    test/googletest-catch-exceptions-test_.cc)\n  py_test(googletest-catch-exceptions-test)\n\n  cxx_executable(googletest-color-test_ test gtest)\n  py_test(googletest-color-test)\n\n  cxx_executable(googletest-env-var-test_ test gtest)\n  py_test(googletest-env-var-test)\n\n  cxx_executable(googletest-filter-unittest_ test gtest)\n  py_test(googletest-filter-unittest)\n\n  cxx_executable(gtest_help_test_ test gtest_main)\n  py_test(gtest_help_test)\n\n  cxx_executable(googletest-list-tests-unittest_ test gtest)\n  py_test(googletest-list-tests-unittest)\n\n  cxx_executable(googletest-output-test_ test gtest)\n  py_test(googletest-output-test --no_stacktrace_support)\n\n  cxx_executable(googletest-shuffle-test_ test gtest)\n  py_test(googletest-shuffle-test)\n\n  # MSVC 7.1 does not support STL with exceptions disabled.\n  if (NOT MSVC OR MSVC_VERSION GREATER 1310)\n    cxx_executable(googletest-throw-on-failure-test_ test gtest_no_exception)\n    set_target_properties(googletest-throw-on-failure-test_\n      PROPERTIES\n      COMPILE_FLAGS \"${cxx_no_exception}\")\n    py_test(googletest-throw-on-failure-test)\n  endif()\n\n  cxx_executable(googletest-uninitialized-test_ test gtest)\n  py_test(googletest-uninitialized-test)\n\n  cxx_executable(gtest_list_output_unittest_ test gtest)\n  py_test(gtest_list_output_unittest)\n\n  cxx_executable(gtest_xml_outfile1_test_ test gtest_main)\n  cxx_executable(gtest_xml_outfile2_test_ test gtest_main)\n  py_test(gtest_xml_outfiles_test)\n  py_test(googletest-json-outfiles-test)\n\n  cxx_executable(gtest_xml_output_unittest_ test gtest)\n  py_test(gtest_xml_output_unittest --no_stacktrace_support)\n  py_test(googletest-json-output-unittest --no_stacktrace_support)\nendif()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/README.md",
    "content": "### Generic Build Instructions\n\n#### Setup\n\nTo build GoogleTest and your tests that use it, you need to tell your build\nsystem where to find its headers and source files. The exact way to do it\ndepends on which build system you use, and is usually straightforward.\n\n### Build with CMake\n\nGoogleTest comes with a CMake build script\n([CMakeLists.txt](https://github.com/google/googletest/blob/master/CMakeLists.txt))\nthat can be used on a wide range of platforms (\"C\" stands for cross-platform.).\nIf you don't have CMake installed already, you can download it for free from\n<http://www.cmake.org/>.\n\nCMake works by generating native makefiles or build projects that can be used in\nthe compiler environment of your choice. You can either build GoogleTest as a\nstandalone project or it can be incorporated into an existing CMake build for\nanother project.\n\n#### Standalone CMake Project\n\nWhen building GoogleTest as a standalone project, the typical workflow starts\nwith\n\n```\ngit clone https://github.com/google/googletest.git -b release-1.11.0\ncd googletest        # Main directory of the cloned repository.\nmkdir build          # Create a directory to hold the build output.\ncd build\ncmake ..             # Generate native build scripts for GoogleTest.\n```\n\nThe above command also includes GoogleMock by default. And so, if you want to\nbuild only GoogleTest, you should replace the last command with\n\n```\ncmake .. -DBUILD_GMOCK=OFF\n```\n\nIf you are on a \\*nix system, you should now see a Makefile in the current\ndirectory. Just type `make` to build GoogleTest. And then you can simply install\nGoogleTest if you are a system administrator.\n\n```\nmake\nsudo make install    # Install in /usr/local/ by default\n```\n\nIf you use Windows and have Visual Studio installed, a `gtest.sln` file and\nseveral `.vcproj` files will be created. You can then build them using Visual\nStudio.\n\nOn Mac OS X with Xcode installed, a `.xcodeproj` file will be generated.\n\n#### Incorporating Into An Existing CMake Project\n\nIf you want to use GoogleTest in a project which already uses CMake, the easiest\nway is to get installed libraries and headers.\n\n*   Import GoogleTest by using `find_package` (or `pkg_check_modules`). For\n    example, if `find_package(GTest CONFIG REQUIRED)` succeeds, you can use the\n    libraries as `GTest::gtest`, `GTest::gmock`.\n\nAnd a more robust and flexible approach is to build GoogleTest as part of that\nproject directly. This is done by making the GoogleTest source code available to\nthe main build and adding it using CMake's `add_subdirectory()` command. This\nhas the significant advantage that the same compiler and linker settings are\nused between GoogleTest and the rest of your project, so issues associated with\nusing incompatible libraries (eg debug/release), etc. are avoided. This is\nparticularly useful on Windows. Making GoogleTest's source code available to the\nmain build can be done a few different ways:\n\n*   Download the GoogleTest source code manually and place it at a known\n    location. This is the least flexible approach and can make it more difficult\n    to use with continuous integration systems, etc.\n*   Embed the GoogleTest source code as a direct copy in the main project's\n    source tree. This is often the simplest approach, but is also the hardest to\n    keep up to date. Some organizations may not permit this method.\n*   Add GoogleTest as a git submodule or equivalent. This may not always be\n    possible or appropriate. Git submodules, for example, have their own set of\n    advantages and drawbacks.\n*   Use CMake to download GoogleTest as part of the build's configure step. This\n    approach doesn't have the limitations of the other methods.\n\nThe last of the above methods is implemented with a small piece of CMake code\nthat downloads and pulls the GoogleTest code into the main build.\n\nJust add to your `CMakeLists.txt`:\n\n```cmake\ninclude(FetchContent)\nFetchContent_Declare(\n  googletest\n  # Specify the commit you depend on and update it regularly.\n  URL https://github.com/google/googletest/archive/e2239ee6043f73722e7aa812a459f54a28552929.zip\n)\n# For Windows: Prevent overriding the parent project's compiler/linker settings\nset(gtest_force_shared_crt ON CACHE BOOL \"\" FORCE)\nFetchContent_MakeAvailable(googletest)\n\n# Now simply link against gtest or gtest_main as needed. Eg\nadd_executable(example example.cpp)\ntarget_link_libraries(example gtest_main)\nadd_test(NAME example_test COMMAND example)\n```\n\nNote that this approach requires CMake 3.14 or later due to its use of the\n`FetchContent_MakeAvailable()` command.\n\n##### Visual Studio Dynamic vs Static Runtimes\n\nBy default, new Visual Studio projects link the C runtimes dynamically but\nGoogleTest links them statically. This will generate an error that looks\nsomething like the following: gtest.lib(gtest-all.obj) : error LNK2038: mismatch\ndetected for 'RuntimeLibrary': value 'MTd_StaticDebug' doesn't match value\n'MDd_DynamicDebug' in main.obj\n\nGoogleTest already has a CMake option for this: `gtest_force_shared_crt`\n\nEnabling this option will make gtest link the runtimes dynamically too, and\nmatch the project in which it is included.\n\n#### C++ Standard Version\n\nAn environment that supports C++11 is required in order to successfully build\nGoogleTest. One way to ensure this is to specify the standard in the top-level\nproject, for example by using the `set(CMAKE_CXX_STANDARD 11)` command. If this\nis not feasible, for example in a C project using GoogleTest for validation,\nthen it can be specified by adding it to the options for cmake via the\n`DCMAKE_CXX_FLAGS` option.\n\n### Tweaking GoogleTest\n\nGoogleTest can be used in diverse environments. The default configuration may\nnot work (or may not work well) out of the box in some environments. However,\nyou can easily tweak GoogleTest by defining control macros on the compiler\ncommand line. Generally, these macros are named like `GTEST_XYZ` and you define\nthem to either 1 or 0 to enable or disable a certain feature.\n\nWe list the most frequently used macros below. For a complete list, see file\n[include/gtest/internal/gtest-port.h](https://github.com/google/googletest/blob/master/googletest/include/gtest/internal/gtest-port.h).\n\n### Multi-threaded Tests\n\nGoogleTest is thread-safe where the pthread library is available. After\n`#include \"gtest/gtest.h\"`, you can check the\n`GTEST_IS_THREADSAFE` macro to see whether this is the case (yes if the macro is\n`#defined` to 1, no if it's undefined.).\n\nIf GoogleTest doesn't correctly detect whether pthread is available in your\nenvironment, you can force it with\n\n    -DGTEST_HAS_PTHREAD=1\n\nor\n\n    -DGTEST_HAS_PTHREAD=0\n\nWhen GoogleTest uses pthread, you may need to add flags to your compiler and/or\nlinker to select the pthread library, or you'll get link errors. If you use the\nCMake script, this is taken care of for you. If you use your own build script,\nyou'll need to read your compiler and linker's manual to figure out what flags\nto add.\n\n### As a Shared Library (DLL)\n\nGoogleTest is compact, so most users can build and link it as a static library\nfor the simplicity. You can choose to use GoogleTest as a shared library (known\nas a DLL on Windows) if you prefer.\n\nTo compile *gtest* as a shared library, add\n\n    -DGTEST_CREATE_SHARED_LIBRARY=1\n\nto the compiler flags. You'll also need to tell the linker to produce a shared\nlibrary instead - consult your linker's manual for how to do it.\n\nTo compile your *tests* that use the gtest shared library, add\n\n    -DGTEST_LINKED_AS_SHARED_LIBRARY=1\n\nto the compiler flags.\n\nNote: while the above steps aren't technically necessary today when using some\ncompilers (e.g. GCC), they may become necessary in the future, if we decide to\nimprove the speed of loading the library (see\n<http://gcc.gnu.org/wiki/Visibility> for details). Therefore you are recommended\nto always add the above flags when using GoogleTest as a shared library.\nOtherwise a future release of GoogleTest may break your build script.\n\n### Avoiding Macro Name Clashes\n\nIn C++, macros don't obey namespaces. Therefore two libraries that both define a\nmacro of the same name will clash if you `#include` both definitions. In case a\nGoogleTest macro clashes with another library, you can force GoogleTest to\nrename its macro to avoid the conflict.\n\nSpecifically, if both GoogleTest and some other code define macro FOO, you can\nadd\n\n    -DGTEST_DONT_DEFINE_FOO=1\n\nto the compiler flags to tell GoogleTest to change the macro's name from `FOO`\nto `GTEST_FOO`. Currently `FOO` can be `ASSERT_EQ`, `ASSERT_FALSE`, `ASSERT_GE`,\n`ASSERT_GT`, `ASSERT_LE`, `ASSERT_LT`, `ASSERT_NE`, `ASSERT_TRUE`,\n`EXPECT_FALSE`, `EXPECT_TRUE`, `FAIL`, `SUCCEED`, `TEST`, or `TEST_F`. For\nexample, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll need to write\n\n    GTEST_TEST(SomeTest, DoesThis) { ... }\n\ninstead of\n\n    TEST(SomeTest, DoesThis) { ... }\n\nin order to define a test.\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/cmake/Config.cmake.in",
    "content": "@PACKAGE_INIT@\ninclude(CMakeFindDependencyMacro)\nif (@GTEST_HAS_PTHREAD@)\n  set(THREADS_PREFER_PTHREAD_FLAG @THREADS_PREFER_PTHREAD_FLAG@)\n  find_dependency(Threads)\nendif()\n\ninclude(\"${CMAKE_CURRENT_LIST_DIR}/@targets_export_name@.cmake\")\ncheck_required_components(\"@project_name@\")\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/cmake/gtest.pc.in",
    "content": "libdir=@CMAKE_INSTALL_FULL_LIBDIR@\nincludedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@\n\nName: gtest\nDescription: GoogleTest (without main() function)\nVersion: @PROJECT_VERSION@\nURL: https://github.com/google/googletest\nLibs: -L${libdir} -lgtest @CMAKE_THREAD_LIBS_INIT@\nCflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/cmake/gtest_main.pc.in",
    "content": "libdir=@CMAKE_INSTALL_FULL_LIBDIR@\nincludedir=@CMAKE_INSTALL_FULL_INCLUDEDIR@\n\nName: gtest_main\nDescription: GoogleTest (with main() function)\nVersion: @PROJECT_VERSION@\nURL: https://github.com/google/googletest\nRequires: gtest = @PROJECT_VERSION@\nLibs: -L${libdir} -lgtest_main @CMAKE_THREAD_LIBS_INIT@\nCflags: -I${includedir} @GTEST_HAS_PTHREAD_MACRO@\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/cmake/internal_utils.cmake",
    "content": "# Defines functions and macros useful for building Google Test and\n# Google Mock.\n#\n# Note:\n#\n# - This file will be run twice when building Google Mock (once via\n#   Google Test's CMakeLists.txt, and once via Google Mock's).\n#   Therefore it shouldn't have any side effects other than defining\n#   the functions and macros.\n#\n# - The functions/macros defined in this file may depend on Google\n#   Test and Google Mock's option() definitions, and thus must be\n#   called *after* the options have been defined.\n\nif (POLICY CMP0054)\n  cmake_policy(SET CMP0054 NEW)\nendif (POLICY CMP0054)\n\n# Tweaks CMake's default compiler/linker settings to suit Google Test's needs.\n#\n# This must be a macro(), as inside a function string() can only\n# update variables in the function scope.\nmacro(fix_default_compiler_settings_)\n  if (MSVC)\n    # For MSVC, CMake sets certain flags to defaults we want to override.\n    # This replacement code is taken from sample in the CMake Wiki at\n    # https://gitlab.kitware.com/cmake/community/wikis/FAQ#dynamic-replace.\n    foreach (flag_var\n             CMAKE_C_FLAGS CMAKE_C_FLAGS_DEBUG CMAKE_C_FLAGS_RELEASE\n             CMAKE_C_FLAGS_MINSIZEREL CMAKE_C_FLAGS_RELWITHDEBINFO\n             CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE\n             CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)\n      if (NOT BUILD_SHARED_LIBS AND NOT gtest_force_shared_crt)\n        # When Google Test is built as a shared library, it should also use\n        # shared runtime libraries.  Otherwise, it may end up with multiple\n        # copies of runtime library data in different modules, resulting in\n        # hard-to-find crashes. When it is built as a static library, it is\n        # preferable to use CRT as static libraries, as we don't have to rely\n        # on CRT DLLs being available. CMake always defaults to using shared\n        # CRT libraries, so we override that default here.\n        string(REPLACE \"/MD\" \"-MT\" ${flag_var} \"${${flag_var}}\")\n      endif()\n\n      # We prefer more strict warning checking for building Google Test.\n      # Replaces /W3 with /W4 in defaults.\n      string(REPLACE \"/W3\" \"/W4\" ${flag_var} \"${${flag_var}}\")\n\n      # Prevent D9025 warning for targets that have exception handling\n      # turned off (/EHs-c- flag). Where required, exceptions are explicitly\n      # re-enabled using the cxx_exception_flags variable.\n      string(REPLACE \"/EHsc\" \"\" ${flag_var} \"${${flag_var}}\")\n    endforeach()\n  endif()\nendmacro()\n\n# Defines the compiler/linker flags used to build Google Test and\n# Google Mock.  You can tweak these definitions to suit your need.  A\n# variable's value is empty before it's explicitly assigned to.\nmacro(config_compiler_and_linker)\n  # Note: pthreads on MinGW is not supported, even if available\n  # instead, we use windows threading primitives\n  unset(GTEST_HAS_PTHREAD)\n  if (NOT gtest_disable_pthreads AND NOT MINGW)\n    # Defines CMAKE_USE_PTHREADS_INIT and CMAKE_THREAD_LIBS_INIT.\n    find_package(Threads)\n    if (CMAKE_USE_PTHREADS_INIT)\n      set(GTEST_HAS_PTHREAD ON)\n    endif()\n  endif()\n\n  fix_default_compiler_settings_()\n  if (MSVC)\n    # Newlines inside flags variables break CMake's NMake generator.\n    # TODO(vladl@google.com): Add -RTCs and -RTCu to debug builds.\n    set(cxx_base_flags \"-GS -W4 -WX -wd4251 -wd4275 -nologo -J\")\n    set(cxx_base_flags \"${cxx_base_flags} -D_UNICODE -DUNICODE -DWIN32 -D_WIN32\")\n    set(cxx_base_flags \"${cxx_base_flags} -DSTRICT -DWIN32_LEAN_AND_MEAN\")\n    set(cxx_exception_flags \"-EHsc -D_HAS_EXCEPTIONS=1\")\n    set(cxx_no_exception_flags \"-EHs-c- -D_HAS_EXCEPTIONS=0\")\n    set(cxx_no_rtti_flags \"-GR-\")\n    # Suppress \"unreachable code\" warning\n    # http://stackoverflow.com/questions/3232669 explains the issue.\n    set(cxx_base_flags \"${cxx_base_flags} -wd4702\")\n    # Ensure MSVC treats source files as UTF-8 encoded.\n    set(cxx_base_flags \"${cxx_base_flags} -utf-8\")\n  elseif (CMAKE_CXX_COMPILER_ID STREQUAL \"Clang\")\n    set(cxx_base_flags \"-Wall -Wshadow -Wconversion\")\n    set(cxx_exception_flags \"-fexceptions\")\n    set(cxx_no_exception_flags \"-fno-exceptions\")\n    set(cxx_strict_flags \"-W -Wpointer-arith -Wreturn-type -Wcast-qual -Wwrite-strings -Wswitch -Wunused-parameter -Wcast-align -Wchar-subscripts -Winline -Wredundant-decls\")\n    set(cxx_no_rtti_flags \"-fno-rtti\")\n  elseif (CMAKE_COMPILER_IS_GNUCXX)\n    set(cxx_base_flags \"-Wall -Wshadow\")\n    if(NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 7.0.0)\n      set(cxx_base_flags \"${cxx_base_flags} -Wno-error=dangling-else\")\n    endif()\n    set(cxx_exception_flags \"-fexceptions\")\n    set(cxx_no_exception_flags \"-fno-exceptions\")\n    # Until version 4.3.2, GCC doesn't define a macro to indicate\n    # whether RTTI is enabled.  Therefore we define GTEST_HAS_RTTI\n    # explicitly.\n    set(cxx_no_rtti_flags \"-fno-rtti -DGTEST_HAS_RTTI=0\")\n    set(cxx_strict_flags\n      \"-Wextra -Wno-unused-parameter -Wno-missing-field-initializers\")\n  elseif (CMAKE_CXX_COMPILER_ID STREQUAL \"SunPro\")\n    set(cxx_exception_flags \"-features=except\")\n    # Sun Pro doesn't provide macros to indicate whether exceptions and\n    # RTTI are enabled, so we define GTEST_HAS_* explicitly.\n    set(cxx_no_exception_flags \"-features=no%except -DGTEST_HAS_EXCEPTIONS=0\")\n    set(cxx_no_rtti_flags \"-features=no%rtti -DGTEST_HAS_RTTI=0\")\n  elseif (CMAKE_CXX_COMPILER_ID STREQUAL \"VisualAge\" OR\n      CMAKE_CXX_COMPILER_ID STREQUAL \"XL\")\n    # CMake 2.8 changes Visual Age's compiler ID to \"XL\".\n    set(cxx_exception_flags \"-qeh\")\n    set(cxx_no_exception_flags \"-qnoeh\")\n    # Until version 9.0, Visual Age doesn't define a macro to indicate\n    # whether RTTI is enabled.  Therefore we define GTEST_HAS_RTTI\n    # explicitly.\n    set(cxx_no_rtti_flags \"-qnortti -DGTEST_HAS_RTTI=0\")\n  elseif (CMAKE_CXX_COMPILER_ID STREQUAL \"HP\")\n    set(cxx_base_flags \"-AA -mt\")\n    set(cxx_exception_flags \"-DGTEST_HAS_EXCEPTIONS=1\")\n    set(cxx_no_exception_flags \"+noeh -DGTEST_HAS_EXCEPTIONS=0\")\n    # RTTI can not be disabled in HP aCC compiler.\n    set(cxx_no_rtti_flags \"\")\n  endif()\n\n  # The pthreads library is available and allowed?\n  if (DEFINED GTEST_HAS_PTHREAD)\n    set(GTEST_HAS_PTHREAD_MACRO \"-DGTEST_HAS_PTHREAD=1\")\n  else()\n    set(GTEST_HAS_PTHREAD_MACRO \"-DGTEST_HAS_PTHREAD=0\")\n  endif()\n  set(cxx_base_flags \"${cxx_base_flags} ${GTEST_HAS_PTHREAD_MACRO}\")\n\n  # For building gtest's own tests and samples.\n  set(cxx_exception \"${cxx_base_flags} ${cxx_exception_flags}\")\n  set(cxx_no_exception\n    \"${CMAKE_CXX_FLAGS} ${cxx_base_flags} ${cxx_no_exception_flags}\")\n  set(cxx_default \"${cxx_exception}\")\n  set(cxx_no_rtti \"${cxx_default} ${cxx_no_rtti_flags}\")\n\n  # For building the gtest libraries.\n  set(cxx_strict \"${cxx_default} ${cxx_strict_flags}\")\nendmacro()\n\n# Defines the gtest & gtest_main libraries.  User tests should link\n# with one of them.\nfunction(cxx_library_with_type name type cxx_flags)\n  # type can be either STATIC or SHARED to denote a static or shared library.\n  # ARGN refers to additional arguments after 'cxx_flags'.\n  add_library(${name} ${type} ${ARGN})\n  add_library(${cmake_package_name}::${name} ALIAS ${name})\n  set_target_properties(${name}\n    PROPERTIES\n    COMPILE_FLAGS \"${cxx_flags}\")\n  # Set the output directory for build artifacts\n  set_target_properties(${name}\n    PROPERTIES\n    RUNTIME_OUTPUT_DIRECTORY \"${CMAKE_BINARY_DIR}/bin\"\n    LIBRARY_OUTPUT_DIRECTORY \"${CMAKE_BINARY_DIR}/lib\"\n    ARCHIVE_OUTPUT_DIRECTORY \"${CMAKE_BINARY_DIR}/lib\"\n    PDB_OUTPUT_DIRECTORY \"${CMAKE_BINARY_DIR}/bin\")\n  # make PDBs match library name\n  get_target_property(pdb_debug_postfix ${name} DEBUG_POSTFIX)\n  set_target_properties(${name}\n    PROPERTIES\n    PDB_NAME \"${name}\"\n    PDB_NAME_DEBUG \"${name}${pdb_debug_postfix}\"\n    COMPILE_PDB_NAME \"${name}\"\n    COMPILE_PDB_NAME_DEBUG \"${name}${pdb_debug_postfix}\")\n\n  if (BUILD_SHARED_LIBS OR type STREQUAL \"SHARED\")\n    set_target_properties(${name}\n      PROPERTIES\n      COMPILE_DEFINITIONS \"GTEST_CREATE_SHARED_LIBRARY=1\")\n    if (NOT \"${CMAKE_VERSION}\" VERSION_LESS \"2.8.11\")\n      target_compile_definitions(${name} INTERFACE\n        $<INSTALL_INTERFACE:GTEST_LINKED_AS_SHARED_LIBRARY=1>)\n    endif()\n  endif()\n  if (DEFINED GTEST_HAS_PTHREAD)\n    if (\"${CMAKE_VERSION}\" VERSION_LESS \"3.1.0\")\n      set(threads_spec ${CMAKE_THREAD_LIBS_INIT})\n    else()\n      set(threads_spec Threads::Threads)\n    endif()\n    target_link_libraries(${name} PUBLIC ${threads_spec})\n  endif()\n\n  if (NOT \"${CMAKE_VERSION}\" VERSION_LESS \"3.8\")\n    target_compile_features(${name} PUBLIC cxx_std_11)\n  endif()\nendfunction()\n\n########################################################################\n#\n# Helper functions for creating build targets.\n\nfunction(cxx_shared_library name cxx_flags)\n  cxx_library_with_type(${name} SHARED \"${cxx_flags}\" ${ARGN})\nendfunction()\n\nfunction(cxx_library name cxx_flags)\n  cxx_library_with_type(${name} \"\" \"${cxx_flags}\" ${ARGN})\nendfunction()\n\n# cxx_executable_with_flags(name cxx_flags libs srcs...)\n#\n# creates a named C++ executable that depends on the given libraries and\n# is built from the given source files with the given compiler flags.\nfunction(cxx_executable_with_flags name cxx_flags libs)\n  add_executable(${name} ${ARGN})\n  if (MSVC)\n    # BigObj required for tests.\n    set(cxx_flags \"${cxx_flags} -bigobj\")\n  endif()\n  if (cxx_flags)\n    set_target_properties(${name}\n      PROPERTIES\n      COMPILE_FLAGS \"${cxx_flags}\")\n  endif()\n  if (BUILD_SHARED_LIBS)\n    set_target_properties(${name}\n      PROPERTIES\n      COMPILE_DEFINITIONS \"GTEST_LINKED_AS_SHARED_LIBRARY=1\")\n  endif()\n  # To support mixing linking in static and dynamic libraries, link each\n  # library in with an extra call to target_link_libraries.\n  foreach (lib \"${libs}\")\n    target_link_libraries(${name} ${lib})\n  endforeach()\nendfunction()\n\n# cxx_executable(name dir lib srcs...)\n#\n# creates a named target that depends on the given libs and is built\n# from the given source files.  dir/name.cc is implicitly included in\n# the source file list.\nfunction(cxx_executable name dir libs)\n  cxx_executable_with_flags(\n    ${name} \"${cxx_default}\" \"${libs}\" \"${dir}/${name}.cc\" ${ARGN})\nendfunction()\n\n# Sets PYTHONINTERP_FOUND and PYTHON_EXECUTABLE.\nif (\"${CMAKE_VERSION}\" VERSION_LESS \"3.12.0\")\n  find_package(PythonInterp)\nelse()\n  find_package(Python COMPONENTS Interpreter)\n  set(PYTHONINTERP_FOUND ${Python_Interpreter_FOUND})\n  set(PYTHON_EXECUTABLE ${Python_EXECUTABLE})\nendif()\n\n# cxx_test_with_flags(name cxx_flags libs srcs...)\n#\n# creates a named C++ test that depends on the given libs and is built\n# from the given source files with the given compiler flags.\nfunction(cxx_test_with_flags name cxx_flags libs)\n  cxx_executable_with_flags(${name} \"${cxx_flags}\" \"${libs}\" ${ARGN})\n    add_test(NAME ${name} COMMAND \"$<TARGET_FILE:${name}>\")\nendfunction()\n\n# cxx_test(name libs srcs...)\n#\n# creates a named test target that depends on the given libs and is\n# built from the given source files.  Unlike cxx_test_with_flags,\n# test/name.cc is already implicitly included in the source file list.\nfunction(cxx_test name libs)\n  cxx_test_with_flags(\"${name}\" \"${cxx_default}\" \"${libs}\"\n    \"test/${name}.cc\" ${ARGN})\nendfunction()\n\n# py_test(name)\n#\n# creates a Python test with the given name whose main module is in\n# test/name.py.  It does nothing if Python is not installed.\nfunction(py_test name)\n  if (PYTHONINTERP_FOUND)\n    if (\"${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}\" VERSION_GREATER 3.1)\n      if (CMAKE_CONFIGURATION_TYPES)\n        # Multi-configuration build generators as for Visual Studio save\n        # output in a subdirectory of CMAKE_CURRENT_BINARY_DIR (Debug,\n        # Release etc.), so we have to provide it here.\n        add_test(NAME ${name}\n          COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py\n              --build_dir=${CMAKE_CURRENT_BINARY_DIR}/$<CONFIG> ${ARGN})\n      else (CMAKE_CONFIGURATION_TYPES)\n        # Single-configuration build generators like Makefile generators\n        # don't have subdirs below CMAKE_CURRENT_BINARY_DIR.\n        add_test(NAME ${name}\n          COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py\n            --build_dir=${CMAKE_CURRENT_BINARY_DIR} ${ARGN})\n      endif (CMAKE_CONFIGURATION_TYPES)\n    else()\n      # ${CMAKE_CURRENT_BINARY_DIR} is known at configuration time, so we can\n      # directly bind it from cmake. ${CTEST_CONFIGURATION_TYPE} is known\n      # only at ctest runtime (by calling ctest -c <Configuration>), so\n      # we have to escape $ to delay variable substitution here.\n      add_test(NAME ${name}\n        COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/test/${name}.py\n          --build_dir=${CMAKE_CURRENT_BINARY_DIR}/\\${CTEST_CONFIGURATION_TYPE} ${ARGN})\n    endif()\n    # Make the Python import path consistent between Bazel and CMake.\n    set_tests_properties(${name} PROPERTIES ENVIRONMENT PYTHONPATH=${CMAKE_SOURCE_DIR})\n  endif(PYTHONINTERP_FOUND)\nendfunction()\n\n# install_project(targets...)\n#\n# Installs the specified targets and configures the associated pkgconfig files.\nfunction(install_project)\n  if(INSTALL_GTEST)\n    install(DIRECTORY \"${PROJECT_SOURCE_DIR}/include/\"\n      DESTINATION \"${CMAKE_INSTALL_INCLUDEDIR}\")\n    # Install the project targets.\n    install(TARGETS ${ARGN}\n      EXPORT ${targets_export_name}\n      RUNTIME DESTINATION \"${CMAKE_INSTALL_BINDIR}\"\n      ARCHIVE DESTINATION \"${CMAKE_INSTALL_LIBDIR}\"\n      LIBRARY DESTINATION \"${CMAKE_INSTALL_LIBDIR}\")\n    if(CMAKE_CXX_COMPILER_ID MATCHES \"MSVC\")\n      # Install PDBs\n      foreach(t ${ARGN})\n        get_target_property(t_pdb_name ${t} COMPILE_PDB_NAME)\n        get_target_property(t_pdb_name_debug ${t} COMPILE_PDB_NAME_DEBUG)\n        get_target_property(t_pdb_output_directory ${t} PDB_OUTPUT_DIRECTORY)\n        install(FILES\n          \"${t_pdb_output_directory}/\\${CMAKE_INSTALL_CONFIG_NAME}/$<$<CONFIG:Debug>:${t_pdb_name_debug}>$<$<NOT:$<CONFIG:Debug>>:${t_pdb_name}>.pdb\"\n          DESTINATION ${CMAKE_INSTALL_LIBDIR}\n          OPTIONAL)\n      endforeach()\n    endif()\n    # Configure and install pkgconfig files.\n    foreach(t ${ARGN})\n      set(configured_pc \"${generated_dir}/${t}.pc\")\n      configure_file(\"${PROJECT_SOURCE_DIR}/cmake/${t}.pc.in\"\n        \"${configured_pc}\" @ONLY)\n      install(FILES \"${configured_pc}\"\n        DESTINATION \"${CMAKE_INSTALL_LIBDIR}/pkgconfig\")\n    endforeach()\n  endif()\nendfunction()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/cmake/libgtest.la.in",
    "content": "# libgtest.la - a libtool library file\n# Generated by libtool (GNU libtool) 2.4.6\n\n# Please DO NOT delete this file!\n# It is necessary for linking the library.\n\n# Names of this library.\nlibrary_names='libgtest.so'\n\n# Is this an already installed library?\ninstalled=yes\n\n# Should we warn about portability when linking against -modules?\nshouldnotlink=no\n\n# Files to dlopen/dlpreopen\ndlopen=''\ndlpreopen=''\n\n# Directory that this library needs to be installed in:\nlibdir='@CMAKE_INSTALL_FULL_LIBDIR@'\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/docs/README.md",
    "content": "# Content Moved\n\nWe are working on updates to the GoogleTest documentation, which has moved to\nthe top-level [docs](../../docs) directory.\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/include/gtest/gtest-assertion-result.h",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// The Google C++ Testing and Mocking Framework (Google Test)\n//\n// This file implements the AssertionResult type.\n\n// IWYU pragma: private, include \"gtest/gtest.h\"\n// IWYU pragma: friend gtest/.*\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_ASSERTION_RESULT_H_\n#define GOOGLETEST_INCLUDE_GTEST_GTEST_ASSERTION_RESULT_H_\n\n#include <memory>\n#include <ostream>\n#include <string>\n#include <type_traits>\n\n#include \"gtest/gtest-message.h\"\n#include \"gtest/internal/gtest-port.h\"\n\nGTEST_DISABLE_MSC_WARNINGS_PUSH_(4251                                   \\\n/* class A needs to have dll-interface to be used by clients of class B */)\n\nnamespace testing {\n\n// A class for indicating whether an assertion was successful.  When\n// the assertion wasn't successful, the AssertionResult object\n// remembers a non-empty message that describes how it failed.\n//\n// To create an instance of this class, use one of the factory functions\n// (AssertionSuccess() and AssertionFailure()).\n//\n// This class is useful for two purposes:\n//   1. Defining predicate functions to be used with Boolean test assertions\n//      EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts\n//   2. Defining predicate-format functions to be\n//      used with predicate assertions (ASSERT_PRED_FORMAT*, etc).\n//\n// For example, if you define IsEven predicate:\n//\n//   testing::AssertionResult IsEven(int n) {\n//     if ((n % 2) == 0)\n//       return testing::AssertionSuccess();\n//     else\n//       return testing::AssertionFailure() << n << \" is odd\";\n//   }\n//\n// Then the failed expectation EXPECT_TRUE(IsEven(Fib(5)))\n// will print the message\n//\n//   Value of: IsEven(Fib(5))\n//     Actual: false (5 is odd)\n//   Expected: true\n//\n// instead of a more opaque\n//\n//   Value of: IsEven(Fib(5))\n//     Actual: false\n//   Expected: true\n//\n// in case IsEven is a simple Boolean predicate.\n//\n// If you expect your predicate to be reused and want to support informative\n// messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up\n// about half as often as positive ones in our tests), supply messages for\n// both success and failure cases:\n//\n//   testing::AssertionResult IsEven(int n) {\n//     if ((n % 2) == 0)\n//       return testing::AssertionSuccess() << n << \" is even\";\n//     else\n//       return testing::AssertionFailure() << n << \" is odd\";\n//   }\n//\n// Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print\n//\n//   Value of: IsEven(Fib(6))\n//     Actual: true (8 is even)\n//   Expected: false\n//\n// NB: Predicates that support negative Boolean assertions have reduced\n// performance in positive ones so be careful not to use them in tests\n// that have lots (tens of thousands) of positive Boolean assertions.\n//\n// To use this class with EXPECT_PRED_FORMAT assertions such as:\n//\n//   // Verifies that Foo() returns an even number.\n//   EXPECT_PRED_FORMAT1(IsEven, Foo());\n//\n// you need to define:\n//\n//   testing::AssertionResult IsEven(const char* expr, int n) {\n//     if ((n % 2) == 0)\n//       return testing::AssertionSuccess();\n//     else\n//       return testing::AssertionFailure()\n//         << \"Expected: \" << expr << \" is even\\n  Actual: it's \" << n;\n//   }\n//\n// If Foo() returns 5, you will see the following message:\n//\n//   Expected: Foo() is even\n//     Actual: it's 5\n//\nclass GTEST_API_ AssertionResult {\n public:\n  // Copy constructor.\n  // Used in EXPECT_TRUE/FALSE(assertion_result).\n  AssertionResult(const AssertionResult& other);\n\n// C4800 is a level 3 warning in Visual Studio 2015 and earlier.\n// This warning is not emitted in Visual Studio 2017.\n// This warning is off by default starting in Visual Studio 2019 but can be\n// enabled with command-line options.\n#if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)\n  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 /* forcing value to bool */)\n#endif\n\n  // Used in the EXPECT_TRUE/FALSE(bool_expression).\n  //\n  // T must be contextually convertible to bool.\n  //\n  // The second parameter prevents this overload from being considered if\n  // the argument is implicitly convertible to AssertionResult. In that case\n  // we want AssertionResult's copy constructor to be used.\n  template <typename T>\n  explicit AssertionResult(\n      const T& success,\n      typename std::enable_if<\n          !std::is_convertible<T, AssertionResult>::value>::type*\n      /*enabler*/\n      = nullptr)\n      : success_(success) {}\n\n#if defined(_MSC_VER) && (_MSC_VER < 1910 || _MSC_VER >= 1920)\n  GTEST_DISABLE_MSC_WARNINGS_POP_()\n#endif\n\n  // Assignment operator.\n  AssertionResult& operator=(AssertionResult other) {\n    swap(other);\n    return *this;\n  }\n\n  // Returns true if and only if the assertion succeeded.\n  operator bool() const { return success_; }  // NOLINT\n\n  // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.\n  AssertionResult operator!() const;\n\n  // Returns the text streamed into this AssertionResult. Test assertions\n  // use it when they fail (i.e., the predicate's outcome doesn't match the\n  // assertion's expectation). When nothing has been streamed into the\n  // object, returns an empty string.\n  const char* message() const {\n    return message_.get() != nullptr ? message_->c_str() : \"\";\n  }\n  // Deprecated; please use message() instead.\n  const char* failure_message() const { return message(); }\n\n  // Streams a custom failure message into this object.\n  template <typename T>\n  AssertionResult& operator<<(const T& value) {\n    AppendMessage(Message() << value);\n    return *this;\n  }\n\n  // Allows streaming basic output manipulators such as endl or flush into\n  // this object.\n  AssertionResult& operator<<(\n      ::std::ostream& (*basic_manipulator)(::std::ostream& stream)) {\n    AppendMessage(Message() << basic_manipulator);\n    return *this;\n  }\n\n private:\n  // Appends the contents of message to message_.\n  void AppendMessage(const Message& a_message) {\n    if (message_.get() == nullptr) message_.reset(new ::std::string);\n    message_->append(a_message.GetString().c_str());\n  }\n\n  // Swap the contents of this AssertionResult with other.\n  void swap(AssertionResult& other);\n\n  // Stores result of the assertion predicate.\n  bool success_;\n  // Stores the message describing the condition in case the expectation\n  // construct is not satisfied with the predicate's outcome.\n  // Referenced via a pointer to avoid taking too much stack frame space\n  // with test assertions.\n  std::unique_ptr< ::std::string> message_;\n};\n\n// Makes a successful assertion result.\nGTEST_API_ AssertionResult AssertionSuccess();\n\n// Makes a failed assertion result.\nGTEST_API_ AssertionResult AssertionFailure();\n\n// Makes a failed assertion result with the given failure message.\n// Deprecated; use AssertionFailure() << msg.\nGTEST_API_ AssertionResult AssertionFailure(const Message& msg);\n\n}  // namespace testing\n\nGTEST_DISABLE_MSC_WARNINGS_POP_()  // 4251\n\n#endif  // GOOGLETEST_INCLUDE_GTEST_GTEST_ASSERTION_RESULT_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/include/gtest/gtest-death-test.h",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// The Google C++ Testing and Mocking Framework (Google Test)\n//\n// This header file defines the public API for death tests.  It is\n// #included by gtest.h so a user doesn't need to include this\n// directly.\n\n// IWYU pragma: private, include \"gtest/gtest.h\"\n// IWYU pragma: friend gtest/.*\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_\n#define GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_\n\n#include \"gtest/internal/gtest-death-test-internal.h\"\n\n// This flag controls the style of death tests.  Valid values are \"threadsafe\",\n// meaning that the death test child process will re-execute the test binary\n// from the start, running only a single death test, or \"fast\",\n// meaning that the child process will execute the test logic immediately\n// after forking.\nGTEST_DECLARE_string_(death_test_style);\n\nnamespace testing {\n\n#if GTEST_HAS_DEATH_TEST\n\nnamespace internal {\n\n// Returns a Boolean value indicating whether the caller is currently\n// executing in the context of the death test child process.  Tools such as\n// Valgrind heap checkers may need this to modify their behavior in death\n// tests.  IMPORTANT: This is an internal utility.  Using it may break the\n// implementation of death tests.  User code MUST NOT use it.\nGTEST_API_ bool InDeathTestChild();\n\n}  // namespace internal\n\n// The following macros are useful for writing death tests.\n\n// Here's what happens when an ASSERT_DEATH* or EXPECT_DEATH* is\n// executed:\n//\n//   1. It generates a warning if there is more than one active\n//   thread.  This is because it's safe to fork() or clone() only\n//   when there is a single thread.\n//\n//   2. The parent process clone()s a sub-process and runs the death\n//   test in it; the sub-process exits with code 0 at the end of the\n//   death test, if it hasn't exited already.\n//\n//   3. The parent process waits for the sub-process to terminate.\n//\n//   4. The parent process checks the exit code and error message of\n//   the sub-process.\n//\n// Examples:\n//\n//   ASSERT_DEATH(server.SendMessage(56, \"Hello\"), \"Invalid port number\");\n//   for (int i = 0; i < 5; i++) {\n//     EXPECT_DEATH(server.ProcessRequest(i),\n//                  \"Invalid request .* in ProcessRequest()\")\n//                  << \"Failed to die on request \" << i;\n//   }\n//\n//   ASSERT_EXIT(server.ExitNow(), ::testing::ExitedWithCode(0), \"Exiting\");\n//\n//   bool KilledBySIGHUP(int exit_code) {\n//     return WIFSIGNALED(exit_code) && WTERMSIG(exit_code) == SIGHUP;\n//   }\n//\n//   ASSERT_EXIT(client.HangUpServer(), KilledBySIGHUP, \"Hanging up!\");\n//\n// The final parameter to each of these macros is a matcher applied to any data\n// the sub-process wrote to stderr.  For compatibility with existing tests, a\n// bare string is interpreted as a regular expression matcher.\n//\n// On the regular expressions used in death tests:\n//\n//   On POSIX-compliant systems (*nix), we use the <regex.h> library,\n//   which uses the POSIX extended regex syntax.\n//\n//   On other platforms (e.g. Windows or Mac), we only support a simple regex\n//   syntax implemented as part of Google Test.  This limited\n//   implementation should be enough most of the time when writing\n//   death tests; though it lacks many features you can find in PCRE\n//   or POSIX extended regex syntax.  For example, we don't support\n//   union (\"x|y\"), grouping (\"(xy)\"), brackets (\"[xy]\"), and\n//   repetition count (\"x{5,7}\"), among others.\n//\n//   Below is the syntax that we do support.  We chose it to be a\n//   subset of both PCRE and POSIX extended regex, so it's easy to\n//   learn wherever you come from.  In the following: 'A' denotes a\n//   literal character, period (.), or a single \\\\ escape sequence;\n//   'x' and 'y' denote regular expressions; 'm' and 'n' are for\n//   natural numbers.\n//\n//     c     matches any literal character c\n//     \\\\d   matches any decimal digit\n//     \\\\D   matches any character that's not a decimal digit\n//     \\\\f   matches \\f\n//     \\\\n   matches \\n\n//     \\\\r   matches \\r\n//     \\\\s   matches any ASCII whitespace, including \\n\n//     \\\\S   matches any character that's not a whitespace\n//     \\\\t   matches \\t\n//     \\\\v   matches \\v\n//     \\\\w   matches any letter, _, or decimal digit\n//     \\\\W   matches any character that \\\\w doesn't match\n//     \\\\c   matches any literal character c, which must be a punctuation\n//     .     matches any single character except \\n\n//     A?    matches 0 or 1 occurrences of A\n//     A*    matches 0 or many occurrences of A\n//     A+    matches 1 or many occurrences of A\n//     ^     matches the beginning of a string (not that of each line)\n//     $     matches the end of a string (not that of each line)\n//     xy    matches x followed by y\n//\n//   If you accidentally use PCRE or POSIX extended regex features\n//   not implemented by us, you will get a run-time failure.  In that\n//   case, please try to rewrite your regular expression within the\n//   above syntax.\n//\n//   This implementation is *not* meant to be as highly tuned or robust\n//   as a compiled regex library, but should perform well enough for a\n//   death test, which already incurs significant overhead by launching\n//   a child process.\n//\n// Known caveats:\n//\n//   A \"threadsafe\" style death test obtains the path to the test\n//   program from argv[0] and re-executes it in the sub-process.  For\n//   simplicity, the current implementation doesn't search the PATH\n//   when launching the sub-process.  This means that the user must\n//   invoke the test program via a path that contains at least one\n//   path separator (e.g. path/to/foo_test and\n//   /absolute/path/to/bar_test are fine, but foo_test is not).  This\n//   is rarely a problem as people usually don't put the test binary\n//   directory in PATH.\n//\n\n// Asserts that a given `statement` causes the program to exit, with an\n// integer exit status that satisfies `predicate`, and emitting error output\n// that matches `matcher`.\n#define ASSERT_EXIT(statement, predicate, matcher) \\\n  GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_FATAL_FAILURE_)\n\n// Like `ASSERT_EXIT`, but continues on to successive tests in the\n// test suite, if any:\n#define EXPECT_EXIT(statement, predicate, matcher) \\\n  GTEST_DEATH_TEST_(statement, predicate, matcher, GTEST_NONFATAL_FAILURE_)\n\n// Asserts that a given `statement` causes the program to exit, either by\n// explicitly exiting with a nonzero exit code or being killed by a\n// signal, and emitting error output that matches `matcher`.\n#define ASSERT_DEATH(statement, matcher) \\\n  ASSERT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher)\n\n// Like `ASSERT_DEATH`, but continues on to successive tests in the\n// test suite, if any:\n#define EXPECT_DEATH(statement, matcher) \\\n  EXPECT_EXIT(statement, ::testing::internal::ExitedUnsuccessfully, matcher)\n\n// Two predicate classes that can be used in {ASSERT,EXPECT}_EXIT*:\n\n// Tests that an exit code describes a normal exit with a given exit code.\nclass GTEST_API_ ExitedWithCode {\n public:\n  explicit ExitedWithCode(int exit_code);\n  ExitedWithCode(const ExitedWithCode&) = default;\n  void operator=(const ExitedWithCode& other) = delete;\n  bool operator()(int exit_status) const;\n\n private:\n  const int exit_code_;\n};\n\n#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA\n// Tests that an exit code describes an exit due to termination by a\n// given signal.\nclass GTEST_API_ KilledBySignal {\n public:\n  explicit KilledBySignal(int signum);\n  bool operator()(int exit_status) const;\n\n private:\n  const int signum_;\n};\n#endif  // !GTEST_OS_WINDOWS\n\n// EXPECT_DEBUG_DEATH asserts that the given statements die in debug mode.\n// The death testing framework causes this to have interesting semantics,\n// since the sideeffects of the call are only visible in opt mode, and not\n// in debug mode.\n//\n// In practice, this can be used to test functions that utilize the\n// LOG(DFATAL) macro using the following style:\n//\n// int DieInDebugOr12(int* sideeffect) {\n//   if (sideeffect) {\n//     *sideeffect = 12;\n//   }\n//   LOG(DFATAL) << \"death\";\n//   return 12;\n// }\n//\n// TEST(TestSuite, TestDieOr12WorksInDgbAndOpt) {\n//   int sideeffect = 0;\n//   // Only asserts in dbg.\n//   EXPECT_DEBUG_DEATH(DieInDebugOr12(&sideeffect), \"death\");\n//\n// #ifdef NDEBUG\n//   // opt-mode has sideeffect visible.\n//   EXPECT_EQ(12, sideeffect);\n// #else\n//   // dbg-mode no visible sideeffect.\n//   EXPECT_EQ(0, sideeffect);\n// #endif\n// }\n//\n// This will assert that DieInDebugReturn12InOpt() crashes in debug\n// mode, usually due to a DCHECK or LOG(DFATAL), but returns the\n// appropriate fallback value (12 in this case) in opt mode. If you\n// need to test that a function has appropriate side-effects in opt\n// mode, include assertions against the side-effects.  A general\n// pattern for this is:\n//\n// EXPECT_DEBUG_DEATH({\n//   // Side-effects here will have an effect after this statement in\n//   // opt mode, but none in debug mode.\n//   EXPECT_EQ(12, DieInDebugOr12(&sideeffect));\n// }, \"death\");\n//\n#ifdef NDEBUG\n\n#define EXPECT_DEBUG_DEATH(statement, regex) \\\n  GTEST_EXECUTE_STATEMENT_(statement, regex)\n\n#define ASSERT_DEBUG_DEATH(statement, regex) \\\n  GTEST_EXECUTE_STATEMENT_(statement, regex)\n\n#else\n\n#define EXPECT_DEBUG_DEATH(statement, regex) EXPECT_DEATH(statement, regex)\n\n#define ASSERT_DEBUG_DEATH(statement, regex) ASSERT_DEATH(statement, regex)\n\n#endif  // NDEBUG for EXPECT_DEBUG_DEATH\n#endif  // GTEST_HAS_DEATH_TEST\n\n// This macro is used for implementing macros such as\n// EXPECT_DEATH_IF_SUPPORTED and ASSERT_DEATH_IF_SUPPORTED on systems where\n// death tests are not supported. Those macros must compile on such systems\n// if and only if EXPECT_DEATH and ASSERT_DEATH compile with the same parameters\n// on systems that support death tests. This allows one to write such a macro on\n// a system that does not support death tests and be sure that it will compile\n// on a death-test supporting system. It is exposed publicly so that systems\n// that have death-tests with stricter requirements than GTEST_HAS_DEATH_TEST\n// can write their own equivalent of EXPECT_DEATH_IF_SUPPORTED and\n// ASSERT_DEATH_IF_SUPPORTED.\n//\n// Parameters:\n//   statement -  A statement that a macro such as EXPECT_DEATH would test\n//                for program termination. This macro has to make sure this\n//                statement is compiled but not executed, to ensure that\n//                EXPECT_DEATH_IF_SUPPORTED compiles with a certain\n//                parameter if and only if EXPECT_DEATH compiles with it.\n//   regex     -  A regex that a macro such as EXPECT_DEATH would use to test\n//                the output of statement.  This parameter has to be\n//                compiled but not evaluated by this macro, to ensure that\n//                this macro only accepts expressions that a macro such as\n//                EXPECT_DEATH would accept.\n//   terminator - Must be an empty statement for EXPECT_DEATH_IF_SUPPORTED\n//                and a return statement for ASSERT_DEATH_IF_SUPPORTED.\n//                This ensures that ASSERT_DEATH_IF_SUPPORTED will not\n//                compile inside functions where ASSERT_DEATH doesn't\n//                compile.\n//\n//  The branch that has an always false condition is used to ensure that\n//  statement and regex are compiled (and thus syntactically correct) but\n//  never executed. The unreachable code macro protects the terminator\n//  statement from generating an 'unreachable code' warning in case\n//  statement unconditionally returns or throws. The Message constructor at\n//  the end allows the syntax of streaming additional messages into the\n//  macro, for compilational compatibility with EXPECT_DEATH/ASSERT_DEATH.\n#define GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, terminator)             \\\n  GTEST_AMBIGUOUS_ELSE_BLOCKER_                                                \\\n  if (::testing::internal::AlwaysTrue()) {                                     \\\n    GTEST_LOG_(WARNING) << \"Death tests are not supported on this platform.\\n\" \\\n                        << \"Statement '\" #statement \"' cannot be verified.\";   \\\n  } else if (::testing::internal::AlwaysFalse()) {                             \\\n    ::testing::internal::RE::PartialMatch(\".*\", (regex));                      \\\n    GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement);                 \\\n    terminator;                                                                \\\n  } else                                                                       \\\n    ::testing::Message()\n\n// EXPECT_DEATH_IF_SUPPORTED(statement, regex) and\n// ASSERT_DEATH_IF_SUPPORTED(statement, regex) expand to real death tests if\n// death tests are supported; otherwise they just issue a warning.  This is\n// useful when you are combining death test assertions with normal test\n// assertions in one test.\n#if GTEST_HAS_DEATH_TEST\n#define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \\\n  EXPECT_DEATH(statement, regex)\n#define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \\\n  ASSERT_DEATH(statement, regex)\n#else\n#define EXPECT_DEATH_IF_SUPPORTED(statement, regex) \\\n  GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, )\n#define ASSERT_DEATH_IF_SUPPORTED(statement, regex) \\\n  GTEST_UNSUPPORTED_DEATH_TEST(statement, regex, return)\n#endif\n\n}  // namespace testing\n\n#endif  // GOOGLETEST_INCLUDE_GTEST_GTEST_DEATH_TEST_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/include/gtest/gtest-matchers.h",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// The Google C++ Testing and Mocking Framework (Google Test)\n//\n// This file implements just enough of the matcher interface to allow\n// EXPECT_DEATH and friends to accept a matcher argument.\n\n// IWYU pragma: private, include \"gtest/gtest.h\"\n// IWYU pragma: friend gtest/.*\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_\n#define GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_\n\n#include <atomic>\n#include <memory>\n#include <ostream>\n#include <string>\n#include <type_traits>\n\n#include \"gtest/gtest-printers.h\"\n#include \"gtest/internal/gtest-internal.h\"\n#include \"gtest/internal/gtest-port.h\"\n\n// MSVC warning C5046 is new as of VS2017 version 15.8.\n#if defined(_MSC_VER) && _MSC_VER >= 1915\n#define GTEST_MAYBE_5046_ 5046\n#else\n#define GTEST_MAYBE_5046_\n#endif\n\nGTEST_DISABLE_MSC_WARNINGS_PUSH_(\n    4251 GTEST_MAYBE_5046_ /* class A needs to have dll-interface to be used by\n                              clients of class B */\n    /* Symbol involving type with internal linkage not defined */)\n\nnamespace testing {\n\n// To implement a matcher Foo for type T, define:\n//   1. a class FooMatcherMatcher that implements the matcher interface:\n//     using is_gtest_matcher = void;\n//     bool MatchAndExplain(const T&, std::ostream*);\n//       (MatchResultListener* can also be used instead of std::ostream*)\n//     void DescribeTo(std::ostream*);\n//     void DescribeNegationTo(std::ostream*);\n//\n//   2. a factory function that creates a Matcher<T> object from a\n//      FooMatcherMatcher.\n\nclass MatchResultListener {\n public:\n  // Creates a listener object with the given underlying ostream.  The\n  // listener does not own the ostream, and does not dereference it\n  // in the constructor or destructor.\n  explicit MatchResultListener(::std::ostream* os) : stream_(os) {}\n  virtual ~MatchResultListener() = 0;  // Makes this class abstract.\n\n  // Streams x to the underlying ostream; does nothing if the ostream\n  // is NULL.\n  template <typename T>\n  MatchResultListener& operator<<(const T& x) {\n    if (stream_ != nullptr) *stream_ << x;\n    return *this;\n  }\n\n  // Returns the underlying ostream.\n  ::std::ostream* stream() { return stream_; }\n\n  // Returns true if and only if the listener is interested in an explanation\n  // of the match result.  A matcher's MatchAndExplain() method can use\n  // this information to avoid generating the explanation when no one\n  // intends to hear it.\n  bool IsInterested() const { return stream_ != nullptr; }\n\n private:\n  ::std::ostream* const stream_;\n\n  MatchResultListener(const MatchResultListener&) = delete;\n  MatchResultListener& operator=(const MatchResultListener&) = delete;\n};\n\ninline MatchResultListener::~MatchResultListener() {}\n\n// An instance of a subclass of this knows how to describe itself as a\n// matcher.\nclass GTEST_API_ MatcherDescriberInterface {\n public:\n  virtual ~MatcherDescriberInterface() {}\n\n  // Describes this matcher to an ostream.  The function should print\n  // a verb phrase that describes the property a value matching this\n  // matcher should have.  The subject of the verb phrase is the value\n  // being matched.  For example, the DescribeTo() method of the Gt(7)\n  // matcher prints \"is greater than 7\".\n  virtual void DescribeTo(::std::ostream* os) const = 0;\n\n  // Describes the negation of this matcher to an ostream.  For\n  // example, if the description of this matcher is \"is greater than\n  // 7\", the negated description could be \"is not greater than 7\".\n  // You are not required to override this when implementing\n  // MatcherInterface, but it is highly advised so that your matcher\n  // can produce good error messages.\n  virtual void DescribeNegationTo(::std::ostream* os) const {\n    *os << \"not (\";\n    DescribeTo(os);\n    *os << \")\";\n  }\n};\n\n// The implementation of a matcher.\ntemplate <typename T>\nclass MatcherInterface : public MatcherDescriberInterface {\n public:\n  // Returns true if and only if the matcher matches x; also explains the\n  // match result to 'listener' if necessary (see the next paragraph), in\n  // the form of a non-restrictive relative clause (\"which ...\",\n  // \"whose ...\", etc) that describes x.  For example, the\n  // MatchAndExplain() method of the Pointee(...) matcher should\n  // generate an explanation like \"which points to ...\".\n  //\n  // Implementations of MatchAndExplain() should add an explanation of\n  // the match result *if and only if* they can provide additional\n  // information that's not already present (or not obvious) in the\n  // print-out of x and the matcher's description.  Whether the match\n  // succeeds is not a factor in deciding whether an explanation is\n  // needed, as sometimes the caller needs to print a failure message\n  // when the match succeeds (e.g. when the matcher is used inside\n  // Not()).\n  //\n  // For example, a \"has at least 10 elements\" matcher should explain\n  // what the actual element count is, regardless of the match result,\n  // as it is useful information to the reader; on the other hand, an\n  // \"is empty\" matcher probably only needs to explain what the actual\n  // size is when the match fails, as it's redundant to say that the\n  // size is 0 when the value is already known to be empty.\n  //\n  // You should override this method when defining a new matcher.\n  //\n  // It's the responsibility of the caller (Google Test) to guarantee\n  // that 'listener' is not NULL.  This helps to simplify a matcher's\n  // implementation when it doesn't care about the performance, as it\n  // can talk to 'listener' without checking its validity first.\n  // However, in order to implement dummy listeners efficiently,\n  // listener->stream() may be NULL.\n  virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;\n\n  // Inherits these methods from MatcherDescriberInterface:\n  //   virtual void DescribeTo(::std::ostream* os) const = 0;\n  //   virtual void DescribeNegationTo(::std::ostream* os) const;\n};\n\nnamespace internal {\n\nstruct AnyEq {\n  template <typename A, typename B>\n  bool operator()(const A& a, const B& b) const {\n    return a == b;\n  }\n};\nstruct AnyNe {\n  template <typename A, typename B>\n  bool operator()(const A& a, const B& b) const {\n    return a != b;\n  }\n};\nstruct AnyLt {\n  template <typename A, typename B>\n  bool operator()(const A& a, const B& b) const {\n    return a < b;\n  }\n};\nstruct AnyGt {\n  template <typename A, typename B>\n  bool operator()(const A& a, const B& b) const {\n    return a > b;\n  }\n};\nstruct AnyLe {\n  template <typename A, typename B>\n  bool operator()(const A& a, const B& b) const {\n    return a <= b;\n  }\n};\nstruct AnyGe {\n  template <typename A, typename B>\n  bool operator()(const A& a, const B& b) const {\n    return a >= b;\n  }\n};\n\n// A match result listener that ignores the explanation.\nclass DummyMatchResultListener : public MatchResultListener {\n public:\n  DummyMatchResultListener() : MatchResultListener(nullptr) {}\n\n private:\n  DummyMatchResultListener(const DummyMatchResultListener&) = delete;\n  DummyMatchResultListener& operator=(const DummyMatchResultListener&) = delete;\n};\n\n// A match result listener that forwards the explanation to a given\n// ostream.  The difference between this and MatchResultListener is\n// that the former is concrete.\nclass StreamMatchResultListener : public MatchResultListener {\n public:\n  explicit StreamMatchResultListener(::std::ostream* os)\n      : MatchResultListener(os) {}\n\n private:\n  StreamMatchResultListener(const StreamMatchResultListener&) = delete;\n  StreamMatchResultListener& operator=(const StreamMatchResultListener&) =\n      delete;\n};\n\nstruct SharedPayloadBase {\n  std::atomic<int> ref{1};\n  void Ref() { ref.fetch_add(1, std::memory_order_relaxed); }\n  bool Unref() { return ref.fetch_sub(1, std::memory_order_acq_rel) == 1; }\n};\n\ntemplate <typename T>\nstruct SharedPayload : SharedPayloadBase {\n  explicit SharedPayload(const T& v) : value(v) {}\n  explicit SharedPayload(T&& v) : value(std::move(v)) {}\n\n  static void Destroy(SharedPayloadBase* shared) {\n    delete static_cast<SharedPayload*>(shared);\n  }\n\n  T value;\n};\n\n// An internal class for implementing Matcher<T>, which will derive\n// from it.  We put functionalities common to all Matcher<T>\n// specializations here to avoid code duplication.\ntemplate <typename T>\nclass MatcherBase : private MatcherDescriberInterface {\n public:\n  // Returns true if and only if the matcher matches x; also explains the\n  // match result to 'listener'.\n  bool MatchAndExplain(const T& x, MatchResultListener* listener) const {\n    GTEST_CHECK_(vtable_ != nullptr);\n    return vtable_->match_and_explain(*this, x, listener);\n  }\n\n  // Returns true if and only if this matcher matches x.\n  bool Matches(const T& x) const {\n    DummyMatchResultListener dummy;\n    return MatchAndExplain(x, &dummy);\n  }\n\n  // Describes this matcher to an ostream.\n  void DescribeTo(::std::ostream* os) const final {\n    GTEST_CHECK_(vtable_ != nullptr);\n    vtable_->describe(*this, os, false);\n  }\n\n  // Describes the negation of this matcher to an ostream.\n  void DescribeNegationTo(::std::ostream* os) const final {\n    GTEST_CHECK_(vtable_ != nullptr);\n    vtable_->describe(*this, os, true);\n  }\n\n  // Explains why x matches, or doesn't match, the matcher.\n  void ExplainMatchResultTo(const T& x, ::std::ostream* os) const {\n    StreamMatchResultListener listener(os);\n    MatchAndExplain(x, &listener);\n  }\n\n  // Returns the describer for this matcher object; retains ownership\n  // of the describer, which is only guaranteed to be alive when\n  // this matcher object is alive.\n  const MatcherDescriberInterface* GetDescriber() const {\n    if (vtable_ == nullptr) return nullptr;\n    return vtable_->get_describer(*this);\n  }\n\n protected:\n  MatcherBase() : vtable_(nullptr), buffer_() {}\n\n  // Constructs a matcher from its implementation.\n  template <typename U>\n  explicit MatcherBase(const MatcherInterface<U>* impl)\n      : vtable_(nullptr), buffer_() {\n    Init(impl);\n  }\n\n  template <typename M, typename = typename std::remove_reference<\n                            M>::type::is_gtest_matcher>\n  MatcherBase(M&& m) : vtable_(nullptr), buffer_() {  // NOLINT\n    Init(std::forward<M>(m));\n  }\n\n  MatcherBase(const MatcherBase& other)\n      : vtable_(other.vtable_), buffer_(other.buffer_) {\n    if (IsShared()) buffer_.shared->Ref();\n  }\n\n  MatcherBase& operator=(const MatcherBase& other) {\n    if (this == &other) return *this;\n    Destroy();\n    vtable_ = other.vtable_;\n    buffer_ = other.buffer_;\n    if (IsShared()) buffer_.shared->Ref();\n    return *this;\n  }\n\n  MatcherBase(MatcherBase&& other)\n      : vtable_(other.vtable_), buffer_(other.buffer_) {\n    other.vtable_ = nullptr;\n  }\n\n  MatcherBase& operator=(MatcherBase&& other) {\n    if (this == &other) return *this;\n    Destroy();\n    vtable_ = other.vtable_;\n    buffer_ = other.buffer_;\n    other.vtable_ = nullptr;\n    return *this;\n  }\n\n  ~MatcherBase() override { Destroy(); }\n\n private:\n  struct VTable {\n    bool (*match_and_explain)(const MatcherBase&, const T&,\n                              MatchResultListener*);\n    void (*describe)(const MatcherBase&, std::ostream*, bool negation);\n    // Returns the captured object if it implements the interface, otherwise\n    // returns the MatcherBase itself.\n    const MatcherDescriberInterface* (*get_describer)(const MatcherBase&);\n    // Called on shared instances when the reference count reaches 0.\n    void (*shared_destroy)(SharedPayloadBase*);\n  };\n\n  bool IsShared() const {\n    return vtable_ != nullptr && vtable_->shared_destroy != nullptr;\n  }\n\n  // If the implementation uses a listener, call that.\n  template <typename P>\n  static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,\n                                  MatchResultListener* listener)\n      -> decltype(P::Get(m).MatchAndExplain(value, listener->stream())) {\n    return P::Get(m).MatchAndExplain(value, listener->stream());\n  }\n\n  template <typename P>\n  static auto MatchAndExplainImpl(const MatcherBase& m, const T& value,\n                                  MatchResultListener* listener)\n      -> decltype(P::Get(m).MatchAndExplain(value, listener)) {\n    return P::Get(m).MatchAndExplain(value, listener);\n  }\n\n  template <typename P>\n  static void DescribeImpl(const MatcherBase& m, std::ostream* os,\n                           bool negation) {\n    if (negation) {\n      P::Get(m).DescribeNegationTo(os);\n    } else {\n      P::Get(m).DescribeTo(os);\n    }\n  }\n\n  template <typename P>\n  static const MatcherDescriberInterface* GetDescriberImpl(\n      const MatcherBase& m) {\n    // If the impl is a MatcherDescriberInterface, then return it.\n    // Otherwise use MatcherBase itself.\n    // This allows us to implement the GetDescriber() function without support\n    // from the impl, but some users really want to get their impl back when\n    // they call GetDescriber().\n    // We use std::get on a tuple as a workaround of not having `if constexpr`.\n    return std::get<(\n        std::is_convertible<decltype(&P::Get(m)),\n                            const MatcherDescriberInterface*>::value\n            ? 1\n            : 0)>(std::make_tuple(&m, &P::Get(m)));\n  }\n\n  template <typename P>\n  const VTable* GetVTable() {\n    static constexpr VTable kVTable = {&MatchAndExplainImpl<P>,\n                                       &DescribeImpl<P>, &GetDescriberImpl<P>,\n                                       P::shared_destroy};\n    return &kVTable;\n  }\n\n  union Buffer {\n    // Add some types to give Buffer some common alignment/size use cases.\n    void* ptr;\n    double d;\n    int64_t i;\n    // And add one for the out-of-line cases.\n    SharedPayloadBase* shared;\n  };\n\n  void Destroy() {\n    if (IsShared() && buffer_.shared->Unref()) {\n      vtable_->shared_destroy(buffer_.shared);\n    }\n  }\n\n  template <typename M>\n  static constexpr bool IsInlined() {\n    return sizeof(M) <= sizeof(Buffer) && alignof(M) <= alignof(Buffer) &&\n           std::is_trivially_copy_constructible<M>::value &&\n           std::is_trivially_destructible<M>::value;\n  }\n\n  template <typename M, bool = MatcherBase::IsInlined<M>()>\n  struct ValuePolicy {\n    static const M& Get(const MatcherBase& m) {\n      // When inlined along with Init, need to be explicit to avoid violating\n      // strict aliasing rules.\n      const M* ptr =\n          static_cast<const M*>(static_cast<const void*>(&m.buffer_));\n      return *ptr;\n    }\n    static void Init(MatcherBase& m, M impl) {\n      ::new (static_cast<void*>(&m.buffer_)) M(impl);\n    }\n    static constexpr auto shared_destroy = nullptr;\n  };\n\n  template <typename M>\n  struct ValuePolicy<M, false> {\n    using Shared = SharedPayload<M>;\n    static const M& Get(const MatcherBase& m) {\n      return static_cast<Shared*>(m.buffer_.shared)->value;\n    }\n    template <typename Arg>\n    static void Init(MatcherBase& m, Arg&& arg) {\n      m.buffer_.shared = new Shared(std::forward<Arg>(arg));\n    }\n    static constexpr auto shared_destroy = &Shared::Destroy;\n  };\n\n  template <typename U, bool B>\n  struct ValuePolicy<const MatcherInterface<U>*, B> {\n    using M = const MatcherInterface<U>;\n    using Shared = SharedPayload<std::unique_ptr<M>>;\n    static const M& Get(const MatcherBase& m) {\n      return *static_cast<Shared*>(m.buffer_.shared)->value;\n    }\n    static void Init(MatcherBase& m, M* impl) {\n      m.buffer_.shared = new Shared(std::unique_ptr<M>(impl));\n    }\n\n    static constexpr auto shared_destroy = &Shared::Destroy;\n  };\n\n  template <typename M>\n  void Init(M&& m) {\n    using MM = typename std::decay<M>::type;\n    using Policy = ValuePolicy<MM>;\n    vtable_ = GetVTable<Policy>();\n    Policy::Init(*this, std::forward<M>(m));\n  }\n\n  const VTable* vtable_;\n  Buffer buffer_;\n};\n\n}  // namespace internal\n\n// A Matcher<T> is a copyable and IMMUTABLE (except by assignment)\n// object that can check whether a value of type T matches.  The\n// implementation of Matcher<T> is just a std::shared_ptr to const\n// MatcherInterface<T>.  Don't inherit from Matcher!\ntemplate <typename T>\nclass Matcher : public internal::MatcherBase<T> {\n public:\n  // Constructs a null matcher.  Needed for storing Matcher objects in STL\n  // containers.  A default-constructed matcher is not yet initialized.  You\n  // cannot use it until a valid value has been assigned to it.\n  explicit Matcher() {}  // NOLINT\n\n  // Constructs a matcher from its implementation.\n  explicit Matcher(const MatcherInterface<const T&>* impl)\n      : internal::MatcherBase<T>(impl) {}\n\n  template <typename U>\n  explicit Matcher(\n      const MatcherInterface<U>* impl,\n      typename std::enable_if<!std::is_same<U, const U&>::value>::type* =\n          nullptr)\n      : internal::MatcherBase<T>(impl) {}\n\n  template <typename M, typename = typename std::remove_reference<\n                            M>::type::is_gtest_matcher>\n  Matcher(M&& m) : internal::MatcherBase<T>(std::forward<M>(m)) {}  // NOLINT\n\n  // Implicit constructor here allows people to write\n  // EXPECT_CALL(foo, Bar(5)) instead of EXPECT_CALL(foo, Bar(Eq(5))) sometimes\n  Matcher(T value);  // NOLINT\n};\n\n// The following two specializations allow the user to write str\n// instead of Eq(str) and \"foo\" instead of Eq(\"foo\") when a std::string\n// matcher is expected.\ntemplate <>\nclass GTEST_API_ Matcher<const std::string&>\n    : public internal::MatcherBase<const std::string&> {\n public:\n  Matcher() {}\n\n  explicit Matcher(const MatcherInterface<const std::string&>* impl)\n      : internal::MatcherBase<const std::string&>(impl) {}\n\n  template <typename M, typename = typename std::remove_reference<\n                            M>::type::is_gtest_matcher>\n  Matcher(M&& m)  // NOLINT\n      : internal::MatcherBase<const std::string&>(std::forward<M>(m)) {}\n\n  // Allows the user to write str instead of Eq(str) sometimes, where\n  // str is a std::string object.\n  Matcher(const std::string& s);  // NOLINT\n\n  // Allows the user to write \"foo\" instead of Eq(\"foo\") sometimes.\n  Matcher(const char* s);  // NOLINT\n};\n\ntemplate <>\nclass GTEST_API_ Matcher<std::string>\n    : public internal::MatcherBase<std::string> {\n public:\n  Matcher() {}\n\n  explicit Matcher(const MatcherInterface<const std::string&>* impl)\n      : internal::MatcherBase<std::string>(impl) {}\n  explicit Matcher(const MatcherInterface<std::string>* impl)\n      : internal::MatcherBase<std::string>(impl) {}\n\n  template <typename M, typename = typename std::remove_reference<\n                            M>::type::is_gtest_matcher>\n  Matcher(M&& m)  // NOLINT\n      : internal::MatcherBase<std::string>(std::forward<M>(m)) {}\n\n  // Allows the user to write str instead of Eq(str) sometimes, where\n  // str is a string object.\n  Matcher(const std::string& s);  // NOLINT\n\n  // Allows the user to write \"foo\" instead of Eq(\"foo\") sometimes.\n  Matcher(const char* s);  // NOLINT\n};\n\n#if GTEST_INTERNAL_HAS_STRING_VIEW\n// The following two specializations allow the user to write str\n// instead of Eq(str) and \"foo\" instead of Eq(\"foo\") when a absl::string_view\n// matcher is expected.\ntemplate <>\nclass GTEST_API_ Matcher<const internal::StringView&>\n    : public internal::MatcherBase<const internal::StringView&> {\n public:\n  Matcher() {}\n\n  explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)\n      : internal::MatcherBase<const internal::StringView&>(impl) {}\n\n  template <typename M, typename = typename std::remove_reference<\n                            M>::type::is_gtest_matcher>\n  Matcher(M&& m)  // NOLINT\n      : internal::MatcherBase<const internal::StringView&>(std::forward<M>(m)) {\n  }\n\n  // Allows the user to write str instead of Eq(str) sometimes, where\n  // str is a std::string object.\n  Matcher(const std::string& s);  // NOLINT\n\n  // Allows the user to write \"foo\" instead of Eq(\"foo\") sometimes.\n  Matcher(const char* s);  // NOLINT\n\n  // Allows the user to pass absl::string_views or std::string_views directly.\n  Matcher(internal::StringView s);  // NOLINT\n};\n\ntemplate <>\nclass GTEST_API_ Matcher<internal::StringView>\n    : public internal::MatcherBase<internal::StringView> {\n public:\n  Matcher() {}\n\n  explicit Matcher(const MatcherInterface<const internal::StringView&>* impl)\n      : internal::MatcherBase<internal::StringView>(impl) {}\n  explicit Matcher(const MatcherInterface<internal::StringView>* impl)\n      : internal::MatcherBase<internal::StringView>(impl) {}\n\n  template <typename M, typename = typename std::remove_reference<\n                            M>::type::is_gtest_matcher>\n  Matcher(M&& m)  // NOLINT\n      : internal::MatcherBase<internal::StringView>(std::forward<M>(m)) {}\n\n  // Allows the user to write str instead of Eq(str) sometimes, where\n  // str is a std::string object.\n  Matcher(const std::string& s);  // NOLINT\n\n  // Allows the user to write \"foo\" instead of Eq(\"foo\") sometimes.\n  Matcher(const char* s);  // NOLINT\n\n  // Allows the user to pass absl::string_views or std::string_views directly.\n  Matcher(internal::StringView s);  // NOLINT\n};\n#endif  // GTEST_INTERNAL_HAS_STRING_VIEW\n\n// Prints a matcher in a human-readable format.\ntemplate <typename T>\nstd::ostream& operator<<(std::ostream& os, const Matcher<T>& matcher) {\n  matcher.DescribeTo(&os);\n  return os;\n}\n\n// The PolymorphicMatcher class template makes it easy to implement a\n// polymorphic matcher (i.e. a matcher that can match values of more\n// than one type, e.g. Eq(n) and NotNull()).\n//\n// To define a polymorphic matcher, a user should provide an Impl\n// class that has a DescribeTo() method and a DescribeNegationTo()\n// method, and define a member function (or member function template)\n//\n//   bool MatchAndExplain(const Value& value,\n//                        MatchResultListener* listener) const;\n//\n// See the definition of NotNull() for a complete example.\ntemplate <class Impl>\nclass PolymorphicMatcher {\n public:\n  explicit PolymorphicMatcher(const Impl& an_impl) : impl_(an_impl) {}\n\n  // Returns a mutable reference to the underlying matcher\n  // implementation object.\n  Impl& mutable_impl() { return impl_; }\n\n  // Returns an immutable reference to the underlying matcher\n  // implementation object.\n  const Impl& impl() const { return impl_; }\n\n  template <typename T>\n  operator Matcher<T>() const {\n    return Matcher<T>(new MonomorphicImpl<const T&>(impl_));\n  }\n\n private:\n  template <typename T>\n  class MonomorphicImpl : public MatcherInterface<T> {\n   public:\n    explicit MonomorphicImpl(const Impl& impl) : impl_(impl) {}\n\n    void DescribeTo(::std::ostream* os) const override { impl_.DescribeTo(os); }\n\n    void DescribeNegationTo(::std::ostream* os) const override {\n      impl_.DescribeNegationTo(os);\n    }\n\n    bool MatchAndExplain(T x, MatchResultListener* listener) const override {\n      return impl_.MatchAndExplain(x, listener);\n    }\n\n   private:\n    const Impl impl_;\n  };\n\n  Impl impl_;\n};\n\n// Creates a matcher from its implementation.\n// DEPRECATED: Especially in the generic code, prefer:\n//   Matcher<T>(new MyMatcherImpl<const T&>(...));\n//\n// MakeMatcher may create a Matcher that accepts its argument by value, which\n// leads to unnecessary copies & lack of support for non-copyable types.\ntemplate <typename T>\ninline Matcher<T> MakeMatcher(const MatcherInterface<T>* impl) {\n  return Matcher<T>(impl);\n}\n\n// Creates a polymorphic matcher from its implementation.  This is\n// easier to use than the PolymorphicMatcher<Impl> constructor as it\n// doesn't require you to explicitly write the template argument, e.g.\n//\n//   MakePolymorphicMatcher(foo);\n// vs\n//   PolymorphicMatcher<TypeOfFoo>(foo);\ntemplate <class Impl>\ninline PolymorphicMatcher<Impl> MakePolymorphicMatcher(const Impl& impl) {\n  return PolymorphicMatcher<Impl>(impl);\n}\n\nnamespace internal {\n// Implements a matcher that compares a given value with a\n// pre-supplied value using one of the ==, <=, <, etc, operators.  The\n// two values being compared don't have to have the same type.\n//\n// The matcher defined here is polymorphic (for example, Eq(5) can be\n// used to match an int, a short, a double, etc).  Therefore we use\n// a template type conversion operator in the implementation.\n//\n// The following template definition assumes that the Rhs parameter is\n// a \"bare\" type (i.e. neither 'const T' nor 'T&').\ntemplate <typename D, typename Rhs, typename Op>\nclass ComparisonBase {\n public:\n  explicit ComparisonBase(const Rhs& rhs) : rhs_(rhs) {}\n\n  using is_gtest_matcher = void;\n\n  template <typename Lhs>\n  bool MatchAndExplain(const Lhs& lhs, std::ostream*) const {\n    return Op()(lhs, Unwrap(rhs_));\n  }\n  void DescribeTo(std::ostream* os) const {\n    *os << D::Desc() << \" \";\n    UniversalPrint(Unwrap(rhs_), os);\n  }\n  void DescribeNegationTo(std::ostream* os) const {\n    *os << D::NegatedDesc() << \" \";\n    UniversalPrint(Unwrap(rhs_), os);\n  }\n\n private:\n  template <typename T>\n  static const T& Unwrap(const T& v) {\n    return v;\n  }\n  template <typename T>\n  static const T& Unwrap(std::reference_wrapper<T> v) {\n    return v;\n  }\n\n  Rhs rhs_;\n};\n\ntemplate <typename Rhs>\nclass EqMatcher : public ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq> {\n public:\n  explicit EqMatcher(const Rhs& rhs)\n      : ComparisonBase<EqMatcher<Rhs>, Rhs, AnyEq>(rhs) {}\n  static const char* Desc() { return \"is equal to\"; }\n  static const char* NegatedDesc() { return \"isn't equal to\"; }\n};\ntemplate <typename Rhs>\nclass NeMatcher : public ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe> {\n public:\n  explicit NeMatcher(const Rhs& rhs)\n      : ComparisonBase<NeMatcher<Rhs>, Rhs, AnyNe>(rhs) {}\n  static const char* Desc() { return \"isn't equal to\"; }\n  static const char* NegatedDesc() { return \"is equal to\"; }\n};\ntemplate <typename Rhs>\nclass LtMatcher : public ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt> {\n public:\n  explicit LtMatcher(const Rhs& rhs)\n      : ComparisonBase<LtMatcher<Rhs>, Rhs, AnyLt>(rhs) {}\n  static const char* Desc() { return \"is <\"; }\n  static const char* NegatedDesc() { return \"isn't <\"; }\n};\ntemplate <typename Rhs>\nclass GtMatcher : public ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt> {\n public:\n  explicit GtMatcher(const Rhs& rhs)\n      : ComparisonBase<GtMatcher<Rhs>, Rhs, AnyGt>(rhs) {}\n  static const char* Desc() { return \"is >\"; }\n  static const char* NegatedDesc() { return \"isn't >\"; }\n};\ntemplate <typename Rhs>\nclass LeMatcher : public ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe> {\n public:\n  explicit LeMatcher(const Rhs& rhs)\n      : ComparisonBase<LeMatcher<Rhs>, Rhs, AnyLe>(rhs) {}\n  static const char* Desc() { return \"is <=\"; }\n  static const char* NegatedDesc() { return \"isn't <=\"; }\n};\ntemplate <typename Rhs>\nclass GeMatcher : public ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe> {\n public:\n  explicit GeMatcher(const Rhs& rhs)\n      : ComparisonBase<GeMatcher<Rhs>, Rhs, AnyGe>(rhs) {}\n  static const char* Desc() { return \"is >=\"; }\n  static const char* NegatedDesc() { return \"isn't >=\"; }\n};\n\ntemplate <typename T, typename = typename std::enable_if<\n                          std::is_constructible<std::string, T>::value>::type>\nusing StringLike = T;\n\n// Implements polymorphic matchers MatchesRegex(regex) and\n// ContainsRegex(regex), which can be used as a Matcher<T> as long as\n// T can be converted to a string.\nclass MatchesRegexMatcher {\n public:\n  MatchesRegexMatcher(const RE* regex, bool full_match)\n      : regex_(regex), full_match_(full_match) {}\n\n#if GTEST_INTERNAL_HAS_STRING_VIEW\n  bool MatchAndExplain(const internal::StringView& s,\n                       MatchResultListener* listener) const {\n    return MatchAndExplain(std::string(s), listener);\n  }\n#endif  // GTEST_INTERNAL_HAS_STRING_VIEW\n\n  // Accepts pointer types, particularly:\n  //   const char*\n  //   char*\n  //   const wchar_t*\n  //   wchar_t*\n  template <typename CharType>\n  bool MatchAndExplain(CharType* s, MatchResultListener* listener) const {\n    return s != nullptr && MatchAndExplain(std::string(s), listener);\n  }\n\n  // Matches anything that can convert to std::string.\n  //\n  // This is a template, not just a plain function with const std::string&,\n  // because absl::string_view has some interfering non-explicit constructors.\n  template <class MatcheeStringType>\n  bool MatchAndExplain(const MatcheeStringType& s,\n                       MatchResultListener* /* listener */) const {\n    const std::string& s2(s);\n    return full_match_ ? RE::FullMatch(s2, *regex_)\n                       : RE::PartialMatch(s2, *regex_);\n  }\n\n  void DescribeTo(::std::ostream* os) const {\n    *os << (full_match_ ? \"matches\" : \"contains\") << \" regular expression \";\n    UniversalPrinter<std::string>::Print(regex_->pattern(), os);\n  }\n\n  void DescribeNegationTo(::std::ostream* os) const {\n    *os << \"doesn't \" << (full_match_ ? \"match\" : \"contain\")\n        << \" regular expression \";\n    UniversalPrinter<std::string>::Print(regex_->pattern(), os);\n  }\n\n private:\n  const std::shared_ptr<const RE> regex_;\n  const bool full_match_;\n};\n}  // namespace internal\n\n// Matches a string that fully matches regular expression 'regex'.\n// The matcher takes ownership of 'regex'.\ninline PolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(\n    const internal::RE* regex) {\n  return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, true));\n}\ntemplate <typename T = std::string>\nPolymorphicMatcher<internal::MatchesRegexMatcher> MatchesRegex(\n    const internal::StringLike<T>& regex) {\n  return MatchesRegex(new internal::RE(std::string(regex)));\n}\n\n// Matches a string that contains regular expression 'regex'.\n// The matcher takes ownership of 'regex'.\ninline PolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(\n    const internal::RE* regex) {\n  return MakePolymorphicMatcher(internal::MatchesRegexMatcher(regex, false));\n}\ntemplate <typename T = std::string>\nPolymorphicMatcher<internal::MatchesRegexMatcher> ContainsRegex(\n    const internal::StringLike<T>& regex) {\n  return ContainsRegex(new internal::RE(std::string(regex)));\n}\n\n// Creates a polymorphic matcher that matches anything equal to x.\n// Note: if the parameter of Eq() were declared as const T&, Eq(\"foo\")\n// wouldn't compile.\ntemplate <typename T>\ninline internal::EqMatcher<T> Eq(T x) {\n  return internal::EqMatcher<T>(x);\n}\n\n// Constructs a Matcher<T> from a 'value' of type T.  The constructed\n// matcher matches any value that's equal to 'value'.\ntemplate <typename T>\nMatcher<T>::Matcher(T value) {\n  *this = Eq(value);\n}\n\n// Creates a monomorphic matcher that matches anything with type Lhs\n// and equal to rhs.  A user may need to use this instead of Eq(...)\n// in order to resolve an overloading ambiguity.\n//\n// TypedEq<T>(x) is just a convenient short-hand for Matcher<T>(Eq(x))\n// or Matcher<T>(x), but more readable than the latter.\n//\n// We could define similar monomorphic matchers for other comparison\n// operations (e.g. TypedLt, TypedGe, and etc), but decided not to do\n// it yet as those are used much less than Eq() in practice.  A user\n// can always write Matcher<T>(Lt(5)) to be explicit about the type,\n// for example.\ntemplate <typename Lhs, typename Rhs>\ninline Matcher<Lhs> TypedEq(const Rhs& rhs) {\n  return Eq(rhs);\n}\n\n// Creates a polymorphic matcher that matches anything >= x.\ntemplate <typename Rhs>\ninline internal::GeMatcher<Rhs> Ge(Rhs x) {\n  return internal::GeMatcher<Rhs>(x);\n}\n\n// Creates a polymorphic matcher that matches anything > x.\ntemplate <typename Rhs>\ninline internal::GtMatcher<Rhs> Gt(Rhs x) {\n  return internal::GtMatcher<Rhs>(x);\n}\n\n// Creates a polymorphic matcher that matches anything <= x.\ntemplate <typename Rhs>\ninline internal::LeMatcher<Rhs> Le(Rhs x) {\n  return internal::LeMatcher<Rhs>(x);\n}\n\n// Creates a polymorphic matcher that matches anything < x.\ntemplate <typename Rhs>\ninline internal::LtMatcher<Rhs> Lt(Rhs x) {\n  return internal::LtMatcher<Rhs>(x);\n}\n\n// Creates a polymorphic matcher that matches anything != x.\ntemplate <typename Rhs>\ninline internal::NeMatcher<Rhs> Ne(Rhs x) {\n  return internal::NeMatcher<Rhs>(x);\n}\n}  // namespace testing\n\nGTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251 5046\n\n#endif  // GOOGLETEST_INCLUDE_GTEST_GTEST_MATCHERS_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/include/gtest/gtest-message.h",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// The Google C++ Testing and Mocking Framework (Google Test)\n//\n// This header file defines the Message class.\n//\n// IMPORTANT NOTE: Due to limitation of the C++ language, we have to\n// leave some internal implementation details in this header file.\n// They are clearly marked by comments like this:\n//\n//   // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.\n//\n// Such code is NOT meant to be used by a user directly, and is subject\n// to CHANGE WITHOUT NOTICE.  Therefore DO NOT DEPEND ON IT in a user\n// program!\n\n// IWYU pragma: private, include \"gtest/gtest.h\"\n// IWYU pragma: friend gtest/.*\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_\n#define GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_\n\n#include <limits>\n#include <memory>\n#include <sstream>\n\n#include \"gtest/internal/gtest-port.h\"\n\nGTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \\\n/* class A needs to have dll-interface to be used by clients of class B */)\n\n// Ensures that there is at least one operator<< in the global namespace.\n// See Message& operator<<(...) below for why.\nvoid operator<<(const testing::internal::Secret&, int);\n\nnamespace testing {\n\n// The Message class works like an ostream repeater.\n//\n// Typical usage:\n//\n//   1. You stream a bunch of values to a Message object.\n//      It will remember the text in a stringstream.\n//   2. Then you stream the Message object to an ostream.\n//      This causes the text in the Message to be streamed\n//      to the ostream.\n//\n// For example;\n//\n//   testing::Message foo;\n//   foo << 1 << \" != \" << 2;\n//   std::cout << foo;\n//\n// will print \"1 != 2\".\n//\n// Message is not intended to be inherited from.  In particular, its\n// destructor is not virtual.\n//\n// Note that stringstream behaves differently in gcc and in MSVC.  You\n// can stream a NULL char pointer to it in the former, but not in the\n// latter (it causes an access violation if you do).  The Message\n// class hides this difference by treating a NULL char pointer as\n// \"(null)\".\nclass GTEST_API_ Message {\n private:\n  // The type of basic IO manipulators (endl, ends, and flush) for\n  // narrow streams.\n  typedef std::ostream& (*BasicNarrowIoManip)(std::ostream&);\n\n public:\n  // Constructs an empty Message.\n  Message();\n\n  // Copy constructor.\n  Message(const Message& msg) : ss_(new ::std::stringstream) {  // NOLINT\n    *ss_ << msg.GetString();\n  }\n\n  // Constructs a Message from a C-string.\n  explicit Message(const char* str) : ss_(new ::std::stringstream) {\n    *ss_ << str;\n  }\n\n  // Streams a non-pointer value to this object.\n  template <typename T>\n  inline Message& operator<<(const T& val) {\n        // Some libraries overload << for STL containers.  These\n    // overloads are defined in the global namespace instead of ::std.\n    //\n    // C++'s symbol lookup rule (i.e. Koenig lookup) says that these\n    // overloads are visible in either the std namespace or the global\n    // namespace, but not other namespaces, including the testing\n    // namespace which Google Test's Message class is in.\n    //\n    // To allow STL containers (and other types that has a << operator\n    // defined in the global namespace) to be used in Google Test\n    // assertions, testing::Message must access the custom << operator\n    // from the global namespace.  With this using declaration,\n    // overloads of << defined in the global namespace and those\n    // visible via Koenig lookup are both exposed in this function.\n    using ::operator<<;\n    *ss_ << val;\n    return *this;\n  }\n\n  // Streams a pointer value to this object.\n  //\n  // This function is an overload of the previous one.  When you\n  // stream a pointer to a Message, this definition will be used as it\n  // is more specialized.  (The C++ Standard, section\n  // [temp.func.order].)  If you stream a non-pointer, then the\n  // previous definition will be used.\n  //\n  // The reason for this overload is that streaming a NULL pointer to\n  // ostream is undefined behavior.  Depending on the compiler, you\n  // may get \"0\", \"(nil)\", \"(null)\", or an access violation.  To\n  // ensure consistent result across compilers, we always treat NULL\n  // as \"(null)\".\n  template <typename T>\n  inline Message& operator<<(T* const& pointer) {  // NOLINT\n    if (pointer == nullptr) {\n      *ss_ << \"(null)\";\n    } else {\n      *ss_ << pointer;\n    }\n    return *this;\n  }\n\n  // Since the basic IO manipulators are overloaded for both narrow\n  // and wide streams, we have to provide this specialized definition\n  // of operator <<, even though its body is the same as the\n  // templatized version above.  Without this definition, streaming\n  // endl or other basic IO manipulators to Message will confuse the\n  // compiler.\n  Message& operator<<(BasicNarrowIoManip val) {\n    *ss_ << val;\n    return *this;\n  }\n\n  // Instead of 1/0, we want to see true/false for bool values.\n  Message& operator<<(bool b) { return *this << (b ? \"true\" : \"false\"); }\n\n  // These two overloads allow streaming a wide C string to a Message\n  // using the UTF-8 encoding.\n  Message& operator<<(const wchar_t* wide_c_str);\n  Message& operator<<(wchar_t* wide_c_str);\n\n#if GTEST_HAS_STD_WSTRING\n  // Converts the given wide string to a narrow string using the UTF-8\n  // encoding, and streams the result to this Message object.\n  Message& operator<<(const ::std::wstring& wstr);\n#endif  // GTEST_HAS_STD_WSTRING\n\n  // Gets the text streamed to this object so far as an std::string.\n  // Each '\\0' character in the buffer is replaced with \"\\\\0\".\n  //\n  // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.\n  std::string GetString() const;\n\n private:\n  // We'll hold the text streamed to this object here.\n  const std::unique_ptr< ::std::stringstream> ss_;\n\n  // We declare (but don't implement) this to prevent the compiler\n  // from implementing the assignment operator.\n  void operator=(const Message&);\n};\n\n// Streams a Message to an ostream.\ninline std::ostream& operator<<(std::ostream& os, const Message& sb) {\n  return os << sb.GetString();\n}\n\nnamespace internal {\n\n// Converts a streamable value to an std::string.  A NULL pointer is\n// converted to \"(null)\".  When the input value is a ::string,\n// ::std::string, ::wstring, or ::std::wstring object, each NUL\n// character in it is replaced with \"\\\\0\".\ntemplate <typename T>\nstd::string StreamableToString(const T& streamable) {\n  return (Message() << streamable).GetString();\n}\n\n}  // namespace internal\n}  // namespace testing\n\nGTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251\n\n#endif  // GOOGLETEST_INCLUDE_GTEST_GTEST_MESSAGE_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/include/gtest/gtest-param-test.h",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Macros and functions for implementing parameterized tests\n// in Google C++ Testing and Mocking Framework (Google Test)\n\n// IWYU pragma: private, include \"gtest/gtest.h\"\n// IWYU pragma: friend gtest/.*\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_\n#define GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_\n\n// Value-parameterized tests allow you to test your code with different\n// parameters without writing multiple copies of the same test.\n//\n// Here is how you use value-parameterized tests:\n\n#if 0\n\n// To write value-parameterized tests, first you should define a fixture\n// class. It is usually derived from testing::TestWithParam<T> (see below for\n// another inheritance scheme that's sometimes useful in more complicated\n// class hierarchies), where the type of your parameter values.\n// TestWithParam<T> is itself derived from testing::Test. T can be any\n// copyable type. If it's a raw pointer, you are responsible for managing the\n// lifespan of the pointed values.\n\nclass FooTest : public ::testing::TestWithParam<const char*> {\n  // You can implement all the usual class fixture members here.\n};\n\n// Then, use the TEST_P macro to define as many parameterized tests\n// for this fixture as you want. The _P suffix is for \"parameterized\"\n// or \"pattern\", whichever you prefer to think.\n\nTEST_P(FooTest, DoesBlah) {\n  // Inside a test, access the test parameter with the GetParam() method\n  // of the TestWithParam<T> class:\n  EXPECT_TRUE(foo.Blah(GetParam()));\n  ...\n}\n\nTEST_P(FooTest, HasBlahBlah) {\n  ...\n}\n\n// Finally, you can use INSTANTIATE_TEST_SUITE_P to instantiate the test\n// case with any set of parameters you want. Google Test defines a number\n// of functions for generating test parameters. They return what we call\n// (surprise!) parameter generators. Here is a summary of them, which\n// are all in the testing namespace:\n//\n//\n//  Range(begin, end [, step]) - Yields values {begin, begin+step,\n//                               begin+step+step, ...}. The values do not\n//                               include end. step defaults to 1.\n//  Values(v1, v2, ..., vN)    - Yields values {v1, v2, ..., vN}.\n//  ValuesIn(container)        - Yields values from a C-style array, an STL\n//  ValuesIn(begin,end)          container, or an iterator range [begin, end).\n//  Bool()                     - Yields sequence {false, true}.\n//  Combine(g1, g2, ..., gN)   - Yields all combinations (the Cartesian product\n//                               for the math savvy) of the values generated\n//                               by the N generators.\n//\n// For more details, see comments at the definitions of these functions below\n// in this file.\n//\n// The following statement will instantiate tests from the FooTest test suite\n// each with parameter values \"meeny\", \"miny\", and \"moe\".\n\nINSTANTIATE_TEST_SUITE_P(InstantiationName,\n                         FooTest,\n                         Values(\"meeny\", \"miny\", \"moe\"));\n\n// To distinguish different instances of the pattern, (yes, you\n// can instantiate it more than once) the first argument to the\n// INSTANTIATE_TEST_SUITE_P macro is a prefix that will be added to the\n// actual test suite name. Remember to pick unique prefixes for different\n// instantiations. The tests from the instantiation above will have\n// these names:\n//\n//    * InstantiationName/FooTest.DoesBlah/0 for \"meeny\"\n//    * InstantiationName/FooTest.DoesBlah/1 for \"miny\"\n//    * InstantiationName/FooTest.DoesBlah/2 for \"moe\"\n//    * InstantiationName/FooTest.HasBlahBlah/0 for \"meeny\"\n//    * InstantiationName/FooTest.HasBlahBlah/1 for \"miny\"\n//    * InstantiationName/FooTest.HasBlahBlah/2 for \"moe\"\n//\n// You can use these names in --gtest_filter.\n//\n// This statement will instantiate all tests from FooTest again, each\n// with parameter values \"cat\" and \"dog\":\n\nconst char* pets[] = {\"cat\", \"dog\"};\nINSTANTIATE_TEST_SUITE_P(AnotherInstantiationName, FooTest, ValuesIn(pets));\n\n// The tests from the instantiation above will have these names:\n//\n//    * AnotherInstantiationName/FooTest.DoesBlah/0 for \"cat\"\n//    * AnotherInstantiationName/FooTest.DoesBlah/1 for \"dog\"\n//    * AnotherInstantiationName/FooTest.HasBlahBlah/0 for \"cat\"\n//    * AnotherInstantiationName/FooTest.HasBlahBlah/1 for \"dog\"\n//\n// Please note that INSTANTIATE_TEST_SUITE_P will instantiate all tests\n// in the given test suite, whether their definitions come before or\n// AFTER the INSTANTIATE_TEST_SUITE_P statement.\n//\n// Please also note that generator expressions (including parameters to the\n// generators) are evaluated in InitGoogleTest(), after main() has started.\n// This allows the user on one hand, to adjust generator parameters in order\n// to dynamically determine a set of tests to run and on the other hand,\n// give the user a chance to inspect the generated tests with Google Test\n// reflection API before RUN_ALL_TESTS() is executed.\n//\n// You can see samples/sample7_unittest.cc and samples/sample8_unittest.cc\n// for more examples.\n//\n// In the future, we plan to publish the API for defining new parameter\n// generators. But for now this interface remains part of the internal\n// implementation and is subject to change.\n//\n//\n// A parameterized test fixture must be derived from testing::Test and from\n// testing::WithParamInterface<T>, where T is the type of the parameter\n// values. Inheriting from TestWithParam<T> satisfies that requirement because\n// TestWithParam<T> inherits from both Test and WithParamInterface. In more\n// complicated hierarchies, however, it is occasionally useful to inherit\n// separately from Test and WithParamInterface. For example:\n\nclass BaseTest : public ::testing::Test {\n  // You can inherit all the usual members for a non-parameterized test\n  // fixture here.\n};\n\nclass DerivedTest : public BaseTest, public ::testing::WithParamInterface<int> {\n  // The usual test fixture members go here too.\n};\n\nTEST_F(BaseTest, HasFoo) {\n  // This is an ordinary non-parameterized test.\n}\n\nTEST_P(DerivedTest, DoesBlah) {\n  // GetParam works just the same here as if you inherit from TestWithParam.\n  EXPECT_TRUE(foo.Blah(GetParam()));\n}\n\n#endif  // 0\n\n#include <iterator>\n#include <utility>\n\n#include \"gtest/internal/gtest-internal.h\"\n#include \"gtest/internal/gtest-param-util.h\"\n#include \"gtest/internal/gtest-port.h\"\n\nnamespace testing {\n\n// Functions producing parameter generators.\n//\n// Google Test uses these generators to produce parameters for value-\n// parameterized tests. When a parameterized test suite is instantiated\n// with a particular generator, Google Test creates and runs tests\n// for each element in the sequence produced by the generator.\n//\n// In the following sample, tests from test suite FooTest are instantiated\n// each three times with parameter values 3, 5, and 8:\n//\n// class FooTest : public TestWithParam<int> { ... };\n//\n// TEST_P(FooTest, TestThis) {\n// }\n// TEST_P(FooTest, TestThat) {\n// }\n// INSTANTIATE_TEST_SUITE_P(TestSequence, FooTest, Values(3, 5, 8));\n//\n\n// Range() returns generators providing sequences of values in a range.\n//\n// Synopsis:\n// Range(start, end)\n//   - returns a generator producing a sequence of values {start, start+1,\n//     start+2, ..., }.\n// Range(start, end, step)\n//   - returns a generator producing a sequence of values {start, start+step,\n//     start+step+step, ..., }.\n// Notes:\n//   * The generated sequences never include end. For example, Range(1, 5)\n//     returns a generator producing a sequence {1, 2, 3, 4}. Range(1, 9, 2)\n//     returns a generator producing {1, 3, 5, 7}.\n//   * start and end must have the same type. That type may be any integral or\n//     floating-point type or a user defined type satisfying these conditions:\n//     * It must be assignable (have operator=() defined).\n//     * It must have operator+() (operator+(int-compatible type) for\n//       two-operand version).\n//     * It must have operator<() defined.\n//     Elements in the resulting sequences will also have that type.\n//   * Condition start < end must be satisfied in order for resulting sequences\n//     to contain any elements.\n//\ntemplate <typename T, typename IncrementT>\ninternal::ParamGenerator<T> Range(T start, T end, IncrementT step) {\n  return internal::ParamGenerator<T>(\n      new internal::RangeGenerator<T, IncrementT>(start, end, step));\n}\n\ntemplate <typename T>\ninternal::ParamGenerator<T> Range(T start, T end) {\n  return Range(start, end, 1);\n}\n\n// ValuesIn() function allows generation of tests with parameters coming from\n// a container.\n//\n// Synopsis:\n// ValuesIn(const T (&array)[N])\n//   - returns a generator producing sequences with elements from\n//     a C-style array.\n// ValuesIn(const Container& container)\n//   - returns a generator producing sequences with elements from\n//     an STL-style container.\n// ValuesIn(Iterator begin, Iterator end)\n//   - returns a generator producing sequences with elements from\n//     a range [begin, end) defined by a pair of STL-style iterators. These\n//     iterators can also be plain C pointers.\n//\n// Please note that ValuesIn copies the values from the containers\n// passed in and keeps them to generate tests in RUN_ALL_TESTS().\n//\n// Examples:\n//\n// This instantiates tests from test suite StringTest\n// each with C-string values of \"foo\", \"bar\", and \"baz\":\n//\n// const char* strings[] = {\"foo\", \"bar\", \"baz\"};\n// INSTANTIATE_TEST_SUITE_P(StringSequence, StringTest, ValuesIn(strings));\n//\n// This instantiates tests from test suite StlStringTest\n// each with STL strings with values \"a\" and \"b\":\n//\n// ::std::vector< ::std::string> GetParameterStrings() {\n//   ::std::vector< ::std::string> v;\n//   v.push_back(\"a\");\n//   v.push_back(\"b\");\n//   return v;\n// }\n//\n// INSTANTIATE_TEST_SUITE_P(CharSequence,\n//                          StlStringTest,\n//                          ValuesIn(GetParameterStrings()));\n//\n//\n// This will also instantiate tests from CharTest\n// each with parameter values 'a' and 'b':\n//\n// ::std::list<char> GetParameterChars() {\n//   ::std::list<char> list;\n//   list.push_back('a');\n//   list.push_back('b');\n//   return list;\n// }\n// ::std::list<char> l = GetParameterChars();\n// INSTANTIATE_TEST_SUITE_P(CharSequence2,\n//                          CharTest,\n//                          ValuesIn(l.begin(), l.end()));\n//\ntemplate <typename ForwardIterator>\ninternal::ParamGenerator<\n    typename std::iterator_traits<ForwardIterator>::value_type>\nValuesIn(ForwardIterator begin, ForwardIterator end) {\n  typedef typename std::iterator_traits<ForwardIterator>::value_type ParamType;\n  return internal::ParamGenerator<ParamType>(\n      new internal::ValuesInIteratorRangeGenerator<ParamType>(begin, end));\n}\n\ntemplate <typename T, size_t N>\ninternal::ParamGenerator<T> ValuesIn(const T (&array)[N]) {\n  return ValuesIn(array, array + N);\n}\n\ntemplate <class Container>\ninternal::ParamGenerator<typename Container::value_type> ValuesIn(\n    const Container& container) {\n  return ValuesIn(container.begin(), container.end());\n}\n\n// Values() allows generating tests from explicitly specified list of\n// parameters.\n//\n// Synopsis:\n// Values(T v1, T v2, ..., T vN)\n//   - returns a generator producing sequences with elements v1, v2, ..., vN.\n//\n// For example, this instantiates tests from test suite BarTest each\n// with values \"one\", \"two\", and \"three\":\n//\n// INSTANTIATE_TEST_SUITE_P(NumSequence,\n//                          BarTest,\n//                          Values(\"one\", \"two\", \"three\"));\n//\n// This instantiates tests from test suite BazTest each with values 1, 2, 3.5.\n// The exact type of values will depend on the type of parameter in BazTest.\n//\n// INSTANTIATE_TEST_SUITE_P(FloatingNumbers, BazTest, Values(1, 2, 3.5));\n//\n//\ntemplate <typename... T>\ninternal::ValueArray<T...> Values(T... v) {\n  return internal::ValueArray<T...>(std::move(v)...);\n}\n\n// Bool() allows generating tests with parameters in a set of (false, true).\n//\n// Synopsis:\n// Bool()\n//   - returns a generator producing sequences with elements {false, true}.\n//\n// It is useful when testing code that depends on Boolean flags. Combinations\n// of multiple flags can be tested when several Bool()'s are combined using\n// Combine() function.\n//\n// In the following example all tests in the test suite FlagDependentTest\n// will be instantiated twice with parameters false and true.\n//\n// class FlagDependentTest : public testing::TestWithParam<bool> {\n//   virtual void SetUp() {\n//     external_flag = GetParam();\n//   }\n// }\n// INSTANTIATE_TEST_SUITE_P(BoolSequence, FlagDependentTest, Bool());\n//\ninline internal::ParamGenerator<bool> Bool() { return Values(false, true); }\n\n// Combine() allows the user to combine two or more sequences to produce\n// values of a Cartesian product of those sequences' elements.\n//\n// Synopsis:\n// Combine(gen1, gen2, ..., genN)\n//   - returns a generator producing sequences with elements coming from\n//     the Cartesian product of elements from the sequences generated by\n//     gen1, gen2, ..., genN. The sequence elements will have a type of\n//     std::tuple<T1, T2, ..., TN> where T1, T2, ..., TN are the types\n//     of elements from sequences produces by gen1, gen2, ..., genN.\n//\n// Example:\n//\n// This will instantiate tests in test suite AnimalTest each one with\n// the parameter values tuple(\"cat\", BLACK), tuple(\"cat\", WHITE),\n// tuple(\"dog\", BLACK), and tuple(\"dog\", WHITE):\n//\n// enum Color { BLACK, GRAY, WHITE };\n// class AnimalTest\n//     : public testing::TestWithParam<std::tuple<const char*, Color> > {...};\n//\n// TEST_P(AnimalTest, AnimalLooksNice) {...}\n//\n// INSTANTIATE_TEST_SUITE_P(AnimalVariations, AnimalTest,\n//                          Combine(Values(\"cat\", \"dog\"),\n//                                  Values(BLACK, WHITE)));\n//\n// This will instantiate tests in FlagDependentTest with all variations of two\n// Boolean flags:\n//\n// class FlagDependentTest\n//     : public testing::TestWithParam<std::tuple<bool, bool> > {\n//   virtual void SetUp() {\n//     // Assigns external_flag_1 and external_flag_2 values from the tuple.\n//     std::tie(external_flag_1, external_flag_2) = GetParam();\n//   }\n// };\n//\n// TEST_P(FlagDependentTest, TestFeature1) {\n//   // Test your code using external_flag_1 and external_flag_2 here.\n// }\n// INSTANTIATE_TEST_SUITE_P(TwoBoolSequence, FlagDependentTest,\n//                          Combine(Bool(), Bool()));\n//\ntemplate <typename... Generator>\ninternal::CartesianProductHolder<Generator...> Combine(const Generator&... g) {\n  return internal::CartesianProductHolder<Generator...>(g...);\n}\n\n#define TEST_P(test_suite_name, test_name)                                     \\\n  class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)                     \\\n      : public test_suite_name {                                               \\\n   public:                                                                     \\\n    GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() {}                    \\\n    void TestBody() override;                                                  \\\n                                                                               \\\n   private:                                                                    \\\n    static int AddToRegistry() {                                               \\\n      ::testing::UnitTest::GetInstance()                                       \\\n          ->parameterized_test_registry()                                      \\\n          .GetTestSuitePatternHolder<test_suite_name>(                         \\\n              GTEST_STRINGIFY_(test_suite_name),                               \\\n              ::testing::internal::CodeLocation(__FILE__, __LINE__))           \\\n          ->AddTestPattern(                                                    \\\n              GTEST_STRINGIFY_(test_suite_name), GTEST_STRINGIFY_(test_name),  \\\n              new ::testing::internal::TestMetaFactory<GTEST_TEST_CLASS_NAME_( \\\n                  test_suite_name, test_name)>(),                              \\\n              ::testing::internal::CodeLocation(__FILE__, __LINE__));          \\\n      return 0;                                                                \\\n    }                                                                          \\\n    static int gtest_registering_dummy_ GTEST_ATTRIBUTE_UNUSED_;               \\\n    GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)                         \\\n    (const GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) &) = delete;     \\\n    GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) & operator=(            \\\n        const GTEST_TEST_CLASS_NAME_(test_suite_name,                          \\\n                                     test_name) &) = delete; /* NOLINT */      \\\n  };                                                                           \\\n  int GTEST_TEST_CLASS_NAME_(test_suite_name,                                  \\\n                             test_name)::gtest_registering_dummy_ =            \\\n      GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::AddToRegistry();     \\\n  void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()\n\n// The last argument to INSTANTIATE_TEST_SUITE_P allows the user to specify\n// generator and an optional function or functor that generates custom test name\n// suffixes based on the test parameters. Such a function or functor should\n// accept one argument of type testing::TestParamInfo<class ParamType>, and\n// return std::string.\n//\n// testing::PrintToStringParamName is a builtin test suffix generator that\n// returns the value of testing::PrintToString(GetParam()).\n//\n// Note: test names must be non-empty, unique, and may only contain ASCII\n// alphanumeric characters or underscore. Because PrintToString adds quotes\n// to std::string and C strings, it won't work for these types.\n\n#define GTEST_EXPAND_(arg) arg\n#define GTEST_GET_FIRST_(first, ...) first\n#define GTEST_GET_SECOND_(first, second, ...) second\n\n#define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name, ...)               \\\n  static ::testing::internal::ParamGenerator<test_suite_name::ParamType>     \\\n      gtest_##prefix##test_suite_name##_EvalGenerator_() {                   \\\n    return GTEST_EXPAND_(GTEST_GET_FIRST_(__VA_ARGS__, DUMMY_PARAM_));       \\\n  }                                                                          \\\n  static ::std::string gtest_##prefix##test_suite_name##_EvalGenerateName_(  \\\n      const ::testing::TestParamInfo<test_suite_name::ParamType>& info) {    \\\n    if (::testing::internal::AlwaysFalse()) {                                \\\n      ::testing::internal::TestNotEmpty(GTEST_EXPAND_(GTEST_GET_SECOND_(     \\\n          __VA_ARGS__,                                                       \\\n          ::testing::internal::DefaultParamName<test_suite_name::ParamType>, \\\n          DUMMY_PARAM_)));                                                   \\\n      auto t = std::make_tuple(__VA_ARGS__);                                 \\\n      static_assert(std::tuple_size<decltype(t)>::value <= 2,                \\\n                    \"Too Many Args!\");                                       \\\n    }                                                                        \\\n    return ((GTEST_EXPAND_(GTEST_GET_SECOND_(                                \\\n        __VA_ARGS__,                                                         \\\n        ::testing::internal::DefaultParamName<test_suite_name::ParamType>,   \\\n        DUMMY_PARAM_))))(info);                                              \\\n  }                                                                          \\\n  static int gtest_##prefix##test_suite_name##_dummy_                        \\\n      GTEST_ATTRIBUTE_UNUSED_ =                                              \\\n          ::testing::UnitTest::GetInstance()                                 \\\n              ->parameterized_test_registry()                                \\\n              .GetTestSuitePatternHolder<test_suite_name>(                   \\\n                  GTEST_STRINGIFY_(test_suite_name),                         \\\n                  ::testing::internal::CodeLocation(__FILE__, __LINE__))     \\\n              ->AddTestSuiteInstantiation(                                   \\\n                  GTEST_STRINGIFY_(prefix),                                  \\\n                  &gtest_##prefix##test_suite_name##_EvalGenerator_,         \\\n                  &gtest_##prefix##test_suite_name##_EvalGenerateName_,      \\\n                  __FILE__, __LINE__)\n\n// Allow Marking a Parameterized test class as not needing to be instantiated.\n#define GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(T)                  \\\n  namespace gtest_do_not_use_outside_namespace_scope {}                   \\\n  static const ::testing::internal::MarkAsIgnored gtest_allow_ignore_##T( \\\n      GTEST_STRINGIFY_(T))\n\n// Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n#define INSTANTIATE_TEST_CASE_P                                            \\\n  static_assert(::testing::internal::InstantiateTestCase_P_IsDeprecated(), \\\n                \"\");                                                       \\\n  INSTANTIATE_TEST_SUITE_P\n#endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n}  // namespace testing\n\n#endif  // GOOGLETEST_INCLUDE_GTEST_GTEST_PARAM_TEST_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/include/gtest/gtest-printers.h",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Test - The Google C++ Testing and Mocking Framework\n//\n// This file implements a universal value printer that can print a\n// value of any type T:\n//\n//   void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);\n//\n// A user can teach this function how to print a class type T by\n// defining either operator<<() or PrintTo() in the namespace that\n// defines T.  More specifically, the FIRST defined function in the\n// following list will be used (assuming T is defined in namespace\n// foo):\n//\n//   1. foo::PrintTo(const T&, ostream*)\n//   2. operator<<(ostream&, const T&) defined in either foo or the\n//      global namespace.\n//\n// However if T is an STL-style container then it is printed element-wise\n// unless foo::PrintTo(const T&, ostream*) is defined. Note that\n// operator<<() is ignored for container types.\n//\n// If none of the above is defined, it will print the debug string of\n// the value if it is a protocol buffer, or print the raw bytes in the\n// value otherwise.\n//\n// To aid debugging: when T is a reference type, the address of the\n// value is also printed; when T is a (const) char pointer, both the\n// pointer value and the NUL-terminated string it points to are\n// printed.\n//\n// We also provide some convenient wrappers:\n//\n//   // Prints a value to a string.  For a (const or not) char\n//   // pointer, the NUL-terminated string (but not the pointer) is\n//   // printed.\n//   std::string ::testing::PrintToString(const T& value);\n//\n//   // Prints a value tersely: for a reference type, the referenced\n//   // value (but not the address) is printed; for a (const or not) char\n//   // pointer, the NUL-terminated string (but not the pointer) is\n//   // printed.\n//   void ::testing::internal::UniversalTersePrint(const T& value, ostream*);\n//\n//   // Prints value using the type inferred by the compiler.  The difference\n//   // from UniversalTersePrint() is that this function prints both the\n//   // pointer and the NUL-terminated string for a (const or not) char pointer.\n//   void ::testing::internal::UniversalPrint(const T& value, ostream*);\n//\n//   // Prints the fields of a tuple tersely to a string vector, one\n//   // element for each field. Tuple support must be enabled in\n//   // gtest-port.h.\n//   std::vector<string> UniversalTersePrintTupleFieldsToStrings(\n//       const Tuple& value);\n//\n// Known limitation:\n//\n// The print primitives print the elements of an STL-style container\n// using the compiler-inferred type of *iter where iter is a\n// const_iterator of the container.  When const_iterator is an input\n// iterator but not a forward iterator, this inferred type may not\n// match value_type, and the print output may be incorrect.  In\n// practice, this is rarely a problem as for most containers\n// const_iterator is a forward iterator.  We'll fix this if there's an\n// actual need for it.  Note that this fix cannot rely on value_type\n// being defined as many user-defined container types don't have\n// value_type.\n\n// IWYU pragma: private, include \"gtest/gtest.h\"\n// IWYU pragma: friend gtest/.*\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_\n#define GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_\n\n#include <functional>\n#include <memory>\n#include <ostream>  // NOLINT\n#include <sstream>\n#include <string>\n#include <tuple>\n#include <type_traits>\n#include <utility>\n#include <vector>\n\n#include \"gtest/internal/gtest-internal.h\"\n#include \"gtest/internal/gtest-port.h\"\n\nnamespace testing {\n\n// Definitions in the internal* namespaces are subject to change without notice.\n// DO NOT USE THEM IN USER CODE!\nnamespace internal {\n\ntemplate <typename T>\nvoid UniversalPrint(const T& value, ::std::ostream* os);\n\n// Used to print an STL-style container when the user doesn't define\n// a PrintTo() for it.\nstruct ContainerPrinter {\n  template <typename T,\n            typename = typename std::enable_if<\n                (sizeof(IsContainerTest<T>(0)) == sizeof(IsContainer)) &&\n                !IsRecursiveContainer<T>::value>::type>\n  static void PrintValue(const T& container, std::ostream* os) {\n    const size_t kMaxCount = 32;  // The maximum number of elements to print.\n    *os << '{';\n    size_t count = 0;\n    for (auto&& elem : container) {\n      if (count > 0) {\n        *os << ',';\n        if (count == kMaxCount) {  // Enough has been printed.\n          *os << \" ...\";\n          break;\n        }\n      }\n      *os << ' ';\n      // We cannot call PrintTo(elem, os) here as PrintTo() doesn't\n      // handle `elem` being a native array.\n      internal::UniversalPrint(elem, os);\n      ++count;\n    }\n\n    if (count > 0) {\n      *os << ' ';\n    }\n    *os << '}';\n  }\n};\n\n// Used to print a pointer that is neither a char pointer nor a member\n// pointer, when the user doesn't define PrintTo() for it.  (A member\n// variable pointer or member function pointer doesn't really point to\n// a location in the address space.  Their representation is\n// implementation-defined.  Therefore they will be printed as raw\n// bytes.)\nstruct FunctionPointerPrinter {\n  template <typename T, typename = typename std::enable_if<\n                            std::is_function<T>::value>::type>\n  static void PrintValue(T* p, ::std::ostream* os) {\n    if (p == nullptr) {\n      *os << \"NULL\";\n    } else {\n      // T is a function type, so '*os << p' doesn't do what we want\n      // (it just prints p as bool).  We want to print p as a const\n      // void*.\n      *os << reinterpret_cast<const void*>(p);\n    }\n  }\n};\n\nstruct PointerPrinter {\n  template <typename T>\n  static void PrintValue(T* p, ::std::ostream* os) {\n    if (p == nullptr) {\n      *os << \"NULL\";\n    } else {\n      // T is not a function type.  We just call << to print p,\n      // relying on ADL to pick up user-defined << for their pointer\n      // types, if any.\n      *os << p;\n    }\n  }\n};\n\nnamespace internal_stream_operator_without_lexical_name_lookup {\n\n// The presence of an operator<< here will terminate lexical scope lookup\n// straight away (even though it cannot be a match because of its argument\n// types). Thus, the two operator<< calls in StreamPrinter will find only ADL\n// candidates.\nstruct LookupBlocker {};\nvoid operator<<(LookupBlocker, LookupBlocker);\n\nstruct StreamPrinter {\n  template <typename T,\n            // Don't accept member pointers here. We'd print them via implicit\n            // conversion to bool, which isn't useful.\n            typename = typename std::enable_if<\n                !std::is_member_pointer<T>::value>::type,\n            // Only accept types for which we can find a streaming operator via\n            // ADL (possibly involving implicit conversions).\n            typename = decltype(std::declval<std::ostream&>()\n                                << std::declval<const T&>())>\n  static void PrintValue(const T& value, ::std::ostream* os) {\n    // Call streaming operator found by ADL, possibly with implicit conversions\n    // of the arguments.\n    *os << value;\n  }\n};\n\n}  // namespace internal_stream_operator_without_lexical_name_lookup\n\nstruct ProtobufPrinter {\n  // We print a protobuf using its ShortDebugString() when the string\n  // doesn't exceed this many characters; otherwise we print it using\n  // DebugString() for better readability.\n  static const size_t kProtobufOneLinerMaxLength = 50;\n\n  template <typename T,\n            typename = typename std::enable_if<\n                internal::HasDebugStringAndShortDebugString<T>::value>::type>\n  static void PrintValue(const T& value, ::std::ostream* os) {\n    std::string pretty_str = value.ShortDebugString();\n    if (pretty_str.length() > kProtobufOneLinerMaxLength) {\n      pretty_str = \"\\n\" + value.DebugString();\n    }\n    *os << (\"<\" + pretty_str + \">\");\n  }\n};\n\nstruct ConvertibleToIntegerPrinter {\n  // Since T has no << operator or PrintTo() but can be implicitly\n  // converted to BiggestInt, we print it as a BiggestInt.\n  //\n  // Most likely T is an enum type (either named or unnamed), in which\n  // case printing it as an integer is the desired behavior.  In case\n  // T is not an enum, printing it as an integer is the best we can do\n  // given that it has no user-defined printer.\n  static void PrintValue(internal::BiggestInt value, ::std::ostream* os) {\n    *os << value;\n  }\n};\n\nstruct ConvertibleToStringViewPrinter {\n#if GTEST_INTERNAL_HAS_STRING_VIEW\n  static void PrintValue(internal::StringView value, ::std::ostream* os) {\n    internal::UniversalPrint(value, os);\n  }\n#endif\n};\n\n// Prints the given number of bytes in the given object to the given\n// ostream.\nGTEST_API_ void PrintBytesInObjectTo(const unsigned char* obj_bytes,\n                                     size_t count, ::std::ostream* os);\nstruct RawBytesPrinter {\n  // SFINAE on `sizeof` to make sure we have a complete type.\n  template <typename T, size_t = sizeof(T)>\n  static void PrintValue(const T& value, ::std::ostream* os) {\n    PrintBytesInObjectTo(\n        static_cast<const unsigned char*>(\n            // Load bearing cast to void* to support iOS\n            reinterpret_cast<const void*>(std::addressof(value))),\n        sizeof(value), os);\n  }\n};\n\nstruct FallbackPrinter {\n  template <typename T>\n  static void PrintValue(const T&, ::std::ostream* os) {\n    *os << \"(incomplete type)\";\n  }\n};\n\n// Try every printer in order and return the first one that works.\ntemplate <typename T, typename E, typename Printer, typename... Printers>\nstruct FindFirstPrinter : FindFirstPrinter<T, E, Printers...> {};\n\ntemplate <typename T, typename Printer, typename... Printers>\nstruct FindFirstPrinter<\n    T, decltype(Printer::PrintValue(std::declval<const T&>(), nullptr)),\n    Printer, Printers...> {\n  using type = Printer;\n};\n\n// Select the best printer in the following order:\n//  - Print containers (they have begin/end/etc).\n//  - Print function pointers.\n//  - Print object pointers.\n//  - Use the stream operator, if available.\n//  - Print protocol buffers.\n//  - Print types convertible to BiggestInt.\n//  - Print types convertible to StringView, if available.\n//  - Fallback to printing the raw bytes of the object.\ntemplate <typename T>\nvoid PrintWithFallback(const T& value, ::std::ostream* os) {\n  using Printer = typename FindFirstPrinter<\n      T, void, ContainerPrinter, FunctionPointerPrinter, PointerPrinter,\n      internal_stream_operator_without_lexical_name_lookup::StreamPrinter,\n      ProtobufPrinter, ConvertibleToIntegerPrinter,\n      ConvertibleToStringViewPrinter, RawBytesPrinter, FallbackPrinter>::type;\n  Printer::PrintValue(value, os);\n}\n\n// FormatForComparison<ToPrint, OtherOperand>::Format(value) formats a\n// value of type ToPrint that is an operand of a comparison assertion\n// (e.g. ASSERT_EQ).  OtherOperand is the type of the other operand in\n// the comparison, and is used to help determine the best way to\n// format the value.  In particular, when the value is a C string\n// (char pointer) and the other operand is an STL string object, we\n// want to format the C string as a string, since we know it is\n// compared by value with the string object.  If the value is a char\n// pointer but the other operand is not an STL string object, we don't\n// know whether the pointer is supposed to point to a NUL-terminated\n// string, and thus want to print it as a pointer to be safe.\n//\n// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.\n\n// The default case.\ntemplate <typename ToPrint, typename OtherOperand>\nclass FormatForComparison {\n public:\n  static ::std::string Format(const ToPrint& value) {\n    return ::testing::PrintToString(value);\n  }\n};\n\n// Array.\ntemplate <typename ToPrint, size_t N, typename OtherOperand>\nclass FormatForComparison<ToPrint[N], OtherOperand> {\n public:\n  static ::std::string Format(const ToPrint* value) {\n    return FormatForComparison<const ToPrint*, OtherOperand>::Format(value);\n  }\n};\n\n// By default, print C string as pointers to be safe, as we don't know\n// whether they actually point to a NUL-terminated string.\n\n#define GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(CharType)                \\\n  template <typename OtherOperand>                                      \\\n  class FormatForComparison<CharType*, OtherOperand> {                  \\\n   public:                                                              \\\n    static ::std::string Format(CharType* value) {                      \\\n      return ::testing::PrintToString(static_cast<const void*>(value)); \\\n    }                                                                   \\\n  }\n\nGTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char);\nGTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char);\nGTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(wchar_t);\nGTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const wchar_t);\n#ifdef __cpp_lib_char8_t\nGTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char8_t);\nGTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char8_t);\n#endif\nGTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char16_t);\nGTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char16_t);\nGTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(char32_t);\nGTEST_IMPL_FORMAT_C_STRING_AS_POINTER_(const char32_t);\n\n#undef GTEST_IMPL_FORMAT_C_STRING_AS_POINTER_\n\n// If a C string is compared with an STL string object, we know it's meant\n// to point to a NUL-terminated string, and thus can print it as a string.\n\n#define GTEST_IMPL_FORMAT_C_STRING_AS_STRING_(CharType, OtherStringType) \\\n  template <>                                                            \\\n  class FormatForComparison<CharType*, OtherStringType> {                \\\n   public:                                                               \\\n    static ::std::string Format(CharType* value) {                       \\\n      return ::testing::PrintToString(value);                            \\\n    }                                                                    \\\n  }\n\nGTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char, ::std::string);\nGTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char, ::std::string);\n#ifdef __cpp_char8_t\nGTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char8_t, ::std::u8string);\nGTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char8_t, ::std::u8string);\n#endif\nGTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char16_t, ::std::u16string);\nGTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char16_t, ::std::u16string);\nGTEST_IMPL_FORMAT_C_STRING_AS_STRING_(char32_t, ::std::u32string);\nGTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const char32_t, ::std::u32string);\n\n#if GTEST_HAS_STD_WSTRING\nGTEST_IMPL_FORMAT_C_STRING_AS_STRING_(wchar_t, ::std::wstring);\nGTEST_IMPL_FORMAT_C_STRING_AS_STRING_(const wchar_t, ::std::wstring);\n#endif\n\n#undef GTEST_IMPL_FORMAT_C_STRING_AS_STRING_\n\n// Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc)\n// operand to be used in a failure message.  The type (but not value)\n// of the other operand may affect the format.  This allows us to\n// print a char* as a raw pointer when it is compared against another\n// char* or void*, and print it as a C string when it is compared\n// against an std::string object, for example.\n//\n// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.\ntemplate <typename T1, typename T2>\nstd::string FormatForComparisonFailureMessage(const T1& value,\n                                              const T2& /* other_operand */) {\n  return FormatForComparison<T1, T2>::Format(value);\n}\n\n// UniversalPrinter<T>::Print(value, ostream_ptr) prints the given\n// value to the given ostream.  The caller must ensure that\n// 'ostream_ptr' is not NULL, or the behavior is undefined.\n//\n// We define UniversalPrinter as a class template (as opposed to a\n// function template), as we need to partially specialize it for\n// reference types, which cannot be done with function templates.\ntemplate <typename T>\nclass UniversalPrinter;\n\n// Prints the given value using the << operator if it has one;\n// otherwise prints the bytes in it.  This is what\n// UniversalPrinter<T>::Print() does when PrintTo() is not specialized\n// or overloaded for type T.\n//\n// A user can override this behavior for a class type Foo by defining\n// an overload of PrintTo() in the namespace where Foo is defined.  We\n// give the user this option as sometimes defining a << operator for\n// Foo is not desirable (e.g. the coding style may prevent doing it,\n// or there is already a << operator but it doesn't do what the user\n// wants).\ntemplate <typename T>\nvoid PrintTo(const T& value, ::std::ostream* os) {\n  internal::PrintWithFallback(value, os);\n}\n\n// The following list of PrintTo() overloads tells\n// UniversalPrinter<T>::Print() how to print standard types (built-in\n// types, strings, plain arrays, and pointers).\n\n// Overloads for various char types.\nGTEST_API_ void PrintTo(unsigned char c, ::std::ostream* os);\nGTEST_API_ void PrintTo(signed char c, ::std::ostream* os);\ninline void PrintTo(char c, ::std::ostream* os) {\n  // When printing a plain char, we always treat it as unsigned.  This\n  // way, the output won't be affected by whether the compiler thinks\n  // char is signed or not.\n  PrintTo(static_cast<unsigned char>(c), os);\n}\n\n// Overloads for other simple built-in types.\ninline void PrintTo(bool x, ::std::ostream* os) {\n  *os << (x ? \"true\" : \"false\");\n}\n\n// Overload for wchar_t type.\n// Prints a wchar_t as a symbol if it is printable or as its internal\n// code otherwise and also as its decimal code (except for L'\\0').\n// The L'\\0' char is printed as \"L'\\\\0'\". The decimal code is printed\n// as signed integer when wchar_t is implemented by the compiler\n// as a signed type and is printed as an unsigned integer when wchar_t\n// is implemented as an unsigned type.\nGTEST_API_ void PrintTo(wchar_t wc, ::std::ostream* os);\n\nGTEST_API_ void PrintTo(char32_t c, ::std::ostream* os);\ninline void PrintTo(char16_t c, ::std::ostream* os) {\n  PrintTo(ImplicitCast_<char32_t>(c), os);\n}\n#ifdef __cpp_char8_t\ninline void PrintTo(char8_t c, ::std::ostream* os) {\n  PrintTo(ImplicitCast_<char32_t>(c), os);\n}\n#endif\n\n// gcc/clang __{u,}int128_t\n#if defined(__SIZEOF_INT128__)\nGTEST_API_ void PrintTo(__uint128_t v, ::std::ostream* os);\nGTEST_API_ void PrintTo(__int128_t v, ::std::ostream* os);\n#endif  // __SIZEOF_INT128__\n\n// Overloads for C strings.\nGTEST_API_ void PrintTo(const char* s, ::std::ostream* os);\ninline void PrintTo(char* s, ::std::ostream* os) {\n  PrintTo(ImplicitCast_<const char*>(s), os);\n}\n\n// signed/unsigned char is often used for representing binary data, so\n// we print pointers to it as void* to be safe.\ninline void PrintTo(const signed char* s, ::std::ostream* os) {\n  PrintTo(ImplicitCast_<const void*>(s), os);\n}\ninline void PrintTo(signed char* s, ::std::ostream* os) {\n  PrintTo(ImplicitCast_<const void*>(s), os);\n}\ninline void PrintTo(const unsigned char* s, ::std::ostream* os) {\n  PrintTo(ImplicitCast_<const void*>(s), os);\n}\ninline void PrintTo(unsigned char* s, ::std::ostream* os) {\n  PrintTo(ImplicitCast_<const void*>(s), os);\n}\n#ifdef __cpp_char8_t\n// Overloads for u8 strings.\nGTEST_API_ void PrintTo(const char8_t* s, ::std::ostream* os);\ninline void PrintTo(char8_t* s, ::std::ostream* os) {\n  PrintTo(ImplicitCast_<const char8_t*>(s), os);\n}\n#endif\n// Overloads for u16 strings.\nGTEST_API_ void PrintTo(const char16_t* s, ::std::ostream* os);\ninline void PrintTo(char16_t* s, ::std::ostream* os) {\n  PrintTo(ImplicitCast_<const char16_t*>(s), os);\n}\n// Overloads for u32 strings.\nGTEST_API_ void PrintTo(const char32_t* s, ::std::ostream* os);\ninline void PrintTo(char32_t* s, ::std::ostream* os) {\n  PrintTo(ImplicitCast_<const char32_t*>(s), os);\n}\n\n// MSVC can be configured to define wchar_t as a typedef of unsigned\n// short.  It defines _NATIVE_WCHAR_T_DEFINED when wchar_t is a native\n// type.  When wchar_t is a typedef, defining an overload for const\n// wchar_t* would cause unsigned short* be printed as a wide string,\n// possibly causing invalid memory accesses.\n#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)\n// Overloads for wide C strings\nGTEST_API_ void PrintTo(const wchar_t* s, ::std::ostream* os);\ninline void PrintTo(wchar_t* s, ::std::ostream* os) {\n  PrintTo(ImplicitCast_<const wchar_t*>(s), os);\n}\n#endif\n\n// Overload for C arrays.  Multi-dimensional arrays are printed\n// properly.\n\n// Prints the given number of elements in an array, without printing\n// the curly braces.\ntemplate <typename T>\nvoid PrintRawArrayTo(const T a[], size_t count, ::std::ostream* os) {\n  UniversalPrint(a[0], os);\n  for (size_t i = 1; i != count; i++) {\n    *os << \", \";\n    UniversalPrint(a[i], os);\n  }\n}\n\n// Overloads for ::std::string.\nGTEST_API_ void PrintStringTo(const ::std::string& s, ::std::ostream* os);\ninline void PrintTo(const ::std::string& s, ::std::ostream* os) {\n  PrintStringTo(s, os);\n}\n\n// Overloads for ::std::u8string\n#ifdef __cpp_char8_t\nGTEST_API_ void PrintU8StringTo(const ::std::u8string& s, ::std::ostream* os);\ninline void PrintTo(const ::std::u8string& s, ::std::ostream* os) {\n  PrintU8StringTo(s, os);\n}\n#endif\n\n// Overloads for ::std::u16string\nGTEST_API_ void PrintU16StringTo(const ::std::u16string& s, ::std::ostream* os);\ninline void PrintTo(const ::std::u16string& s, ::std::ostream* os) {\n  PrintU16StringTo(s, os);\n}\n\n// Overloads for ::std::u32string\nGTEST_API_ void PrintU32StringTo(const ::std::u32string& s, ::std::ostream* os);\ninline void PrintTo(const ::std::u32string& s, ::std::ostream* os) {\n  PrintU32StringTo(s, os);\n}\n\n// Overloads for ::std::wstring.\n#if GTEST_HAS_STD_WSTRING\nGTEST_API_ void PrintWideStringTo(const ::std::wstring& s, ::std::ostream* os);\ninline void PrintTo(const ::std::wstring& s, ::std::ostream* os) {\n  PrintWideStringTo(s, os);\n}\n#endif  // GTEST_HAS_STD_WSTRING\n\n#if GTEST_INTERNAL_HAS_STRING_VIEW\n// Overload for internal::StringView.\ninline void PrintTo(internal::StringView sp, ::std::ostream* os) {\n  PrintTo(::std::string(sp), os);\n}\n#endif  // GTEST_INTERNAL_HAS_STRING_VIEW\n\ninline void PrintTo(std::nullptr_t, ::std::ostream* os) { *os << \"(nullptr)\"; }\n\n#if GTEST_HAS_RTTI\ninline void PrintTo(const std::type_info& info, std::ostream* os) {\n  *os << internal::GetTypeName(info);\n}\n#endif  // GTEST_HAS_RTTI\n\ntemplate <typename T>\nvoid PrintTo(std::reference_wrapper<T> ref, ::std::ostream* os) {\n  UniversalPrinter<T&>::Print(ref.get(), os);\n}\n\ninline const void* VoidifyPointer(const void* p) { return p; }\ninline const void* VoidifyPointer(volatile const void* p) {\n  return const_cast<const void*>(p);\n}\n\ntemplate <typename T, typename Ptr>\nvoid PrintSmartPointer(const Ptr& ptr, std::ostream* os, char) {\n  if (ptr == nullptr) {\n    *os << \"(nullptr)\";\n  } else {\n    // We can't print the value. Just print the pointer..\n    *os << \"(\" << (VoidifyPointer)(ptr.get()) << \")\";\n  }\n}\ntemplate <typename T, typename Ptr,\n          typename = typename std::enable_if<!std::is_void<T>::value &&\n                                             !std::is_array<T>::value>::type>\nvoid PrintSmartPointer(const Ptr& ptr, std::ostream* os, int) {\n  if (ptr == nullptr) {\n    *os << \"(nullptr)\";\n  } else {\n    *os << \"(ptr = \" << (VoidifyPointer)(ptr.get()) << \", value = \";\n    UniversalPrinter<T>::Print(*ptr, os);\n    *os << \")\";\n  }\n}\n\ntemplate <typename T, typename D>\nvoid PrintTo(const std::unique_ptr<T, D>& ptr, std::ostream* os) {\n  (PrintSmartPointer<T>)(ptr, os, 0);\n}\n\ntemplate <typename T>\nvoid PrintTo(const std::shared_ptr<T>& ptr, std::ostream* os) {\n  (PrintSmartPointer<T>)(ptr, os, 0);\n}\n\n// Helper function for printing a tuple.  T must be instantiated with\n// a tuple type.\ntemplate <typename T>\nvoid PrintTupleTo(const T&, std::integral_constant<size_t, 0>,\n                  ::std::ostream*) {}\n\ntemplate <typename T, size_t I>\nvoid PrintTupleTo(const T& t, std::integral_constant<size_t, I>,\n                  ::std::ostream* os) {\n  PrintTupleTo(t, std::integral_constant<size_t, I - 1>(), os);\n  GTEST_INTENTIONAL_CONST_COND_PUSH_()\n  if (I > 1) {\n    GTEST_INTENTIONAL_CONST_COND_POP_()\n    *os << \", \";\n  }\n  UniversalPrinter<typename std::tuple_element<I - 1, T>::type>::Print(\n      std::get<I - 1>(t), os);\n}\n\ntemplate <typename... Types>\nvoid PrintTo(const ::std::tuple<Types...>& t, ::std::ostream* os) {\n  *os << \"(\";\n  PrintTupleTo(t, std::integral_constant<size_t, sizeof...(Types)>(), os);\n  *os << \")\";\n}\n\n// Overload for std::pair.\ntemplate <typename T1, typename T2>\nvoid PrintTo(const ::std::pair<T1, T2>& value, ::std::ostream* os) {\n  *os << '(';\n  // We cannot use UniversalPrint(value.first, os) here, as T1 may be\n  // a reference type.  The same for printing value.second.\n  UniversalPrinter<T1>::Print(value.first, os);\n  *os << \", \";\n  UniversalPrinter<T2>::Print(value.second, os);\n  *os << ')';\n}\n\n// Implements printing a non-reference type T by letting the compiler\n// pick the right overload of PrintTo() for T.\ntemplate <typename T>\nclass UniversalPrinter {\n public:\n  // MSVC warns about adding const to a function type, so we want to\n  // disable the warning.\n  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)\n\n  // Note: we deliberately don't call this PrintTo(), as that name\n  // conflicts with ::testing::internal::PrintTo in the body of the\n  // function.\n  static void Print(const T& value, ::std::ostream* os) {\n    // By default, ::testing::internal::PrintTo() is used for printing\n    // the value.\n    //\n    // Thanks to Koenig look-up, if T is a class and has its own\n    // PrintTo() function defined in its namespace, that function will\n    // be visible here.  Since it is more specific than the generic ones\n    // in ::testing::internal, it will be picked by the compiler in the\n    // following statement - exactly what we want.\n    PrintTo(value, os);\n  }\n\n  GTEST_DISABLE_MSC_WARNINGS_POP_()\n};\n\n// Remove any const-qualifiers before passing a type to UniversalPrinter.\ntemplate <typename T>\nclass UniversalPrinter<const T> : public UniversalPrinter<T> {};\n\n#if GTEST_INTERNAL_HAS_ANY\n\n// Printer for std::any / absl::any\n\ntemplate <>\nclass UniversalPrinter<Any> {\n public:\n  static void Print(const Any& value, ::std::ostream* os) {\n    if (value.has_value()) {\n      *os << \"value of type \" << GetTypeName(value);\n    } else {\n      *os << \"no value\";\n    }\n  }\n\n private:\n  static std::string GetTypeName(const Any& value) {\n#if GTEST_HAS_RTTI\n    return internal::GetTypeName(value.type());\n#else\n    static_cast<void>(value);  // possibly unused\n    return \"<unknown_type>\";\n#endif  // GTEST_HAS_RTTI\n  }\n};\n\n#endif  // GTEST_INTERNAL_HAS_ANY\n\n#if GTEST_INTERNAL_HAS_OPTIONAL\n\n// Printer for std::optional / absl::optional\n\ntemplate <typename T>\nclass UniversalPrinter<Optional<T>> {\n public:\n  static void Print(const Optional<T>& value, ::std::ostream* os) {\n    *os << '(';\n    if (!value) {\n      *os << \"nullopt\";\n    } else {\n      UniversalPrint(*value, os);\n    }\n    *os << ')';\n  }\n};\n\ntemplate <>\nclass UniversalPrinter<decltype(Nullopt())> {\n public:\n  static void Print(decltype(Nullopt()), ::std::ostream* os) {\n    *os << \"(nullopt)\";\n  }\n};\n\n#endif  // GTEST_INTERNAL_HAS_OPTIONAL\n\n#if GTEST_INTERNAL_HAS_VARIANT\n\n// Printer for std::variant / absl::variant\n\ntemplate <typename... T>\nclass UniversalPrinter<Variant<T...>> {\n public:\n  static void Print(const Variant<T...>& value, ::std::ostream* os) {\n    *os << '(';\n#if GTEST_HAS_ABSL\n    absl::visit(Visitor{os, value.index()}, value);\n#else\n    std::visit(Visitor{os, value.index()}, value);\n#endif  // GTEST_HAS_ABSL\n    *os << ')';\n  }\n\n private:\n  struct Visitor {\n    template <typename U>\n    void operator()(const U& u) const {\n      *os << \"'\" << GetTypeName<U>() << \"(index = \" << index\n          << \")' with value \";\n      UniversalPrint(u, os);\n    }\n    ::std::ostream* os;\n    std::size_t index;\n  };\n};\n\n#endif  // GTEST_INTERNAL_HAS_VARIANT\n\n// UniversalPrintArray(begin, len, os) prints an array of 'len'\n// elements, starting at address 'begin'.\ntemplate <typename T>\nvoid UniversalPrintArray(const T* begin, size_t len, ::std::ostream* os) {\n  if (len == 0) {\n    *os << \"{}\";\n  } else {\n    *os << \"{ \";\n    const size_t kThreshold = 18;\n    const size_t kChunkSize = 8;\n    // If the array has more than kThreshold elements, we'll have to\n    // omit some details by printing only the first and the last\n    // kChunkSize elements.\n    if (len <= kThreshold) {\n      PrintRawArrayTo(begin, len, os);\n    } else {\n      PrintRawArrayTo(begin, kChunkSize, os);\n      *os << \", ..., \";\n      PrintRawArrayTo(begin + len - kChunkSize, kChunkSize, os);\n    }\n    *os << \" }\";\n  }\n}\n// This overload prints a (const) char array compactly.\nGTEST_API_ void UniversalPrintArray(const char* begin, size_t len,\n                                    ::std::ostream* os);\n\n#ifdef __cpp_char8_t\n// This overload prints a (const) char8_t array compactly.\nGTEST_API_ void UniversalPrintArray(const char8_t* begin, size_t len,\n                                    ::std::ostream* os);\n#endif\n\n// This overload prints a (const) char16_t array compactly.\nGTEST_API_ void UniversalPrintArray(const char16_t* begin, size_t len,\n                                    ::std::ostream* os);\n\n// This overload prints a (const) char32_t array compactly.\nGTEST_API_ void UniversalPrintArray(const char32_t* begin, size_t len,\n                                    ::std::ostream* os);\n\n// This overload prints a (const) wchar_t array compactly.\nGTEST_API_ void UniversalPrintArray(const wchar_t* begin, size_t len,\n                                    ::std::ostream* os);\n\n// Implements printing an array type T[N].\ntemplate <typename T, size_t N>\nclass UniversalPrinter<T[N]> {\n public:\n  // Prints the given array, omitting some elements when there are too\n  // many.\n  static void Print(const T (&a)[N], ::std::ostream* os) {\n    UniversalPrintArray(a, N, os);\n  }\n};\n\n// Implements printing a reference type T&.\ntemplate <typename T>\nclass UniversalPrinter<T&> {\n public:\n  // MSVC warns about adding const to a function type, so we want to\n  // disable the warning.\n  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4180)\n\n  static void Print(const T& value, ::std::ostream* os) {\n    // Prints the address of the value.  We use reinterpret_cast here\n    // as static_cast doesn't compile when T is a function type.\n    *os << \"@\" << reinterpret_cast<const void*>(&value) << \" \";\n\n    // Then prints the value itself.\n    UniversalPrint(value, os);\n  }\n\n  GTEST_DISABLE_MSC_WARNINGS_POP_()\n};\n\n// Prints a value tersely: for a reference type, the referenced value\n// (but not the address) is printed; for a (const) char pointer, the\n// NUL-terminated string (but not the pointer) is printed.\n\ntemplate <typename T>\nclass UniversalTersePrinter {\n public:\n  static void Print(const T& value, ::std::ostream* os) {\n    UniversalPrint(value, os);\n  }\n};\ntemplate <typename T>\nclass UniversalTersePrinter<T&> {\n public:\n  static void Print(const T& value, ::std::ostream* os) {\n    UniversalPrint(value, os);\n  }\n};\ntemplate <typename T, size_t N>\nclass UniversalTersePrinter<T[N]> {\n public:\n  static void Print(const T (&value)[N], ::std::ostream* os) {\n    UniversalPrinter<T[N]>::Print(value, os);\n  }\n};\ntemplate <>\nclass UniversalTersePrinter<const char*> {\n public:\n  static void Print(const char* str, ::std::ostream* os) {\n    if (str == nullptr) {\n      *os << \"NULL\";\n    } else {\n      UniversalPrint(std::string(str), os);\n    }\n  }\n};\ntemplate <>\nclass UniversalTersePrinter<char*> : public UniversalTersePrinter<const char*> {\n};\n\n#ifdef __cpp_char8_t\ntemplate <>\nclass UniversalTersePrinter<const char8_t*> {\n public:\n  static void Print(const char8_t* str, ::std::ostream* os) {\n    if (str == nullptr) {\n      *os << \"NULL\";\n    } else {\n      UniversalPrint(::std::u8string(str), os);\n    }\n  }\n};\ntemplate <>\nclass UniversalTersePrinter<char8_t*>\n    : public UniversalTersePrinter<const char8_t*> {};\n#endif\n\ntemplate <>\nclass UniversalTersePrinter<const char16_t*> {\n public:\n  static void Print(const char16_t* str, ::std::ostream* os) {\n    if (str == nullptr) {\n      *os << \"NULL\";\n    } else {\n      UniversalPrint(::std::u16string(str), os);\n    }\n  }\n};\ntemplate <>\nclass UniversalTersePrinter<char16_t*>\n    : public UniversalTersePrinter<const char16_t*> {};\n\ntemplate <>\nclass UniversalTersePrinter<const char32_t*> {\n public:\n  static void Print(const char32_t* str, ::std::ostream* os) {\n    if (str == nullptr) {\n      *os << \"NULL\";\n    } else {\n      UniversalPrint(::std::u32string(str), os);\n    }\n  }\n};\ntemplate <>\nclass UniversalTersePrinter<char32_t*>\n    : public UniversalTersePrinter<const char32_t*> {};\n\n#if GTEST_HAS_STD_WSTRING\ntemplate <>\nclass UniversalTersePrinter<const wchar_t*> {\n public:\n  static void Print(const wchar_t* str, ::std::ostream* os) {\n    if (str == nullptr) {\n      *os << \"NULL\";\n    } else {\n      UniversalPrint(::std::wstring(str), os);\n    }\n  }\n};\n#endif\n\ntemplate <>\nclass UniversalTersePrinter<wchar_t*> {\n public:\n  static void Print(wchar_t* str, ::std::ostream* os) {\n    UniversalTersePrinter<const wchar_t*>::Print(str, os);\n  }\n};\n\ntemplate <typename T>\nvoid UniversalTersePrint(const T& value, ::std::ostream* os) {\n  UniversalTersePrinter<T>::Print(value, os);\n}\n\n// Prints a value using the type inferred by the compiler.  The\n// difference between this and UniversalTersePrint() is that for a\n// (const) char pointer, this prints both the pointer and the\n// NUL-terminated string.\ntemplate <typename T>\nvoid UniversalPrint(const T& value, ::std::ostream* os) {\n  // A workarond for the bug in VC++ 7.1 that prevents us from instantiating\n  // UniversalPrinter with T directly.\n  typedef T T1;\n  UniversalPrinter<T1>::Print(value, os);\n}\n\ntypedef ::std::vector<::std::string> Strings;\n\n// Tersely prints the first N fields of a tuple to a string vector,\n// one element for each field.\ntemplate <typename Tuple>\nvoid TersePrintPrefixToStrings(const Tuple&, std::integral_constant<size_t, 0>,\n                               Strings*) {}\ntemplate <typename Tuple, size_t I>\nvoid TersePrintPrefixToStrings(const Tuple& t,\n                               std::integral_constant<size_t, I>,\n                               Strings* strings) {\n  TersePrintPrefixToStrings(t, std::integral_constant<size_t, I - 1>(),\n                            strings);\n  ::std::stringstream ss;\n  UniversalTersePrint(std::get<I - 1>(t), &ss);\n  strings->push_back(ss.str());\n}\n\n// Prints the fields of a tuple tersely to a string vector, one\n// element for each field.  See the comment before\n// UniversalTersePrint() for how we define \"tersely\".\ntemplate <typename Tuple>\nStrings UniversalTersePrintTupleFieldsToStrings(const Tuple& value) {\n  Strings result;\n  TersePrintPrefixToStrings(\n      value, std::integral_constant<size_t, std::tuple_size<Tuple>::value>(),\n      &result);\n  return result;\n}\n\n}  // namespace internal\n\ntemplate <typename T>\n::std::string PrintToString(const T& value) {\n  ::std::stringstream ss;\n  internal::UniversalTersePrinter<T>::Print(value, &ss);\n  return ss.str();\n}\n\n}  // namespace testing\n\n// Include any custom printer added by the local installation.\n// We must include this header at the end to make sure it can use the\n// declarations from this file.\n#include \"gtest/internal/custom/gtest-printers.h\"\n\n#endif  // GOOGLETEST_INCLUDE_GTEST_GTEST_PRINTERS_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/include/gtest/gtest-spi.h",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Utilities for testing Google Test itself and code that uses Google Test\n// (e.g. frameworks built on top of Google Test).\n\n#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_\n#define GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_\n\n#include \"gtest/gtest.h\"\n\nGTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \\\n/* class A needs to have dll-interface to be used by clients of class B */)\n\nnamespace testing {\n\n// This helper class can be used to mock out Google Test failure reporting\n// so that we can test Google Test or code that builds on Google Test.\n//\n// An object of this class appends a TestPartResult object to the\n// TestPartResultArray object given in the constructor whenever a Google Test\n// failure is reported. It can either intercept only failures that are\n// generated in the same thread that created this object or it can intercept\n// all generated failures. The scope of this mock object can be controlled with\n// the second argument to the two arguments constructor.\nclass GTEST_API_ ScopedFakeTestPartResultReporter\n    : public TestPartResultReporterInterface {\n public:\n  // The two possible mocking modes of this object.\n  enum InterceptMode {\n    INTERCEPT_ONLY_CURRENT_THREAD,  // Intercepts only thread local failures.\n    INTERCEPT_ALL_THREADS           // Intercepts all failures.\n  };\n\n  // The c'tor sets this object as the test part result reporter used\n  // by Google Test.  The 'result' parameter specifies where to report the\n  // results. This reporter will only catch failures generated in the current\n  // thread. DEPRECATED\n  explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result);\n\n  // Same as above, but you can choose the interception scope of this object.\n  ScopedFakeTestPartResultReporter(InterceptMode intercept_mode,\n                                   TestPartResultArray* result);\n\n  // The d'tor restores the previous test part result reporter.\n  ~ScopedFakeTestPartResultReporter() override;\n\n  // Appends the TestPartResult object to the TestPartResultArray\n  // received in the constructor.\n  //\n  // This method is from the TestPartResultReporterInterface\n  // interface.\n  void ReportTestPartResult(const TestPartResult& result) override;\n\n private:\n  void Init();\n\n  const InterceptMode intercept_mode_;\n  TestPartResultReporterInterface* old_reporter_;\n  TestPartResultArray* const result_;\n\n  ScopedFakeTestPartResultReporter(const ScopedFakeTestPartResultReporter&) =\n      delete;\n  ScopedFakeTestPartResultReporter& operator=(\n      const ScopedFakeTestPartResultReporter&) = delete;\n};\n\nnamespace internal {\n\n// A helper class for implementing EXPECT_FATAL_FAILURE() and\n// EXPECT_NONFATAL_FAILURE().  Its destructor verifies that the given\n// TestPartResultArray contains exactly one failure that has the given\n// type and contains the given substring.  If that's not the case, a\n// non-fatal failure will be generated.\nclass GTEST_API_ SingleFailureChecker {\n public:\n  // The constructor remembers the arguments.\n  SingleFailureChecker(const TestPartResultArray* results,\n                       TestPartResult::Type type, const std::string& substr);\n  ~SingleFailureChecker();\n\n private:\n  const TestPartResultArray* const results_;\n  const TestPartResult::Type type_;\n  const std::string substr_;\n\n  SingleFailureChecker(const SingleFailureChecker&) = delete;\n  SingleFailureChecker& operator=(const SingleFailureChecker&) = delete;\n};\n\n}  // namespace internal\n\n}  // namespace testing\n\nGTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251\n\n// A set of macros for testing Google Test assertions or code that's expected\n// to generate Google Test fatal failures (e.g. a failure from an ASSERT_EQ, but\n// not a non-fatal failure, as from EXPECT_EQ).  It verifies that the given\n// statement will cause exactly one fatal Google Test failure with 'substr'\n// being part of the failure message.\n//\n// There are two different versions of this macro. EXPECT_FATAL_FAILURE only\n// affects and considers failures generated in the current thread and\n// EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.\n//\n// The verification of the assertion is done correctly even when the statement\n// throws an exception or aborts the current function.\n//\n// Known restrictions:\n//   - 'statement' cannot reference local non-static variables or\n//     non-static members of the current object.\n//   - 'statement' cannot return a value.\n//   - You cannot stream a failure message to this macro.\n//\n// Note that even though the implementations of the following two\n// macros are much alike, we cannot refactor them to use a common\n// helper macro, due to some peculiarity in how the preprocessor\n// works.  The AcceptsMacroThatExpandsToUnprotectedComma test in\n// gtest_unittest.cc will fail to compile if we do that.\n#define EXPECT_FATAL_FAILURE(statement, substr)                               \\\n  do {                                                                        \\\n    class GTestExpectFatalFailureHelper {                                     \\\n     public:                                                                  \\\n      static void Execute() { statement; }                                    \\\n    };                                                                        \\\n    ::testing::TestPartResultArray gtest_failures;                            \\\n    ::testing::internal::SingleFailureChecker gtest_checker(                  \\\n        &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr)); \\\n    {                                                                         \\\n      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(             \\\n          ::testing::ScopedFakeTestPartResultReporter::                       \\\n              INTERCEPT_ONLY_CURRENT_THREAD,                                  \\\n          &gtest_failures);                                                   \\\n      GTestExpectFatalFailureHelper::Execute();                               \\\n    }                                                                         \\\n  } while (::testing::internal::AlwaysFalse())\n\n#define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr)                \\\n  do {                                                                        \\\n    class GTestExpectFatalFailureHelper {                                     \\\n     public:                                                                  \\\n      static void Execute() { statement; }                                    \\\n    };                                                                        \\\n    ::testing::TestPartResultArray gtest_failures;                            \\\n    ::testing::internal::SingleFailureChecker gtest_checker(                  \\\n        &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr)); \\\n    {                                                                         \\\n      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(             \\\n          ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \\\n          &gtest_failures);                                                   \\\n      GTestExpectFatalFailureHelper::Execute();                               \\\n    }                                                                         \\\n  } while (::testing::internal::AlwaysFalse())\n\n// A macro for testing Google Test assertions or code that's expected to\n// generate Google Test non-fatal failures (e.g. a failure from an EXPECT_EQ,\n// but not from an ASSERT_EQ). It asserts that the given statement will cause\n// exactly one non-fatal Google Test failure with 'substr' being part of the\n// failure message.\n//\n// There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only\n// affects and considers failures generated in the current thread and\n// EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads.\n//\n// 'statement' is allowed to reference local variables and members of\n// the current object.\n//\n// The verification of the assertion is done correctly even when the statement\n// throws an exception or aborts the current function.\n//\n// Known restrictions:\n//   - You cannot stream a failure message to this macro.\n//\n// Note that even though the implementations of the following two\n// macros are much alike, we cannot refactor them to use a common\n// helper macro, due to some peculiarity in how the preprocessor\n// works.  If we do that, the code won't compile when the user gives\n// EXPECT_NONFATAL_FAILURE() a statement that contains a macro that\n// expands to code containing an unprotected comma.  The\n// AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc\n// catches that.\n//\n// For the same reason, we have to write\n//   if (::testing::internal::AlwaysTrue()) { statement; }\n// instead of\n//   GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)\n// to avoid an MSVC warning on unreachable code.\n#define EXPECT_NONFATAL_FAILURE(statement, substr)                    \\\n  do {                                                                \\\n    ::testing::TestPartResultArray gtest_failures;                    \\\n    ::testing::internal::SingleFailureChecker gtest_checker(          \\\n        &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \\\n        (substr));                                                    \\\n    {                                                                 \\\n      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(     \\\n          ::testing::ScopedFakeTestPartResultReporter::               \\\n              INTERCEPT_ONLY_CURRENT_THREAD,                          \\\n          &gtest_failures);                                           \\\n      if (::testing::internal::AlwaysTrue()) {                        \\\n        statement;                                                    \\\n      }                                                               \\\n    }                                                                 \\\n  } while (::testing::internal::AlwaysFalse())\n\n#define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr)             \\\n  do {                                                                        \\\n    ::testing::TestPartResultArray gtest_failures;                            \\\n    ::testing::internal::SingleFailureChecker gtest_checker(                  \\\n        &gtest_failures, ::testing::TestPartResult::kNonFatalFailure,         \\\n        (substr));                                                            \\\n    {                                                                         \\\n      ::testing::ScopedFakeTestPartResultReporter gtest_reporter(             \\\n          ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \\\n          &gtest_failures);                                                   \\\n      if (::testing::internal::AlwaysTrue()) {                                \\\n        statement;                                                            \\\n      }                                                                       \\\n    }                                                                         \\\n  } while (::testing::internal::AlwaysFalse())\n\n#endif  // GOOGLETEST_INCLUDE_GTEST_GTEST_SPI_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/include/gtest/gtest-test-part.h",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// IWYU pragma: private, include \"gtest/gtest.h\"\n// IWYU pragma: friend gtest/.*\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_\n#define GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_\n\n#include <iosfwd>\n#include <vector>\n\n#include \"gtest/internal/gtest-internal.h\"\n#include \"gtest/internal/gtest-string.h\"\n\nGTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \\\n/* class A needs to have dll-interface to be used by clients of class B */)\n\nnamespace testing {\n\n// A copyable object representing the result of a test part (i.e. an\n// assertion or an explicit FAIL(), ADD_FAILURE(), or SUCCESS()).\n//\n// Don't inherit from TestPartResult as its destructor is not virtual.\nclass GTEST_API_ TestPartResult {\n public:\n  // The possible outcomes of a test part (i.e. an assertion or an\n  // explicit SUCCEED(), FAIL(), or ADD_FAILURE()).\n  enum Type {\n    kSuccess,          // Succeeded.\n    kNonFatalFailure,  // Failed but the test can continue.\n    kFatalFailure,     // Failed and the test should be terminated.\n    kSkip              // Skipped.\n  };\n\n  // C'tor.  TestPartResult does NOT have a default constructor.\n  // Always use this constructor (with parameters) to create a\n  // TestPartResult object.\n  TestPartResult(Type a_type, const char* a_file_name, int a_line_number,\n                 const char* a_message)\n      : type_(a_type),\n        file_name_(a_file_name == nullptr ? \"\" : a_file_name),\n        line_number_(a_line_number),\n        summary_(ExtractSummary(a_message)),\n        message_(a_message) {}\n\n  // Gets the outcome of the test part.\n  Type type() const { return type_; }\n\n  // Gets the name of the source file where the test part took place, or\n  // NULL if it's unknown.\n  const char* file_name() const {\n    return file_name_.empty() ? nullptr : file_name_.c_str();\n  }\n\n  // Gets the line in the source file where the test part took place,\n  // or -1 if it's unknown.\n  int line_number() const { return line_number_; }\n\n  // Gets the summary of the failure message.\n  const char* summary() const { return summary_.c_str(); }\n\n  // Gets the message associated with the test part.\n  const char* message() const { return message_.c_str(); }\n\n  // Returns true if and only if the test part was skipped.\n  bool skipped() const { return type_ == kSkip; }\n\n  // Returns true if and only if the test part passed.\n  bool passed() const { return type_ == kSuccess; }\n\n  // Returns true if and only if the test part non-fatally failed.\n  bool nonfatally_failed() const { return type_ == kNonFatalFailure; }\n\n  // Returns true if and only if the test part fatally failed.\n  bool fatally_failed() const { return type_ == kFatalFailure; }\n\n  // Returns true if and only if the test part failed.\n  bool failed() const { return fatally_failed() || nonfatally_failed(); }\n\n private:\n  Type type_;\n\n  // Gets the summary of the failure message by omitting the stack\n  // trace in it.\n  static std::string ExtractSummary(const char* message);\n\n  // The name of the source file where the test part took place, or\n  // \"\" if the source file is unknown.\n  std::string file_name_;\n  // The line in the source file where the test part took place, or -1\n  // if the line number is unknown.\n  int line_number_;\n  std::string summary_;  // The test failure summary.\n  std::string message_;  // The test failure message.\n};\n\n// Prints a TestPartResult object.\nstd::ostream& operator<<(std::ostream& os, const TestPartResult& result);\n\n// An array of TestPartResult objects.\n//\n// Don't inherit from TestPartResultArray as its destructor is not\n// virtual.\nclass GTEST_API_ TestPartResultArray {\n public:\n  TestPartResultArray() {}\n\n  // Appends the given TestPartResult to the array.\n  void Append(const TestPartResult& result);\n\n  // Returns the TestPartResult at the given index (0-based).\n  const TestPartResult& GetTestPartResult(int index) const;\n\n  // Returns the number of TestPartResult objects in the array.\n  int size() const;\n\n private:\n  std::vector<TestPartResult> array_;\n\n  TestPartResultArray(const TestPartResultArray&) = delete;\n  TestPartResultArray& operator=(const TestPartResultArray&) = delete;\n};\n\n// This interface knows how to report a test part result.\nclass GTEST_API_ TestPartResultReporterInterface {\n public:\n  virtual ~TestPartResultReporterInterface() {}\n\n  virtual void ReportTestPartResult(const TestPartResult& result) = 0;\n};\n\nnamespace internal {\n\n// This helper class is used by {ASSERT|EXPECT}_NO_FATAL_FAILURE to check if a\n// statement generates new fatal failures. To do so it registers itself as the\n// current test part result reporter. Besides checking if fatal failures were\n// reported, it only delegates the reporting to the former result reporter.\n// The original result reporter is restored in the destructor.\n// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.\nclass GTEST_API_ HasNewFatalFailureHelper\n    : public TestPartResultReporterInterface {\n public:\n  HasNewFatalFailureHelper();\n  ~HasNewFatalFailureHelper() override;\n  void ReportTestPartResult(const TestPartResult& result) override;\n  bool has_new_fatal_failure() const { return has_new_fatal_failure_; }\n\n private:\n  bool has_new_fatal_failure_;\n  TestPartResultReporterInterface* original_reporter_;\n\n  HasNewFatalFailureHelper(const HasNewFatalFailureHelper&) = delete;\n  HasNewFatalFailureHelper& operator=(const HasNewFatalFailureHelper&) = delete;\n};\n\n}  // namespace internal\n\n}  // namespace testing\n\nGTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251\n\n#endif  // GOOGLETEST_INCLUDE_GTEST_GTEST_TEST_PART_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/include/gtest/gtest-typed-test.h",
    "content": "// Copyright 2008 Google Inc.\n// All Rights Reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// IWYU pragma: private, include \"gtest/gtest.h\"\n// IWYU pragma: friend gtest/.*\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_\n#define GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_\n\n// This header implements typed tests and type-parameterized tests.\n\n// Typed (aka type-driven) tests repeat the same test for types in a\n// list.  You must know which types you want to test with when writing\n// typed tests. Here's how you do it:\n\n#if 0\n\n// First, define a fixture class template.  It should be parameterized\n// by a type.  Remember to derive it from testing::Test.\ntemplate <typename T>\nclass FooTest : public testing::Test {\n public:\n  ...\n  typedef std::list<T> List;\n  static T shared_;\n  T value_;\n};\n\n// Next, associate a list of types with the test suite, which will be\n// repeated for each type in the list.  The typedef is necessary for\n// the macro to parse correctly.\ntypedef testing::Types<char, int, unsigned int> MyTypes;\nTYPED_TEST_SUITE(FooTest, MyTypes);\n\n// If the type list contains only one type, you can write that type\n// directly without Types<...>:\n//   TYPED_TEST_SUITE(FooTest, int);\n\n// Then, use TYPED_TEST() instead of TEST_F() to define as many typed\n// tests for this test suite as you want.\nTYPED_TEST(FooTest, DoesBlah) {\n  // Inside a test, refer to the special name TypeParam to get the type\n  // parameter.  Since we are inside a derived class template, C++ requires\n  // us to visit the members of FooTest via 'this'.\n  TypeParam n = this->value_;\n\n  // To visit static members of the fixture, add the TestFixture::\n  // prefix.\n  n += TestFixture::shared_;\n\n  // To refer to typedefs in the fixture, add the \"typename\n  // TestFixture::\" prefix.\n  typename TestFixture::List values;\n  values.push_back(n);\n  ...\n}\n\nTYPED_TEST(FooTest, HasPropertyA) { ... }\n\n// TYPED_TEST_SUITE takes an optional third argument which allows to specify a\n// class that generates custom test name suffixes based on the type. This should\n// be a class which has a static template function GetName(int index) returning\n// a string for each type. The provided integer index equals the index of the\n// type in the provided type list. In many cases the index can be ignored.\n//\n// For example:\n//   class MyTypeNames {\n//    public:\n//     template <typename T>\n//     static std::string GetName(int) {\n//       if (std::is_same<T, char>()) return \"char\";\n//       if (std::is_same<T, int>()) return \"int\";\n//       if (std::is_same<T, unsigned int>()) return \"unsignedInt\";\n//     }\n//   };\n//   TYPED_TEST_SUITE(FooTest, MyTypes, MyTypeNames);\n\n#endif  // 0\n\n// Type-parameterized tests are abstract test patterns parameterized\n// by a type.  Compared with typed tests, type-parameterized tests\n// allow you to define the test pattern without knowing what the type\n// parameters are.  The defined pattern can be instantiated with\n// different types any number of times, in any number of translation\n// units.\n//\n// If you are designing an interface or concept, you can define a\n// suite of type-parameterized tests to verify properties that any\n// valid implementation of the interface/concept should have.  Then,\n// each implementation can easily instantiate the test suite to verify\n// that it conforms to the requirements, without having to write\n// similar tests repeatedly.  Here's an example:\n\n#if 0\n\n// First, define a fixture class template.  It should be parameterized\n// by a type.  Remember to derive it from testing::Test.\ntemplate <typename T>\nclass FooTest : public testing::Test {\n  ...\n};\n\n// Next, declare that you will define a type-parameterized test suite\n// (the _P suffix is for \"parameterized\" or \"pattern\", whichever you\n// prefer):\nTYPED_TEST_SUITE_P(FooTest);\n\n// Then, use TYPED_TEST_P() to define as many type-parameterized tests\n// for this type-parameterized test suite as you want.\nTYPED_TEST_P(FooTest, DoesBlah) {\n  // Inside a test, refer to TypeParam to get the type parameter.\n  TypeParam n = 0;\n  ...\n}\n\nTYPED_TEST_P(FooTest, HasPropertyA) { ... }\n\n// Now the tricky part: you need to register all test patterns before\n// you can instantiate them.  The first argument of the macro is the\n// test suite name; the rest are the names of the tests in this test\n// case.\nREGISTER_TYPED_TEST_SUITE_P(FooTest,\n                            DoesBlah, HasPropertyA);\n\n// Finally, you are free to instantiate the pattern with the types you\n// want.  If you put the above code in a header file, you can #include\n// it in multiple C++ source files and instantiate it multiple times.\n//\n// To distinguish different instances of the pattern, the first\n// argument to the INSTANTIATE_* macro is a prefix that will be added\n// to the actual test suite name.  Remember to pick unique prefixes for\n// different instances.\ntypedef testing::Types<char, int, unsigned int> MyTypes;\nINSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes);\n\n// If the type list contains only one type, you can write that type\n// directly without Types<...>:\n//   INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, int);\n//\n// Similar to the optional argument of TYPED_TEST_SUITE above,\n// INSTANTIATE_TEST_SUITE_P takes an optional fourth argument which allows to\n// generate custom names.\n//   INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes, MyTypeNames);\n\n#endif  // 0\n\n#include \"gtest/internal/gtest-internal.h\"\n#include \"gtest/internal/gtest-port.h\"\n#include \"gtest/internal/gtest-type-util.h\"\n\n// Implements typed tests.\n\n// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.\n//\n// Expands to the name of the typedef for the type parameters of the\n// given test suite.\n#define GTEST_TYPE_PARAMS_(TestSuiteName) gtest_type_params_##TestSuiteName##_\n\n// Expands to the name of the typedef for the NameGenerator, responsible for\n// creating the suffixes of the name.\n#define GTEST_NAME_GENERATOR_(TestSuiteName) \\\n  gtest_type_params_##TestSuiteName##_NameGenerator\n\n#define TYPED_TEST_SUITE(CaseName, Types, ...)                          \\\n  typedef ::testing::internal::GenerateTypeList<Types>::type            \\\n      GTEST_TYPE_PARAMS_(CaseName);                                     \\\n  typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \\\n  GTEST_NAME_GENERATOR_(CaseName)\n\n#define TYPED_TEST(CaseName, TestName)                                        \\\n  static_assert(sizeof(GTEST_STRINGIFY_(TestName)) > 1,                       \\\n                \"test-name must not be empty\");                               \\\n  template <typename gtest_TypeParam_>                                        \\\n  class GTEST_TEST_CLASS_NAME_(CaseName, TestName)                            \\\n      : public CaseName<gtest_TypeParam_> {                                   \\\n   private:                                                                   \\\n    typedef CaseName<gtest_TypeParam_> TestFixture;                           \\\n    typedef gtest_TypeParam_ TypeParam;                                       \\\n    void TestBody() override;                                                 \\\n  };                                                                          \\\n  static bool gtest_##CaseName##_##TestName##_registered_                     \\\n      GTEST_ATTRIBUTE_UNUSED_ = ::testing::internal::TypeParameterizedTest<   \\\n          CaseName,                                                           \\\n          ::testing::internal::TemplateSel<GTEST_TEST_CLASS_NAME_(CaseName,   \\\n                                                                  TestName)>, \\\n          GTEST_TYPE_PARAMS_(                                                 \\\n              CaseName)>::Register(\"\",                                        \\\n                                   ::testing::internal::CodeLocation(         \\\n                                       __FILE__, __LINE__),                   \\\n                                   GTEST_STRINGIFY_(CaseName),                \\\n                                   GTEST_STRINGIFY_(TestName), 0,             \\\n                                   ::testing::internal::GenerateNames<        \\\n                                       GTEST_NAME_GENERATOR_(CaseName),       \\\n                                       GTEST_TYPE_PARAMS_(CaseName)>());      \\\n  template <typename gtest_TypeParam_>                                        \\\n  void GTEST_TEST_CLASS_NAME_(CaseName,                                       \\\n                              TestName)<gtest_TypeParam_>::TestBody()\n\n// Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n#define TYPED_TEST_CASE                                                \\\n  static_assert(::testing::internal::TypedTestCaseIsDeprecated(), \"\"); \\\n  TYPED_TEST_SUITE\n#endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n// Implements type-parameterized tests.\n\n// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.\n//\n// Expands to the namespace name that the type-parameterized tests for\n// the given type-parameterized test suite are defined in.  The exact\n// name of the namespace is subject to change without notice.\n#define GTEST_SUITE_NAMESPACE_(TestSuiteName) gtest_suite_##TestSuiteName##_\n\n// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.\n//\n// Expands to the name of the variable used to remember the names of\n// the defined tests in the given test suite.\n#define GTEST_TYPED_TEST_SUITE_P_STATE_(TestSuiteName) \\\n  gtest_typed_test_suite_p_state_##TestSuiteName##_\n\n// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY.\n//\n// Expands to the name of the variable used to remember the names of\n// the registered tests in the given test suite.\n#define GTEST_REGISTERED_TEST_NAMES_(TestSuiteName) \\\n  gtest_registered_test_names_##TestSuiteName##_\n\n// The variables defined in the type-parameterized test macros are\n// static as typically these macros are used in a .h file that can be\n// #included in multiple translation units linked together.\n#define TYPED_TEST_SUITE_P(SuiteName)              \\\n  static ::testing::internal::TypedTestSuitePState \\\n  GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName)\n\n// Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n#define TYPED_TEST_CASE_P                                                 \\\n  static_assert(::testing::internal::TypedTestCase_P_IsDeprecated(), \"\"); \\\n  TYPED_TEST_SUITE_P\n#endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n#define TYPED_TEST_P(SuiteName, TestName)                             \\\n  namespace GTEST_SUITE_NAMESPACE_(SuiteName) {                       \\\n    template <typename gtest_TypeParam_>                              \\\n    class TestName : public SuiteName<gtest_TypeParam_> {             \\\n     private:                                                         \\\n      typedef SuiteName<gtest_TypeParam_> TestFixture;                \\\n      typedef gtest_TypeParam_ TypeParam;                             \\\n      void TestBody() override;                                       \\\n    };                                                                \\\n    static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \\\n        GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName(       \\\n            __FILE__, __LINE__, GTEST_STRINGIFY_(SuiteName),          \\\n            GTEST_STRINGIFY_(TestName));                              \\\n  }                                                                   \\\n  template <typename gtest_TypeParam_>                                \\\n  void GTEST_SUITE_NAMESPACE_(                                        \\\n      SuiteName)::TestName<gtest_TypeParam_>::TestBody()\n\n// Note: this won't work correctly if the trailing arguments are macros.\n#define REGISTER_TYPED_TEST_SUITE_P(SuiteName, ...)                         \\\n  namespace GTEST_SUITE_NAMESPACE_(SuiteName) {                             \\\n    typedef ::testing::internal::Templates<__VA_ARGS__> gtest_AllTests_;    \\\n  }                                                                         \\\n  static const char* const GTEST_REGISTERED_TEST_NAMES_(                    \\\n      SuiteName) GTEST_ATTRIBUTE_UNUSED_ =                                  \\\n      GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).VerifyRegisteredTestNames( \\\n          GTEST_STRINGIFY_(SuiteName), __FILE__, __LINE__, #__VA_ARGS__)\n\n// Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n#define REGISTER_TYPED_TEST_CASE_P                                           \\\n  static_assert(::testing::internal::RegisterTypedTestCase_P_IsDeprecated(), \\\n                \"\");                                                         \\\n  REGISTER_TYPED_TEST_SUITE_P\n#endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n#define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...)     \\\n  static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1,                     \\\n                \"test-suit-prefix must not be empty\");                    \\\n  static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ =      \\\n      ::testing::internal::TypeParameterizedTestSuite<                    \\\n          SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_,  \\\n          ::testing::internal::GenerateTypeList<Types>::type>::           \\\n          Register(GTEST_STRINGIFY_(Prefix),                              \\\n                   ::testing::internal::CodeLocation(__FILE__, __LINE__), \\\n                   &GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName),           \\\n                   GTEST_STRINGIFY_(SuiteName),                           \\\n                   GTEST_REGISTERED_TEST_NAMES_(SuiteName),               \\\n                   ::testing::internal::GenerateNames<                    \\\n                       ::testing::internal::NameGeneratorSelector<        \\\n                           __VA_ARGS__>::type,                            \\\n                       ::testing::internal::GenerateTypeList<Types>::type>())\n\n// Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n#define INSTANTIATE_TYPED_TEST_CASE_P                                      \\\n  static_assert(                                                           \\\n      ::testing::internal::InstantiateTypedTestCase_P_IsDeprecated(), \"\"); \\\n  INSTANTIATE_TYPED_TEST_SUITE_P\n#endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n#endif  // GOOGLETEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/include/gtest/gtest.h",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// The Google C++ Testing and Mocking Framework (Google Test)\n//\n// This header file defines the public API for Google Test.  It should be\n// included by any test program that uses Google Test.\n//\n// IMPORTANT NOTE: Due to limitation of the C++ language, we have to\n// leave some internal implementation details in this header file.\n// They are clearly marked by comments like this:\n//\n//   // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.\n//\n// Such code is NOT meant to be used by a user directly, and is subject\n// to CHANGE WITHOUT NOTICE.  Therefore DO NOT DEPEND ON IT in a user\n// program!\n//\n// Acknowledgment: Google Test borrowed the idea of automatic test\n// registration from Barthelemy Dagenais' (barthelemy@prologique.com)\n// easyUnit framework.\n\n#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_H_\n#define GOOGLETEST_INCLUDE_GTEST_GTEST_H_\n\n#include <cstddef>\n#include <limits>\n#include <memory>\n#include <ostream>\n#include <type_traits>\n#include <vector>\n\n#include \"gtest/gtest-assertion-result.h\"\n#include \"gtest/gtest-death-test.h\"\n#include \"gtest/gtest-matchers.h\"\n#include \"gtest/gtest-message.h\"\n#include \"gtest/gtest-param-test.h\"\n#include \"gtest/gtest-printers.h\"\n#include \"gtest/gtest-test-part.h\"\n#include \"gtest/gtest-typed-test.h\"\n#include \"gtest/gtest_pred_impl.h\"\n#include \"gtest/gtest_prod.h\"\n#include \"gtest/internal/gtest-internal.h\"\n#include \"gtest/internal/gtest-string.h\"\n\nGTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \\\n/* class A needs to have dll-interface to be used by clients of class B */)\n\n// Declares the flags.\n\n// This flag temporary enables the disabled tests.\nGTEST_DECLARE_bool_(also_run_disabled_tests);\n\n// This flag brings the debugger on an assertion failure.\nGTEST_DECLARE_bool_(break_on_failure);\n\n// This flag controls whether Google Test catches all test-thrown exceptions\n// and logs them as failures.\nGTEST_DECLARE_bool_(catch_exceptions);\n\n// This flag enables using colors in terminal output. Available values are\n// \"yes\" to enable colors, \"no\" (disable colors), or \"auto\" (the default)\n// to let Google Test decide.\nGTEST_DECLARE_string_(color);\n\n// This flag controls whether the test runner should continue execution past\n// first failure.\nGTEST_DECLARE_bool_(fail_fast);\n\n// This flag sets up the filter to select by name using a glob pattern\n// the tests to run. If the filter is not given all tests are executed.\nGTEST_DECLARE_string_(filter);\n\n// This flag controls whether Google Test installs a signal handler that dumps\n// debugging information when fatal signals are raised.\nGTEST_DECLARE_bool_(install_failure_signal_handler);\n\n// This flag causes the Google Test to list tests. None of the tests listed\n// are actually run if the flag is provided.\nGTEST_DECLARE_bool_(list_tests);\n\n// This flag controls whether Google Test emits a detailed XML report to a file\n// in addition to its normal textual output.\nGTEST_DECLARE_string_(output);\n\n// This flags control whether Google Test prints only test failures.\nGTEST_DECLARE_bool_(brief);\n\n// This flags control whether Google Test prints the elapsed time for each\n// test.\nGTEST_DECLARE_bool_(print_time);\n\n// This flags control whether Google Test prints UTF8 characters as text.\nGTEST_DECLARE_bool_(print_utf8);\n\n// This flag specifies the random number seed.\nGTEST_DECLARE_int32_(random_seed);\n\n// This flag sets how many times the tests are repeated. The default value\n// is 1. If the value is -1 the tests are repeating forever.\nGTEST_DECLARE_int32_(repeat);\n\n// This flag controls whether Google Test Environments are recreated for each\n// repeat of the tests. The default value is true. If set to false the global\n// test Environment objects are only set up once, for the first iteration, and\n// only torn down once, for the last.\nGTEST_DECLARE_bool_(recreate_environments_when_repeating);\n\n// This flag controls whether Google Test includes Google Test internal\n// stack frames in failure stack traces.\nGTEST_DECLARE_bool_(show_internal_stack_frames);\n\n// When this flag is specified, tests' order is randomized on every iteration.\nGTEST_DECLARE_bool_(shuffle);\n\n// This flag specifies the maximum number of stack frames to be\n// printed in a failure message.\nGTEST_DECLARE_int32_(stack_trace_depth);\n\n// When this flag is specified, a failed assertion will throw an\n// exception if exceptions are enabled, or exit the program with a\n// non-zero code otherwise. For use with an external test framework.\nGTEST_DECLARE_bool_(throw_on_failure);\n\n// When this flag is set with a \"host:port\" string, on supported\n// platforms test results are streamed to the specified port on\n// the specified host machine.\nGTEST_DECLARE_string_(stream_result_to);\n\n#if GTEST_USE_OWN_FLAGFILE_FLAG_\nGTEST_DECLARE_string_(flagfile);\n#endif  // GTEST_USE_OWN_FLAGFILE_FLAG_\n\nnamespace testing {\n\n// Silence C4100 (unreferenced formal parameter) and 4805\n// unsafe mix of type 'const int' and type 'const bool'\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 4805)\n#pragma warning(disable : 4100)\n#endif\n\n// The upper limit for valid stack trace depths.\nconst int kMaxStackTraceDepth = 100;\n\nnamespace internal {\n\nclass AssertHelper;\nclass DefaultGlobalTestPartResultReporter;\nclass ExecDeathTest;\nclass NoExecDeathTest;\nclass FinalSuccessChecker;\nclass GTestFlagSaver;\nclass StreamingListenerTest;\nclass TestResultAccessor;\nclass TestEventListenersAccessor;\nclass TestEventRepeater;\nclass UnitTestRecordPropertyTestHelper;\nclass WindowsDeathTest;\nclass FuchsiaDeathTest;\nclass UnitTestImpl* GetUnitTestImpl();\nvoid ReportFailureInUnknownLocation(TestPartResult::Type result_type,\n                                    const std::string& message);\nstd::set<std::string>* GetIgnoredParameterizedTestSuites();\n\n}  // namespace internal\n\n// The friend relationship of some of these classes is cyclic.\n// If we don't forward declare them the compiler might confuse the classes\n// in friendship clauses with same named classes on the scope.\nclass Test;\nclass TestSuite;\n\n// Old API is still available but deprecated\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\nusing TestCase = TestSuite;\n#endif\nclass TestInfo;\nclass UnitTest;\n\n// The abstract class that all tests inherit from.\n//\n// In Google Test, a unit test program contains one or many TestSuites, and\n// each TestSuite contains one or many Tests.\n//\n// When you define a test using the TEST macro, you don't need to\n// explicitly derive from Test - the TEST macro automatically does\n// this for you.\n//\n// The only time you derive from Test is when defining a test fixture\n// to be used in a TEST_F.  For example:\n//\n//   class FooTest : public testing::Test {\n//    protected:\n//     void SetUp() override { ... }\n//     void TearDown() override { ... }\n//     ...\n//   };\n//\n//   TEST_F(FooTest, Bar) { ... }\n//   TEST_F(FooTest, Baz) { ... }\n//\n// Test is not copyable.\nclass GTEST_API_ Test {\n public:\n  friend class TestInfo;\n\n  // The d'tor is virtual as we intend to inherit from Test.\n  virtual ~Test();\n\n  // Sets up the stuff shared by all tests in this test suite.\n  //\n  // Google Test will call Foo::SetUpTestSuite() before running the first\n  // test in test suite Foo.  Hence a sub-class can define its own\n  // SetUpTestSuite() method to shadow the one defined in the super\n  // class.\n  static void SetUpTestSuite() {}\n\n  // Tears down the stuff shared by all tests in this test suite.\n  //\n  // Google Test will call Foo::TearDownTestSuite() after running the last\n  // test in test suite Foo.  Hence a sub-class can define its own\n  // TearDownTestSuite() method to shadow the one defined in the super\n  // class.\n  static void TearDownTestSuite() {}\n\n  // Legacy API is deprecated but still available. Use SetUpTestSuite and\n  // TearDownTestSuite instead.\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  static void TearDownTestCase() {}\n  static void SetUpTestCase() {}\n#endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n  // Returns true if and only if the current test has a fatal failure.\n  static bool HasFatalFailure();\n\n  // Returns true if and only if the current test has a non-fatal failure.\n  static bool HasNonfatalFailure();\n\n  // Returns true if and only if the current test was skipped.\n  static bool IsSkipped();\n\n  // Returns true if and only if the current test has a (either fatal or\n  // non-fatal) failure.\n  static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); }\n\n  // Logs a property for the current test, test suite, or for the entire\n  // invocation of the test program when used outside of the context of a\n  // test suite.  Only the last value for a given key is remembered.  These\n  // are public static so they can be called from utility functions that are\n  // not members of the test fixture.  Calls to RecordProperty made during\n  // lifespan of the test (from the moment its constructor starts to the\n  // moment its destructor finishes) will be output in XML as attributes of\n  // the <testcase> element.  Properties recorded from fixture's\n  // SetUpTestSuite or TearDownTestSuite are logged as attributes of the\n  // corresponding <testsuite> element.  Calls to RecordProperty made in the\n  // global context (before or after invocation of RUN_ALL_TESTS and from\n  // SetUp/TearDown method of Environment objects registered with Google\n  // Test) will be output as attributes of the <testsuites> element.\n  static void RecordProperty(const std::string& key, const std::string& value);\n  static void RecordProperty(const std::string& key, int value);\n\n protected:\n  // Creates a Test object.\n  Test();\n\n  // Sets up the test fixture.\n  virtual void SetUp();\n\n  // Tears down the test fixture.\n  virtual void TearDown();\n\n private:\n  // Returns true if and only if the current test has the same fixture class\n  // as the first test in the current test suite.\n  static bool HasSameFixtureClass();\n\n  // Runs the test after the test fixture has been set up.\n  //\n  // A sub-class must implement this to define the test logic.\n  //\n  // DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM.\n  // Instead, use the TEST or TEST_F macro.\n  virtual void TestBody() = 0;\n\n  // Sets up, executes, and tears down the test.\n  void Run();\n\n  // Deletes self.  We deliberately pick an unusual name for this\n  // internal method to avoid clashing with names used in user TESTs.\n  void DeleteSelf_() { delete this; }\n\n  const std::unique_ptr<GTEST_FLAG_SAVER_> gtest_flag_saver_;\n\n  // Often a user misspells SetUp() as Setup() and spends a long time\n  // wondering why it is never called by Google Test.  The declaration of\n  // the following method is solely for catching such an error at\n  // compile time:\n  //\n  //   - The return type is deliberately chosen to be not void, so it\n  //   will be a conflict if void Setup() is declared in the user's\n  //   test fixture.\n  //\n  //   - This method is private, so it will be another compiler error\n  //   if the method is called from the user's test fixture.\n  //\n  // DO NOT OVERRIDE THIS FUNCTION.\n  //\n  // If you see an error about overriding the following function or\n  // about it being private, you have mis-spelled SetUp() as Setup().\n  struct Setup_should_be_spelled_SetUp {};\n  virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; }\n\n  // We disallow copying Tests.\n  Test(const Test&) = delete;\n  Test& operator=(const Test&) = delete;\n};\n\ntypedef internal::TimeInMillis TimeInMillis;\n\n// A copyable object representing a user specified test property which can be\n// output as a key/value string pair.\n//\n// Don't inherit from TestProperty as its destructor is not virtual.\nclass TestProperty {\n public:\n  // C'tor.  TestProperty does NOT have a default constructor.\n  // Always use this constructor (with parameters) to create a\n  // TestProperty object.\n  TestProperty(const std::string& a_key, const std::string& a_value)\n      : key_(a_key), value_(a_value) {}\n\n  // Gets the user supplied key.\n  const char* key() const { return key_.c_str(); }\n\n  // Gets the user supplied value.\n  const char* value() const { return value_.c_str(); }\n\n  // Sets a new value, overriding the one supplied in the constructor.\n  void SetValue(const std::string& new_value) { value_ = new_value; }\n\n private:\n  // The key supplied by the user.\n  std::string key_;\n  // The value supplied by the user.\n  std::string value_;\n};\n\n// The result of a single Test.  This includes a list of\n// TestPartResults, a list of TestProperties, a count of how many\n// death tests there are in the Test, and how much time it took to run\n// the Test.\n//\n// TestResult is not copyable.\nclass GTEST_API_ TestResult {\n public:\n  // Creates an empty TestResult.\n  TestResult();\n\n  // D'tor.  Do not inherit from TestResult.\n  ~TestResult();\n\n  // Gets the number of all test parts.  This is the sum of the number\n  // of successful test parts and the number of failed test parts.\n  int total_part_count() const;\n\n  // Returns the number of the test properties.\n  int test_property_count() const;\n\n  // Returns true if and only if the test passed (i.e. no test part failed).\n  bool Passed() const { return !Skipped() && !Failed(); }\n\n  // Returns true if and only if the test was skipped.\n  bool Skipped() const;\n\n  // Returns true if and only if the test failed.\n  bool Failed() const;\n\n  // Returns true if and only if the test fatally failed.\n  bool HasFatalFailure() const;\n\n  // Returns true if and only if the test has a non-fatal failure.\n  bool HasNonfatalFailure() const;\n\n  // Returns the elapsed time, in milliseconds.\n  TimeInMillis elapsed_time() const { return elapsed_time_; }\n\n  // Gets the time of the test case start, in ms from the start of the\n  // UNIX epoch.\n  TimeInMillis start_timestamp() const { return start_timestamp_; }\n\n  // Returns the i-th test part result among all the results. i can range from 0\n  // to total_part_count() - 1. If i is not in that range, aborts the program.\n  const TestPartResult& GetTestPartResult(int i) const;\n\n  // Returns the i-th test property. i can range from 0 to\n  // test_property_count() - 1. If i is not in that range, aborts the\n  // program.\n  const TestProperty& GetTestProperty(int i) const;\n\n private:\n  friend class TestInfo;\n  friend class TestSuite;\n  friend class UnitTest;\n  friend class internal::DefaultGlobalTestPartResultReporter;\n  friend class internal::ExecDeathTest;\n  friend class internal::TestResultAccessor;\n  friend class internal::UnitTestImpl;\n  friend class internal::WindowsDeathTest;\n  friend class internal::FuchsiaDeathTest;\n\n  // Gets the vector of TestPartResults.\n  const std::vector<TestPartResult>& test_part_results() const {\n    return test_part_results_;\n  }\n\n  // Gets the vector of TestProperties.\n  const std::vector<TestProperty>& test_properties() const {\n    return test_properties_;\n  }\n\n  // Sets the start time.\n  void set_start_timestamp(TimeInMillis start) { start_timestamp_ = start; }\n\n  // Sets the elapsed time.\n  void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; }\n\n  // Adds a test property to the list. The property is validated and may add\n  // a non-fatal failure if invalid (e.g., if it conflicts with reserved\n  // key names). If a property is already recorded for the same key, the\n  // value will be updated, rather than storing multiple values for the same\n  // key.  xml_element specifies the element for which the property is being\n  // recorded and is used for validation.\n  void RecordProperty(const std::string& xml_element,\n                      const TestProperty& test_property);\n\n  // Adds a failure if the key is a reserved attribute of Google Test\n  // testsuite tags.  Returns true if the property is valid.\n  // FIXME: Validate attribute names are legal and human readable.\n  static bool ValidateTestProperty(const std::string& xml_element,\n                                   const TestProperty& test_property);\n\n  // Adds a test part result to the list.\n  void AddTestPartResult(const TestPartResult& test_part_result);\n\n  // Returns the death test count.\n  int death_test_count() const { return death_test_count_; }\n\n  // Increments the death test count, returning the new count.\n  int increment_death_test_count() { return ++death_test_count_; }\n\n  // Clears the test part results.\n  void ClearTestPartResults();\n\n  // Clears the object.\n  void Clear();\n\n  // Protects mutable state of the property vector and of owned\n  // properties, whose values may be updated.\n  internal::Mutex test_properties_mutex_;\n\n  // The vector of TestPartResults\n  std::vector<TestPartResult> test_part_results_;\n  // The vector of TestProperties\n  std::vector<TestProperty> test_properties_;\n  // Running count of death tests.\n  int death_test_count_;\n  // The start time, in milliseconds since UNIX Epoch.\n  TimeInMillis start_timestamp_;\n  // The elapsed time, in milliseconds.\n  TimeInMillis elapsed_time_;\n\n  // We disallow copying TestResult.\n  TestResult(const TestResult&) = delete;\n  TestResult& operator=(const TestResult&) = delete;\n};  // class TestResult\n\n// A TestInfo object stores the following information about a test:\n//\n//   Test suite name\n//   Test name\n//   Whether the test should be run\n//   A function pointer that creates the test object when invoked\n//   Test result\n//\n// The constructor of TestInfo registers itself with the UnitTest\n// singleton such that the RUN_ALL_TESTS() macro knows which tests to\n// run.\nclass GTEST_API_ TestInfo {\n public:\n  // Destructs a TestInfo object.  This function is not virtual, so\n  // don't inherit from TestInfo.\n  ~TestInfo();\n\n  // Returns the test suite name.\n  const char* test_suite_name() const { return test_suite_name_.c_str(); }\n\n// Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  const char* test_case_name() const { return test_suite_name(); }\n#endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n  // Returns the test name.\n  const char* name() const { return name_.c_str(); }\n\n  // Returns the name of the parameter type, or NULL if this is not a typed\n  // or a type-parameterized test.\n  const char* type_param() const {\n    if (type_param_.get() != nullptr) return type_param_->c_str();\n    return nullptr;\n  }\n\n  // Returns the text representation of the value parameter, or NULL if this\n  // is not a value-parameterized test.\n  const char* value_param() const {\n    if (value_param_.get() != nullptr) return value_param_->c_str();\n    return nullptr;\n  }\n\n  // Returns the file name where this test is defined.\n  const char* file() const { return location_.file.c_str(); }\n\n  // Returns the line where this test is defined.\n  int line() const { return location_.line; }\n\n  // Return true if this test should not be run because it's in another shard.\n  bool is_in_another_shard() const { return is_in_another_shard_; }\n\n  // Returns true if this test should run, that is if the test is not\n  // disabled (or it is disabled but the also_run_disabled_tests flag has\n  // been specified) and its full name matches the user-specified filter.\n  //\n  // Google Test allows the user to filter the tests by their full names.\n  // The full name of a test Bar in test suite Foo is defined as\n  // \"Foo.Bar\".  Only the tests that match the filter will run.\n  //\n  // A filter is a colon-separated list of glob (not regex) patterns,\n  // optionally followed by a '-' and a colon-separated list of\n  // negative patterns (tests to exclude).  A test is run if it\n  // matches one of the positive patterns and does not match any of\n  // the negative patterns.\n  //\n  // For example, *A*:Foo.* is a filter that matches any string that\n  // contains the character 'A' or starts with \"Foo.\".\n  bool should_run() const { return should_run_; }\n\n  // Returns true if and only if this test will appear in the XML report.\n  bool is_reportable() const {\n    // The XML report includes tests matching the filter, excluding those\n    // run in other shards.\n    return matches_filter_ && !is_in_another_shard_;\n  }\n\n  // Returns the result of the test.\n  const TestResult* result() const { return &result_; }\n\n private:\n#if GTEST_HAS_DEATH_TEST\n  friend class internal::DefaultDeathTestFactory;\n#endif  // GTEST_HAS_DEATH_TEST\n  friend class Test;\n  friend class TestSuite;\n  friend class internal::UnitTestImpl;\n  friend class internal::StreamingListenerTest;\n  friend TestInfo* internal::MakeAndRegisterTestInfo(\n      const char* test_suite_name, const char* name, const char* type_param,\n      const char* value_param, internal::CodeLocation code_location,\n      internal::TypeId fixture_class_id, internal::SetUpTestSuiteFunc set_up_tc,\n      internal::TearDownTestSuiteFunc tear_down_tc,\n      internal::TestFactoryBase* factory);\n\n  // Constructs a TestInfo object. The newly constructed instance assumes\n  // ownership of the factory object.\n  TestInfo(const std::string& test_suite_name, const std::string& name,\n           const char* a_type_param,   // NULL if not a type-parameterized test\n           const char* a_value_param,  // NULL if not a value-parameterized test\n           internal::CodeLocation a_code_location,\n           internal::TypeId fixture_class_id,\n           internal::TestFactoryBase* factory);\n\n  // Increments the number of death tests encountered in this test so\n  // far.\n  int increment_death_test_count() {\n    return result_.increment_death_test_count();\n  }\n\n  // Creates the test object, runs it, records its result, and then\n  // deletes it.\n  void Run();\n\n  // Skip and records the test result for this object.\n  void Skip();\n\n  static void ClearTestResult(TestInfo* test_info) {\n    test_info->result_.Clear();\n  }\n\n  // These fields are immutable properties of the test.\n  const std::string test_suite_name_;  // test suite name\n  const std::string name_;             // Test name\n  // Name of the parameter type, or NULL if this is not a typed or a\n  // type-parameterized test.\n  const std::unique_ptr<const ::std::string> type_param_;\n  // Text representation of the value parameter, or NULL if this is not a\n  // value-parameterized test.\n  const std::unique_ptr<const ::std::string> value_param_;\n  internal::CodeLocation location_;\n  const internal::TypeId fixture_class_id_;  // ID of the test fixture class\n  bool should_run_;           // True if and only if this test should run\n  bool is_disabled_;          // True if and only if this test is disabled\n  bool matches_filter_;       // True if this test matches the\n                              // user-specified filter.\n  bool is_in_another_shard_;  // Will be run in another shard.\n  internal::TestFactoryBase* const factory_;  // The factory that creates\n                                              // the test object\n\n  // This field is mutable and needs to be reset before running the\n  // test for the second time.\n  TestResult result_;\n\n  TestInfo(const TestInfo&) = delete;\n  TestInfo& operator=(const TestInfo&) = delete;\n};\n\n// A test suite, which consists of a vector of TestInfos.\n//\n// TestSuite is not copyable.\nclass GTEST_API_ TestSuite {\n public:\n  // Creates a TestSuite with the given name.\n  //\n  // TestSuite does NOT have a default constructor.  Always use this\n  // constructor to create a TestSuite object.\n  //\n  // Arguments:\n  //\n  //   name:         name of the test suite\n  //   a_type_param: the name of the test's type parameter, or NULL if\n  //                 this is not a type-parameterized test.\n  //   set_up_tc:    pointer to the function that sets up the test suite\n  //   tear_down_tc: pointer to the function that tears down the test suite\n  TestSuite(const char* name, const char* a_type_param,\n            internal::SetUpTestSuiteFunc set_up_tc,\n            internal::TearDownTestSuiteFunc tear_down_tc);\n\n  // Destructor of TestSuite.\n  virtual ~TestSuite();\n\n  // Gets the name of the TestSuite.\n  const char* name() const { return name_.c_str(); }\n\n  // Returns the name of the parameter type, or NULL if this is not a\n  // type-parameterized test suite.\n  const char* type_param() const {\n    if (type_param_.get() != nullptr) return type_param_->c_str();\n    return nullptr;\n  }\n\n  // Returns true if any test in this test suite should run.\n  bool should_run() const { return should_run_; }\n\n  // Gets the number of successful tests in this test suite.\n  int successful_test_count() const;\n\n  // Gets the number of skipped tests in this test suite.\n  int skipped_test_count() const;\n\n  // Gets the number of failed tests in this test suite.\n  int failed_test_count() const;\n\n  // Gets the number of disabled tests that will be reported in the XML report.\n  int reportable_disabled_test_count() const;\n\n  // Gets the number of disabled tests in this test suite.\n  int disabled_test_count() const;\n\n  // Gets the number of tests to be printed in the XML report.\n  int reportable_test_count() const;\n\n  // Get the number of tests in this test suite that should run.\n  int test_to_run_count() const;\n\n  // Gets the number of all tests in this test suite.\n  int total_test_count() const;\n\n  // Returns true if and only if the test suite passed.\n  bool Passed() const { return !Failed(); }\n\n  // Returns true if and only if the test suite failed.\n  bool Failed() const {\n    return failed_test_count() > 0 || ad_hoc_test_result().Failed();\n  }\n\n  // Returns the elapsed time, in milliseconds.\n  TimeInMillis elapsed_time() const { return elapsed_time_; }\n\n  // Gets the time of the test suite start, in ms from the start of the\n  // UNIX epoch.\n  TimeInMillis start_timestamp() const { return start_timestamp_; }\n\n  // Returns the i-th test among all the tests. i can range from 0 to\n  // total_test_count() - 1. If i is not in that range, returns NULL.\n  const TestInfo* GetTestInfo(int i) const;\n\n  // Returns the TestResult that holds test properties recorded during\n  // execution of SetUpTestSuite and TearDownTestSuite.\n  const TestResult& ad_hoc_test_result() const { return ad_hoc_test_result_; }\n\n private:\n  friend class Test;\n  friend class internal::UnitTestImpl;\n\n  // Gets the (mutable) vector of TestInfos in this TestSuite.\n  std::vector<TestInfo*>& test_info_list() { return test_info_list_; }\n\n  // Gets the (immutable) vector of TestInfos in this TestSuite.\n  const std::vector<TestInfo*>& test_info_list() const {\n    return test_info_list_;\n  }\n\n  // Returns the i-th test among all the tests. i can range from 0 to\n  // total_test_count() - 1. If i is not in that range, returns NULL.\n  TestInfo* GetMutableTestInfo(int i);\n\n  // Sets the should_run member.\n  void set_should_run(bool should) { should_run_ = should; }\n\n  // Adds a TestInfo to this test suite.  Will delete the TestInfo upon\n  // destruction of the TestSuite object.\n  void AddTestInfo(TestInfo* test_info);\n\n  // Clears the results of all tests in this test suite.\n  void ClearResult();\n\n  // Clears the results of all tests in the given test suite.\n  static void ClearTestSuiteResult(TestSuite* test_suite) {\n    test_suite->ClearResult();\n  }\n\n  // Runs every test in this TestSuite.\n  void Run();\n\n  // Skips the execution of tests under this TestSuite\n  void Skip();\n\n  // Runs SetUpTestSuite() for this TestSuite.  This wrapper is needed\n  // for catching exceptions thrown from SetUpTestSuite().\n  void RunSetUpTestSuite() {\n    if (set_up_tc_ != nullptr) {\n      (*set_up_tc_)();\n    }\n  }\n\n  // Runs TearDownTestSuite() for this TestSuite.  This wrapper is\n  // needed for catching exceptions thrown from TearDownTestSuite().\n  void RunTearDownTestSuite() {\n    if (tear_down_tc_ != nullptr) {\n      (*tear_down_tc_)();\n    }\n  }\n\n  // Returns true if and only if test passed.\n  static bool TestPassed(const TestInfo* test_info) {\n    return test_info->should_run() && test_info->result()->Passed();\n  }\n\n  // Returns true if and only if test skipped.\n  static bool TestSkipped(const TestInfo* test_info) {\n    return test_info->should_run() && test_info->result()->Skipped();\n  }\n\n  // Returns true if and only if test failed.\n  static bool TestFailed(const TestInfo* test_info) {\n    return test_info->should_run() && test_info->result()->Failed();\n  }\n\n  // Returns true if and only if the test is disabled and will be reported in\n  // the XML report.\n  static bool TestReportableDisabled(const TestInfo* test_info) {\n    return test_info->is_reportable() && test_info->is_disabled_;\n  }\n\n  // Returns true if and only if test is disabled.\n  static bool TestDisabled(const TestInfo* test_info) {\n    return test_info->is_disabled_;\n  }\n\n  // Returns true if and only if this test will appear in the XML report.\n  static bool TestReportable(const TestInfo* test_info) {\n    return test_info->is_reportable();\n  }\n\n  // Returns true if the given test should run.\n  static bool ShouldRunTest(const TestInfo* test_info) {\n    return test_info->should_run();\n  }\n\n  // Shuffles the tests in this test suite.\n  void ShuffleTests(internal::Random* random);\n\n  // Restores the test order to before the first shuffle.\n  void UnshuffleTests();\n\n  // Name of the test suite.\n  std::string name_;\n  // Name of the parameter type, or NULL if this is not a typed or a\n  // type-parameterized test.\n  const std::unique_ptr<const ::std::string> type_param_;\n  // The vector of TestInfos in their original order.  It owns the\n  // elements in the vector.\n  std::vector<TestInfo*> test_info_list_;\n  // Provides a level of indirection for the test list to allow easy\n  // shuffling and restoring the test order.  The i-th element in this\n  // vector is the index of the i-th test in the shuffled test list.\n  std::vector<int> test_indices_;\n  // Pointer to the function that sets up the test suite.\n  internal::SetUpTestSuiteFunc set_up_tc_;\n  // Pointer to the function that tears down the test suite.\n  internal::TearDownTestSuiteFunc tear_down_tc_;\n  // True if and only if any test in this test suite should run.\n  bool should_run_;\n  // The start time, in milliseconds since UNIX Epoch.\n  TimeInMillis start_timestamp_;\n  // Elapsed time, in milliseconds.\n  TimeInMillis elapsed_time_;\n  // Holds test properties recorded during execution of SetUpTestSuite and\n  // TearDownTestSuite.\n  TestResult ad_hoc_test_result_;\n\n  // We disallow copying TestSuites.\n  TestSuite(const TestSuite&) = delete;\n  TestSuite& operator=(const TestSuite&) = delete;\n};\n\n// An Environment object is capable of setting up and tearing down an\n// environment.  You should subclass this to define your own\n// environment(s).\n//\n// An Environment object does the set-up and tear-down in virtual\n// methods SetUp() and TearDown() instead of the constructor and the\n// destructor, as:\n//\n//   1. You cannot safely throw from a destructor.  This is a problem\n//      as in some cases Google Test is used where exceptions are enabled, and\n//      we may want to implement ASSERT_* using exceptions where they are\n//      available.\n//   2. You cannot use ASSERT_* directly in a constructor or\n//      destructor.\nclass Environment {\n public:\n  // The d'tor is virtual as we need to subclass Environment.\n  virtual ~Environment() {}\n\n  // Override this to define how to set up the environment.\n  virtual void SetUp() {}\n\n  // Override this to define how to tear down the environment.\n  virtual void TearDown() {}\n\n private:\n  // If you see an error about overriding the following function or\n  // about it being private, you have mis-spelled SetUp() as Setup().\n  struct Setup_should_be_spelled_SetUp {};\n  virtual Setup_should_be_spelled_SetUp* Setup() { return nullptr; }\n};\n\n#if GTEST_HAS_EXCEPTIONS\n\n// Exception which can be thrown from TestEventListener::OnTestPartResult.\nclass GTEST_API_ AssertionException\n    : public internal::GoogleTestFailureException {\n public:\n  explicit AssertionException(const TestPartResult& result)\n      : GoogleTestFailureException(result) {}\n};\n\n#endif  // GTEST_HAS_EXCEPTIONS\n\n// The interface for tracing execution of tests. The methods are organized in\n// the order the corresponding events are fired.\nclass TestEventListener {\n public:\n  virtual ~TestEventListener() {}\n\n  // Fired before any test activity starts.\n  virtual void OnTestProgramStart(const UnitTest& unit_test) = 0;\n\n  // Fired before each iteration of tests starts.  There may be more than\n  // one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration\n  // index, starting from 0.\n  virtual void OnTestIterationStart(const UnitTest& unit_test,\n                                    int iteration) = 0;\n\n  // Fired before environment set-up for each iteration of tests starts.\n  virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0;\n\n  // Fired after environment set-up for each iteration of tests ends.\n  virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0;\n\n  // Fired before the test suite starts.\n  virtual void OnTestSuiteStart(const TestSuite& /*test_suite*/) {}\n\n  //  Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  virtual void OnTestCaseStart(const TestCase& /*test_case*/) {}\n#endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n  // Fired before the test starts.\n  virtual void OnTestStart(const TestInfo& test_info) = 0;\n\n  // Fired when a test is disabled\n  virtual void OnTestDisabled(const TestInfo& /*test_info*/) {}\n\n  // Fired after a failed assertion or a SUCCEED() invocation.\n  // If you want to throw an exception from this function to skip to the next\n  // TEST, it must be AssertionException defined above, or inherited from it.\n  virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0;\n\n  // Fired after the test ends.\n  virtual void OnTestEnd(const TestInfo& test_info) = 0;\n\n  // Fired after the test suite ends.\n  virtual void OnTestSuiteEnd(const TestSuite& /*test_suite*/) {}\n\n//  Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {}\n#endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n  // Fired before environment tear-down for each iteration of tests starts.\n  virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0;\n\n  // Fired after environment tear-down for each iteration of tests ends.\n  virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0;\n\n  // Fired after each iteration of tests finishes.\n  virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration) = 0;\n\n  // Fired after all test activities have ended.\n  virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0;\n};\n\n// The convenience class for users who need to override just one or two\n// methods and are not concerned that a possible change to a signature of\n// the methods they override will not be caught during the build.  For\n// comments about each method please see the definition of TestEventListener\n// above.\nclass EmptyTestEventListener : public TestEventListener {\n public:\n  void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}\n  void OnTestIterationStart(const UnitTest& /*unit_test*/,\n                            int /*iteration*/) override {}\n  void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {}\n  void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}\n  void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {}\n//  Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  void OnTestCaseStart(const TestCase& /*test_case*/) override {}\n#endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n  void OnTestStart(const TestInfo& /*test_info*/) override {}\n  void OnTestDisabled(const TestInfo& /*test_info*/) override {}\n  void OnTestPartResult(const TestPartResult& /*test_part_result*/) override {}\n  void OnTestEnd(const TestInfo& /*test_info*/) override {}\n  void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {}\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  void OnTestCaseEnd(const TestCase& /*test_case*/) override {}\n#endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n  void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {}\n  void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}\n  void OnTestIterationEnd(const UnitTest& /*unit_test*/,\n                          int /*iteration*/) override {}\n  void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}\n};\n\n// TestEventListeners lets users add listeners to track events in Google Test.\nclass GTEST_API_ TestEventListeners {\n public:\n  TestEventListeners();\n  ~TestEventListeners();\n\n  // Appends an event listener to the end of the list. Google Test assumes\n  // the ownership of the listener (i.e. it will delete the listener when\n  // the test program finishes).\n  void Append(TestEventListener* listener);\n\n  // Removes the given event listener from the list and returns it.  It then\n  // becomes the caller's responsibility to delete the listener. Returns\n  // NULL if the listener is not found in the list.\n  TestEventListener* Release(TestEventListener* listener);\n\n  // Returns the standard listener responsible for the default console\n  // output.  Can be removed from the listeners list to shut down default\n  // console output.  Note that removing this object from the listener list\n  // with Release transfers its ownership to the caller and makes this\n  // function return NULL the next time.\n  TestEventListener* default_result_printer() const {\n    return default_result_printer_;\n  }\n\n  // Returns the standard listener responsible for the default XML output\n  // controlled by the --gtest_output=xml flag.  Can be removed from the\n  // listeners list by users who want to shut down the default XML output\n  // controlled by this flag and substitute it with custom one.  Note that\n  // removing this object from the listener list with Release transfers its\n  // ownership to the caller and makes this function return NULL the next\n  // time.\n  TestEventListener* default_xml_generator() const {\n    return default_xml_generator_;\n  }\n\n private:\n  friend class TestSuite;\n  friend class TestInfo;\n  friend class internal::DefaultGlobalTestPartResultReporter;\n  friend class internal::NoExecDeathTest;\n  friend class internal::TestEventListenersAccessor;\n  friend class internal::UnitTestImpl;\n\n  // Returns repeater that broadcasts the TestEventListener events to all\n  // subscribers.\n  TestEventListener* repeater();\n\n  // Sets the default_result_printer attribute to the provided listener.\n  // The listener is also added to the listener list and previous\n  // default_result_printer is removed from it and deleted. The listener can\n  // also be NULL in which case it will not be added to the list. Does\n  // nothing if the previous and the current listener objects are the same.\n  void SetDefaultResultPrinter(TestEventListener* listener);\n\n  // Sets the default_xml_generator attribute to the provided listener.  The\n  // listener is also added to the listener list and previous\n  // default_xml_generator is removed from it and deleted. The listener can\n  // also be NULL in which case it will not be added to the list. Does\n  // nothing if the previous and the current listener objects are the same.\n  void SetDefaultXmlGenerator(TestEventListener* listener);\n\n  // Controls whether events will be forwarded by the repeater to the\n  // listeners in the list.\n  bool EventForwardingEnabled() const;\n  void SuppressEventForwarding();\n\n  // The actual list of listeners.\n  internal::TestEventRepeater* repeater_;\n  // Listener responsible for the standard result output.\n  TestEventListener* default_result_printer_;\n  // Listener responsible for the creation of the XML output file.\n  TestEventListener* default_xml_generator_;\n\n  // We disallow copying TestEventListeners.\n  TestEventListeners(const TestEventListeners&) = delete;\n  TestEventListeners& operator=(const TestEventListeners&) = delete;\n};\n\n// A UnitTest consists of a vector of TestSuites.\n//\n// This is a singleton class.  The only instance of UnitTest is\n// created when UnitTest::GetInstance() is first called.  This\n// instance is never deleted.\n//\n// UnitTest is not copyable.\n//\n// This class is thread-safe as long as the methods are called\n// according to their specification.\nclass GTEST_API_ UnitTest {\n public:\n  // Gets the singleton UnitTest object.  The first time this method\n  // is called, a UnitTest object is constructed and returned.\n  // Consecutive calls will return the same object.\n  static UnitTest* GetInstance();\n\n  // Runs all tests in this UnitTest object and prints the result.\n  // Returns 0 if successful, or 1 otherwise.\n  //\n  // This method can only be called from the main thread.\n  //\n  // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.\n  int Run() GTEST_MUST_USE_RESULT_;\n\n  // Returns the working directory when the first TEST() or TEST_F()\n  // was executed.  The UnitTest object owns the string.\n  const char* original_working_dir() const;\n\n  // Returns the TestSuite object for the test that's currently running,\n  // or NULL if no test is running.\n  const TestSuite* current_test_suite() const GTEST_LOCK_EXCLUDED_(mutex_);\n\n// Legacy API is still available but deprecated\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  const TestCase* current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_);\n#endif\n\n  // Returns the TestInfo object for the test that's currently running,\n  // or NULL if no test is running.\n  const TestInfo* current_test_info() const GTEST_LOCK_EXCLUDED_(mutex_);\n\n  // Returns the random seed used at the start of the current test run.\n  int random_seed() const;\n\n  // Returns the ParameterizedTestSuiteRegistry object used to keep track of\n  // value-parameterized tests and instantiate and register them.\n  //\n  // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.\n  internal::ParameterizedTestSuiteRegistry& parameterized_test_registry()\n      GTEST_LOCK_EXCLUDED_(mutex_);\n\n  // Gets the number of successful test suites.\n  int successful_test_suite_count() const;\n\n  // Gets the number of failed test suites.\n  int failed_test_suite_count() const;\n\n  // Gets the number of all test suites.\n  int total_test_suite_count() const;\n\n  // Gets the number of all test suites that contain at least one test\n  // that should run.\n  int test_suite_to_run_count() const;\n\n  //  Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  int successful_test_case_count() const;\n  int failed_test_case_count() const;\n  int total_test_case_count() const;\n  int test_case_to_run_count() const;\n#endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n  // Gets the number of successful tests.\n  int successful_test_count() const;\n\n  // Gets the number of skipped tests.\n  int skipped_test_count() const;\n\n  // Gets the number of failed tests.\n  int failed_test_count() const;\n\n  // Gets the number of disabled tests that will be reported in the XML report.\n  int reportable_disabled_test_count() const;\n\n  // Gets the number of disabled tests.\n  int disabled_test_count() const;\n\n  // Gets the number of tests to be printed in the XML report.\n  int reportable_test_count() const;\n\n  // Gets the number of all tests.\n  int total_test_count() const;\n\n  // Gets the number of tests that should run.\n  int test_to_run_count() const;\n\n  // Gets the time of the test program start, in ms from the start of the\n  // UNIX epoch.\n  TimeInMillis start_timestamp() const;\n\n  // Gets the elapsed time, in milliseconds.\n  TimeInMillis elapsed_time() const;\n\n  // Returns true if and only if the unit test passed (i.e. all test suites\n  // passed).\n  bool Passed() const;\n\n  // Returns true if and only if the unit test failed (i.e. some test suite\n  // failed or something outside of all tests failed).\n  bool Failed() const;\n\n  // Gets the i-th test suite among all the test suites. i can range from 0 to\n  // total_test_suite_count() - 1. If i is not in that range, returns NULL.\n  const TestSuite* GetTestSuite(int i) const;\n\n//  Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  const TestCase* GetTestCase(int i) const;\n#endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n  // Returns the TestResult containing information on test failures and\n  // properties logged outside of individual test suites.\n  const TestResult& ad_hoc_test_result() const;\n\n  // Returns the list of event listeners that can be used to track events\n  // inside Google Test.\n  TestEventListeners& listeners();\n\n private:\n  // Registers and returns a global test environment.  When a test\n  // program is run, all global test environments will be set-up in\n  // the order they were registered.  After all tests in the program\n  // have finished, all global test environments will be torn-down in\n  // the *reverse* order they were registered.\n  //\n  // The UnitTest object takes ownership of the given environment.\n  //\n  // This method can only be called from the main thread.\n  Environment* AddEnvironment(Environment* env);\n\n  // Adds a TestPartResult to the current TestResult object.  All\n  // Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc)\n  // eventually call this to report their results.  The user code\n  // should use the assertion macros instead of calling this directly.\n  void AddTestPartResult(TestPartResult::Type result_type,\n                         const char* file_name, int line_number,\n                         const std::string& message,\n                         const std::string& os_stack_trace)\n      GTEST_LOCK_EXCLUDED_(mutex_);\n\n  // Adds a TestProperty to the current TestResult object when invoked from\n  // inside a test, to current TestSuite's ad_hoc_test_result_ when invoked\n  // from SetUpTestSuite or TearDownTestSuite, or to the global property set\n  // when invoked elsewhere.  If the result already contains a property with\n  // the same key, the value will be updated.\n  void RecordProperty(const std::string& key, const std::string& value);\n\n  // Gets the i-th test suite among all the test suites. i can range from 0 to\n  // total_test_suite_count() - 1. If i is not in that range, returns NULL.\n  TestSuite* GetMutableTestSuite(int i);\n\n  // Accessors for the implementation object.\n  internal::UnitTestImpl* impl() { return impl_; }\n  const internal::UnitTestImpl* impl() const { return impl_; }\n\n  // These classes and functions are friends as they need to access private\n  // members of UnitTest.\n  friend class ScopedTrace;\n  friend class Test;\n  friend class internal::AssertHelper;\n  friend class internal::StreamingListenerTest;\n  friend class internal::UnitTestRecordPropertyTestHelper;\n  friend Environment* AddGlobalTestEnvironment(Environment* env);\n  friend std::set<std::string>* internal::GetIgnoredParameterizedTestSuites();\n  friend internal::UnitTestImpl* internal::GetUnitTestImpl();\n  friend void internal::ReportFailureInUnknownLocation(\n      TestPartResult::Type result_type, const std::string& message);\n\n  // Creates an empty UnitTest.\n  UnitTest();\n\n  // D'tor\n  virtual ~UnitTest();\n\n  // Pushes a trace defined by SCOPED_TRACE() on to the per-thread\n  // Google Test trace stack.\n  void PushGTestTrace(const internal::TraceInfo& trace)\n      GTEST_LOCK_EXCLUDED_(mutex_);\n\n  // Pops a trace from the per-thread Google Test trace stack.\n  void PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_);\n\n  // Protects mutable state in *impl_.  This is mutable as some const\n  // methods need to lock it too.\n  mutable internal::Mutex mutex_;\n\n  // Opaque implementation object.  This field is never changed once\n  // the object is constructed.  We don't mark it as const here, as\n  // doing so will cause a warning in the constructor of UnitTest.\n  // Mutable state in *impl_ is protected by mutex_.\n  internal::UnitTestImpl* impl_;\n\n  // We disallow copying UnitTest.\n  UnitTest(const UnitTest&) = delete;\n  UnitTest& operator=(const UnitTest&) = delete;\n};\n\n// A convenient wrapper for adding an environment for the test\n// program.\n//\n// You should call this before RUN_ALL_TESTS() is called, probably in\n// main().  If you use gtest_main, you need to call this before main()\n// starts for it to take effect.  For example, you can define a global\n// variable like this:\n//\n//   testing::Environment* const foo_env =\n//       testing::AddGlobalTestEnvironment(new FooEnvironment);\n//\n// However, we strongly recommend you to write your own main() and\n// call AddGlobalTestEnvironment() there, as relying on initialization\n// of global variables makes the code harder to read and may cause\n// problems when you register multiple environments from different\n// translation units and the environments have dependencies among them\n// (remember that the compiler doesn't guarantee the order in which\n// global variables from different translation units are initialized).\ninline Environment* AddGlobalTestEnvironment(Environment* env) {\n  return UnitTest::GetInstance()->AddEnvironment(env);\n}\n\n// Initializes Google Test.  This must be called before calling\n// RUN_ALL_TESTS().  In particular, it parses a command line for the\n// flags that Google Test recognizes.  Whenever a Google Test flag is\n// seen, it is removed from argv, and *argc is decremented.\n//\n// No value is returned.  Instead, the Google Test flag variables are\n// updated.\n//\n// Calling the function for the second time has no user-visible effect.\nGTEST_API_ void InitGoogleTest(int* argc, char** argv);\n\n// This overloaded version can be used in Windows programs compiled in\n// UNICODE mode.\nGTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv);\n\n// This overloaded version can be used on Arduino/embedded platforms where\n// there is no argc/argv.\nGTEST_API_ void InitGoogleTest();\n\nnamespace internal {\n\n// Separate the error generating code from the code path to reduce the stack\n// frame size of CmpHelperEQ. This helps reduce the overhead of some sanitizers\n// when calling EXPECT_* in a tight loop.\ntemplate <typename T1, typename T2>\nAssertionResult CmpHelperEQFailure(const char* lhs_expression,\n                                   const char* rhs_expression, const T1& lhs,\n                                   const T2& rhs) {\n  return EqFailure(lhs_expression, rhs_expression,\n                   FormatForComparisonFailureMessage(lhs, rhs),\n                   FormatForComparisonFailureMessage(rhs, lhs), false);\n}\n\n// This block of code defines operator==/!=\n// to block lexical scope lookup.\n// It prevents using invalid operator==/!= defined at namespace scope.\nstruct faketype {};\ninline bool operator==(faketype, faketype) { return true; }\ninline bool operator!=(faketype, faketype) { return false; }\n\n// The helper function for {ASSERT|EXPECT}_EQ.\ntemplate <typename T1, typename T2>\nAssertionResult CmpHelperEQ(const char* lhs_expression,\n                            const char* rhs_expression, const T1& lhs,\n                            const T2& rhs) {\n  if (lhs == rhs) {\n    return AssertionSuccess();\n  }\n\n  return CmpHelperEQFailure(lhs_expression, rhs_expression, lhs, rhs);\n}\n\nclass EqHelper {\n public:\n  // This templatized version is for the general case.\n  template <\n      typename T1, typename T2,\n      // Disable this overload for cases where one argument is a pointer\n      // and the other is the null pointer constant.\n      typename std::enable_if<!std::is_integral<T1>::value ||\n                              !std::is_pointer<T2>::value>::type* = nullptr>\n  static AssertionResult Compare(const char* lhs_expression,\n                                 const char* rhs_expression, const T1& lhs,\n                                 const T2& rhs) {\n    return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);\n  }\n\n  // With this overloaded version, we allow anonymous enums to be used\n  // in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous\n  // enums can be implicitly cast to BiggestInt.\n  //\n  // Even though its body looks the same as the above version, we\n  // cannot merge the two, as it will make anonymous enums unhappy.\n  static AssertionResult Compare(const char* lhs_expression,\n                                 const char* rhs_expression, BiggestInt lhs,\n                                 BiggestInt rhs) {\n    return CmpHelperEQ(lhs_expression, rhs_expression, lhs, rhs);\n  }\n\n  template <typename T>\n  static AssertionResult Compare(\n      const char* lhs_expression, const char* rhs_expression,\n      // Handle cases where '0' is used as a null pointer literal.\n      std::nullptr_t /* lhs */, T* rhs) {\n    // We already know that 'lhs' is a null pointer.\n    return CmpHelperEQ(lhs_expression, rhs_expression, static_cast<T*>(nullptr),\n                       rhs);\n  }\n};\n\n// Separate the error generating code from the code path to reduce the stack\n// frame size of CmpHelperOP. This helps reduce the overhead of some sanitizers\n// when calling EXPECT_OP in a tight loop.\ntemplate <typename T1, typename T2>\nAssertionResult CmpHelperOpFailure(const char* expr1, const char* expr2,\n                                   const T1& val1, const T2& val2,\n                                   const char* op) {\n  return AssertionFailure()\n         << \"Expected: (\" << expr1 << \") \" << op << \" (\" << expr2\n         << \"), actual: \" << FormatForComparisonFailureMessage(val1, val2)\n         << \" vs \" << FormatForComparisonFailureMessage(val2, val1);\n}\n\n// A macro for implementing the helper functions needed to implement\n// ASSERT_?? and EXPECT_??.  It is here just to avoid copy-and-paste\n// of similar code.\n//\n// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.\n\n#define GTEST_IMPL_CMP_HELPER_(op_name, op)                                \\\n  template <typename T1, typename T2>                                      \\\n  AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \\\n                                     const T1& val1, const T2& val2) {     \\\n    if (val1 op val2) {                                                    \\\n      return AssertionSuccess();                                           \\\n    } else {                                                               \\\n      return CmpHelperOpFailure(expr1, expr2, val1, val2, #op);            \\\n    }                                                                      \\\n  }\n\n// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.\n\n// Implements the helper function for {ASSERT|EXPECT}_NE\nGTEST_IMPL_CMP_HELPER_(NE, !=)\n// Implements the helper function for {ASSERT|EXPECT}_LE\nGTEST_IMPL_CMP_HELPER_(LE, <=)\n// Implements the helper function for {ASSERT|EXPECT}_LT\nGTEST_IMPL_CMP_HELPER_(LT, <)\n// Implements the helper function for {ASSERT|EXPECT}_GE\nGTEST_IMPL_CMP_HELPER_(GE, >=)\n// Implements the helper function for {ASSERT|EXPECT}_GT\nGTEST_IMPL_CMP_HELPER_(GT, >)\n\n#undef GTEST_IMPL_CMP_HELPER_\n\n// The helper function for {ASSERT|EXPECT}_STREQ.\n//\n// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.\nGTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,\n                                          const char* s2_expression,\n                                          const char* s1, const char* s2);\n\n// The helper function for {ASSERT|EXPECT}_STRCASEEQ.\n//\n// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.\nGTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* s1_expression,\n                                              const char* s2_expression,\n                                              const char* s1, const char* s2);\n\n// The helper function for {ASSERT|EXPECT}_STRNE.\n//\n// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.\nGTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,\n                                          const char* s2_expression,\n                                          const char* s1, const char* s2);\n\n// The helper function for {ASSERT|EXPECT}_STRCASENE.\n//\n// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.\nGTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression,\n                                              const char* s2_expression,\n                                              const char* s1, const char* s2);\n\n// Helper function for *_STREQ on wide strings.\n//\n// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.\nGTEST_API_ AssertionResult CmpHelperSTREQ(const char* s1_expression,\n                                          const char* s2_expression,\n                                          const wchar_t* s1, const wchar_t* s2);\n\n// Helper function for *_STRNE on wide strings.\n//\n// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.\nGTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,\n                                          const char* s2_expression,\n                                          const wchar_t* s1, const wchar_t* s2);\n\n}  // namespace internal\n\n// IsSubstring() and IsNotSubstring() are intended to be used as the\n// first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by\n// themselves.  They check whether needle is a substring of haystack\n// (NULL is considered a substring of itself only), and return an\n// appropriate error message when they fail.\n//\n// The {needle,haystack}_expr arguments are the stringified\n// expressions that generated the two real arguments.\nGTEST_API_ AssertionResult IsSubstring(const char* needle_expr,\n                                       const char* haystack_expr,\n                                       const char* needle,\n                                       const char* haystack);\nGTEST_API_ AssertionResult IsSubstring(const char* needle_expr,\n                                       const char* haystack_expr,\n                                       const wchar_t* needle,\n                                       const wchar_t* haystack);\nGTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr,\n                                          const char* haystack_expr,\n                                          const char* needle,\n                                          const char* haystack);\nGTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr,\n                                          const char* haystack_expr,\n                                          const wchar_t* needle,\n                                          const wchar_t* haystack);\nGTEST_API_ AssertionResult IsSubstring(const char* needle_expr,\n                                       const char* haystack_expr,\n                                       const ::std::string& needle,\n                                       const ::std::string& haystack);\nGTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr,\n                                          const char* haystack_expr,\n                                          const ::std::string& needle,\n                                          const ::std::string& haystack);\n\n#if GTEST_HAS_STD_WSTRING\nGTEST_API_ AssertionResult IsSubstring(const char* needle_expr,\n                                       const char* haystack_expr,\n                                       const ::std::wstring& needle,\n                                       const ::std::wstring& haystack);\nGTEST_API_ AssertionResult IsNotSubstring(const char* needle_expr,\n                                          const char* haystack_expr,\n                                          const ::std::wstring& needle,\n                                          const ::std::wstring& haystack);\n#endif  // GTEST_HAS_STD_WSTRING\n\nnamespace internal {\n\n// Helper template function for comparing floating-points.\n//\n// Template parameter:\n//\n//   RawType: the raw floating-point type (either float or double)\n//\n// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.\ntemplate <typename RawType>\nAssertionResult CmpHelperFloatingPointEQ(const char* lhs_expression,\n                                         const char* rhs_expression,\n                                         RawType lhs_value, RawType rhs_value) {\n  const FloatingPoint<RawType> lhs(lhs_value), rhs(rhs_value);\n\n  if (lhs.AlmostEquals(rhs)) {\n    return AssertionSuccess();\n  }\n\n  ::std::stringstream lhs_ss;\n  lhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)\n         << lhs_value;\n\n  ::std::stringstream rhs_ss;\n  rhs_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)\n         << rhs_value;\n\n  return EqFailure(lhs_expression, rhs_expression,\n                   StringStreamToString(&lhs_ss), StringStreamToString(&rhs_ss),\n                   false);\n}\n\n// Helper function for implementing ASSERT_NEAR.\n//\n// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.\nGTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1,\n                                                const char* expr2,\n                                                const char* abs_error_expr,\n                                                double val1, double val2,\n                                                double abs_error);\n\n// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.\n// A class that enables one to stream messages to assertion macros\nclass GTEST_API_ AssertHelper {\n public:\n  // Constructor.\n  AssertHelper(TestPartResult::Type type, const char* file, int line,\n               const char* message);\n  ~AssertHelper();\n\n  // Message assignment is a semantic trick to enable assertion\n  // streaming; see the GTEST_MESSAGE_ macro below.\n  void operator=(const Message& message) const;\n\n private:\n  // We put our data in a struct so that the size of the AssertHelper class can\n  // be as small as possible.  This is important because gcc is incapable of\n  // re-using stack space even for temporary variables, so every EXPECT_EQ\n  // reserves stack space for another AssertHelper.\n  struct AssertHelperData {\n    AssertHelperData(TestPartResult::Type t, const char* srcfile, int line_num,\n                     const char* msg)\n        : type(t), file(srcfile), line(line_num), message(msg) {}\n\n    TestPartResult::Type const type;\n    const char* const file;\n    int const line;\n    std::string const message;\n\n   private:\n    AssertHelperData(const AssertHelperData&) = delete;\n    AssertHelperData& operator=(const AssertHelperData&) = delete;\n  };\n\n  AssertHelperData* const data_;\n\n  AssertHelper(const AssertHelper&) = delete;\n  AssertHelper& operator=(const AssertHelper&) = delete;\n};\n\n}  // namespace internal\n\n// The pure interface class that all value-parameterized tests inherit from.\n// A value-parameterized class must inherit from both ::testing::Test and\n// ::testing::WithParamInterface. In most cases that just means inheriting\n// from ::testing::TestWithParam, but more complicated test hierarchies\n// may need to inherit from Test and WithParamInterface at different levels.\n//\n// This interface has support for accessing the test parameter value via\n// the GetParam() method.\n//\n// Use it with one of the parameter generator defining functions, like Range(),\n// Values(), ValuesIn(), Bool(), and Combine().\n//\n// class FooTest : public ::testing::TestWithParam<int> {\n//  protected:\n//   FooTest() {\n//     // Can use GetParam() here.\n//   }\n//   ~FooTest() override {\n//     // Can use GetParam() here.\n//   }\n//   void SetUp() override {\n//     // Can use GetParam() here.\n//   }\n//   void TearDown override {\n//     // Can use GetParam() here.\n//   }\n// };\n// TEST_P(FooTest, DoesBar) {\n//   // Can use GetParam() method here.\n//   Foo foo;\n//   ASSERT_TRUE(foo.DoesBar(GetParam()));\n// }\n// INSTANTIATE_TEST_SUITE_P(OneToTenRange, FooTest, ::testing::Range(1, 10));\n\ntemplate <typename T>\nclass WithParamInterface {\n public:\n  typedef T ParamType;\n  virtual ~WithParamInterface() {}\n\n  // The current parameter value. Is also available in the test fixture's\n  // constructor.\n  static const ParamType& GetParam() {\n    GTEST_CHECK_(parameter_ != nullptr)\n        << \"GetParam() can only be called inside a value-parameterized test \"\n        << \"-- did you intend to write TEST_P instead of TEST_F?\";\n    return *parameter_;\n  }\n\n private:\n  // Sets parameter value. The caller is responsible for making sure the value\n  // remains alive and unchanged throughout the current test.\n  static void SetParam(const ParamType* parameter) { parameter_ = parameter; }\n\n  // Static value used for accessing parameter during a test lifetime.\n  static const ParamType* parameter_;\n\n  // TestClass must be a subclass of WithParamInterface<T> and Test.\n  template <class TestClass>\n  friend class internal::ParameterizedTestFactory;\n};\n\ntemplate <typename T>\nconst T* WithParamInterface<T>::parameter_ = nullptr;\n\n// Most value-parameterized classes can ignore the existence of\n// WithParamInterface, and can just inherit from ::testing::TestWithParam.\n\ntemplate <typename T>\nclass TestWithParam : public Test, public WithParamInterface<T> {};\n\n// Macros for indicating success/failure in test code.\n\n// Skips test in runtime.\n// Skipping test aborts current function.\n// Skipped tests are neither successful nor failed.\n#define GTEST_SKIP() GTEST_SKIP_(\"\")\n\n// ADD_FAILURE unconditionally adds a failure to the current test.\n// SUCCEED generates a success - it doesn't automatically make the\n// current test successful, as a test is only successful when it has\n// no failure.\n//\n// EXPECT_* verifies that a certain condition is satisfied.  If not,\n// it behaves like ADD_FAILURE.  In particular:\n//\n//   EXPECT_TRUE  verifies that a Boolean condition is true.\n//   EXPECT_FALSE verifies that a Boolean condition is false.\n//\n// FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except\n// that they will also abort the current function on failure.  People\n// usually want the fail-fast behavior of FAIL and ASSERT_*, but those\n// writing data-driven tests often find themselves using ADD_FAILURE\n// and EXPECT_* more.\n\n// Generates a nonfatal failure with a generic message.\n#define ADD_FAILURE() GTEST_NONFATAL_FAILURE_(\"Failed\")\n\n// Generates a nonfatal failure at the given source file location with\n// a generic message.\n#define ADD_FAILURE_AT(file, line)        \\\n  GTEST_MESSAGE_AT_(file, line, \"Failed\", \\\n                    ::testing::TestPartResult::kNonFatalFailure)\n\n// Generates a fatal failure with a generic message.\n#define GTEST_FAIL() GTEST_FATAL_FAILURE_(\"Failed\")\n\n// Like GTEST_FAIL(), but at the given source file location.\n#define GTEST_FAIL_AT(file, line)         \\\n  GTEST_MESSAGE_AT_(file, line, \"Failed\", \\\n                    ::testing::TestPartResult::kFatalFailure)\n\n// Define this macro to 1 to omit the definition of FAIL(), which is a\n// generic name and clashes with some other libraries.\n#if !GTEST_DONT_DEFINE_FAIL\n#define FAIL() GTEST_FAIL()\n#endif\n\n// Generates a success with a generic message.\n#define GTEST_SUCCEED() GTEST_SUCCESS_(\"Succeeded\")\n\n// Define this macro to 1 to omit the definition of SUCCEED(), which\n// is a generic name and clashes with some other libraries.\n#if !GTEST_DONT_DEFINE_SUCCEED\n#define SUCCEED() GTEST_SUCCEED()\n#endif\n\n// Macros for testing exceptions.\n//\n//    * {ASSERT|EXPECT}_THROW(statement, expected_exception):\n//         Tests that the statement throws the expected exception.\n//    * {ASSERT|EXPECT}_NO_THROW(statement):\n//         Tests that the statement doesn't throw any exception.\n//    * {ASSERT|EXPECT}_ANY_THROW(statement):\n//         Tests that the statement throws an exception.\n\n#define EXPECT_THROW(statement, expected_exception) \\\n  GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_)\n#define EXPECT_NO_THROW(statement) \\\n  GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_)\n#define EXPECT_ANY_THROW(statement) \\\n  GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_)\n#define ASSERT_THROW(statement, expected_exception) \\\n  GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_)\n#define ASSERT_NO_THROW(statement) \\\n  GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_)\n#define ASSERT_ANY_THROW(statement) \\\n  GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_)\n\n// Boolean assertions. Condition can be either a Boolean expression or an\n// AssertionResult. For more information on how to use AssertionResult with\n// these macros see comments on that class.\n#define GTEST_EXPECT_TRUE(condition)                      \\\n  GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \\\n                      GTEST_NONFATAL_FAILURE_)\n#define GTEST_EXPECT_FALSE(condition)                        \\\n  GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \\\n                      GTEST_NONFATAL_FAILURE_)\n#define GTEST_ASSERT_TRUE(condition) \\\n  GTEST_TEST_BOOLEAN_(condition, #condition, false, true, GTEST_FATAL_FAILURE_)\n#define GTEST_ASSERT_FALSE(condition)                        \\\n  GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \\\n                      GTEST_FATAL_FAILURE_)\n\n// Define these macros to 1 to omit the definition of the corresponding\n// EXPECT or ASSERT, which clashes with some users' own code.\n\n#if !GTEST_DONT_DEFINE_EXPECT_TRUE\n#define EXPECT_TRUE(condition) GTEST_EXPECT_TRUE(condition)\n#endif\n\n#if !GTEST_DONT_DEFINE_EXPECT_FALSE\n#define EXPECT_FALSE(condition) GTEST_EXPECT_FALSE(condition)\n#endif\n\n#if !GTEST_DONT_DEFINE_ASSERT_TRUE\n#define ASSERT_TRUE(condition) GTEST_ASSERT_TRUE(condition)\n#endif\n\n#if !GTEST_DONT_DEFINE_ASSERT_FALSE\n#define ASSERT_FALSE(condition) GTEST_ASSERT_FALSE(condition)\n#endif\n\n// Macros for testing equalities and inequalities.\n//\n//    * {ASSERT|EXPECT}_EQ(v1, v2): Tests that v1 == v2\n//    * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2\n//    * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2\n//    * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2\n//    * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2\n//    * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2\n//\n// When they are not, Google Test prints both the tested expressions and\n// their actual values.  The values must be compatible built-in types,\n// or you will get a compiler error.  By \"compatible\" we mean that the\n// values can be compared by the respective operator.\n//\n// Note:\n//\n//   1. It is possible to make a user-defined type work with\n//   {ASSERT|EXPECT}_??(), but that requires overloading the\n//   comparison operators and is thus discouraged by the Google C++\n//   Usage Guide.  Therefore, you are advised to use the\n//   {ASSERT|EXPECT}_TRUE() macro to assert that two objects are\n//   equal.\n//\n//   2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on\n//   pointers (in particular, C strings).  Therefore, if you use it\n//   with two C strings, you are testing how their locations in memory\n//   are related, not how their content is related.  To compare two C\n//   strings by content, use {ASSERT|EXPECT}_STR*().\n//\n//   3. {ASSERT|EXPECT}_EQ(v1, v2) is preferred to\n//   {ASSERT|EXPECT}_TRUE(v1 == v2), as the former tells you\n//   what the actual value is when it fails, and similarly for the\n//   other comparisons.\n//\n//   4. Do not depend on the order in which {ASSERT|EXPECT}_??()\n//   evaluate their arguments, which is undefined.\n//\n//   5. These macros evaluate their arguments exactly once.\n//\n// Examples:\n//\n//   EXPECT_NE(Foo(), 5);\n//   EXPECT_EQ(a_pointer, NULL);\n//   ASSERT_LT(i, array_size);\n//   ASSERT_GT(records.size(), 0) << \"There is no record left.\";\n\n#define EXPECT_EQ(val1, val2) \\\n  EXPECT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2)\n#define EXPECT_NE(val1, val2) \\\n  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)\n#define EXPECT_LE(val1, val2) \\\n  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)\n#define EXPECT_LT(val1, val2) \\\n  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)\n#define EXPECT_GE(val1, val2) \\\n  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)\n#define EXPECT_GT(val1, val2) \\\n  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)\n\n#define GTEST_ASSERT_EQ(val1, val2) \\\n  ASSERT_PRED_FORMAT2(::testing::internal::EqHelper::Compare, val1, val2)\n#define GTEST_ASSERT_NE(val1, val2) \\\n  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)\n#define GTEST_ASSERT_LE(val1, val2) \\\n  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)\n#define GTEST_ASSERT_LT(val1, val2) \\\n  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)\n#define GTEST_ASSERT_GE(val1, val2) \\\n  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)\n#define GTEST_ASSERT_GT(val1, val2) \\\n  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)\n\n// Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of\n// ASSERT_XY(), which clashes with some users' own code.\n\n#if !GTEST_DONT_DEFINE_ASSERT_EQ\n#define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2)\n#endif\n\n#if !GTEST_DONT_DEFINE_ASSERT_NE\n#define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2)\n#endif\n\n#if !GTEST_DONT_DEFINE_ASSERT_LE\n#define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2)\n#endif\n\n#if !GTEST_DONT_DEFINE_ASSERT_LT\n#define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2)\n#endif\n\n#if !GTEST_DONT_DEFINE_ASSERT_GE\n#define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2)\n#endif\n\n#if !GTEST_DONT_DEFINE_ASSERT_GT\n#define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2)\n#endif\n\n// C-string Comparisons.  All tests treat NULL and any non-NULL string\n// as different.  Two NULLs are equal.\n//\n//    * {ASSERT|EXPECT}_STREQ(s1, s2):     Tests that s1 == s2\n//    * {ASSERT|EXPECT}_STRNE(s1, s2):     Tests that s1 != s2\n//    * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case\n//    * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case\n//\n// For wide or narrow string objects, you can use the\n// {ASSERT|EXPECT}_??() macros.\n//\n// Don't depend on the order in which the arguments are evaluated,\n// which is undefined.\n//\n// These macros evaluate their arguments exactly once.\n\n#define EXPECT_STREQ(s1, s2) \\\n  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)\n#define EXPECT_STRNE(s1, s2) \\\n  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)\n#define EXPECT_STRCASEEQ(s1, s2) \\\n  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)\n#define EXPECT_STRCASENE(s1, s2) \\\n  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)\n\n#define ASSERT_STREQ(s1, s2) \\\n  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, s1, s2)\n#define ASSERT_STRNE(s1, s2) \\\n  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)\n#define ASSERT_STRCASEEQ(s1, s2) \\\n  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, s1, s2)\n#define ASSERT_STRCASENE(s1, s2) \\\n  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)\n\n// Macros for comparing floating-point numbers.\n//\n//    * {ASSERT|EXPECT}_FLOAT_EQ(val1, val2):\n//         Tests that two float values are almost equal.\n//    * {ASSERT|EXPECT}_DOUBLE_EQ(val1, val2):\n//         Tests that two double values are almost equal.\n//    * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error):\n//         Tests that v1 and v2 are within the given distance to each other.\n//\n// Google Test uses ULP-based comparison to automatically pick a default\n// error bound that is appropriate for the operands.  See the\n// FloatingPoint template class in gtest-internal.h if you are\n// interested in the implementation details.\n\n#define EXPECT_FLOAT_EQ(val1, val2)                                         \\\n  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \\\n                      val1, val2)\n\n#define EXPECT_DOUBLE_EQ(val1, val2)                                         \\\n  EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \\\n                      val1, val2)\n\n#define ASSERT_FLOAT_EQ(val1, val2)                                         \\\n  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \\\n                      val1, val2)\n\n#define ASSERT_DOUBLE_EQ(val1, val2)                                         \\\n  ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \\\n                      val1, val2)\n\n#define EXPECT_NEAR(val1, val2, abs_error)                                   \\\n  EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, val1, val2, \\\n                      abs_error)\n\n#define ASSERT_NEAR(val1, val2, abs_error)                                   \\\n  ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, val1, val2, \\\n                      abs_error)\n\n// These predicate format functions work on floating-point values, and\n// can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g.\n//\n//   EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0);\n\n// Asserts that val1 is less than, or almost equal to, val2.  Fails\n// otherwise.  In particular, it fails if either val1 or val2 is NaN.\nGTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2,\n                                   float val1, float val2);\nGTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,\n                                    double val1, double val2);\n\n#if GTEST_OS_WINDOWS\n\n// Macros that test for HRESULT failure and success, these are only useful\n// on Windows, and rely on Windows SDK macros and APIs to compile.\n//\n//    * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr)\n//\n// When expr unexpectedly fails or succeeds, Google Test prints the\n// expected result and the actual result with both a human-readable\n// string representation of the error, if available, as well as the\n// hex result code.\n#define EXPECT_HRESULT_SUCCEEDED(expr) \\\n  EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))\n\n#define ASSERT_HRESULT_SUCCEEDED(expr) \\\n  ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))\n\n#define EXPECT_HRESULT_FAILED(expr) \\\n  EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))\n\n#define ASSERT_HRESULT_FAILED(expr) \\\n  ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))\n\n#endif  // GTEST_OS_WINDOWS\n\n// Macros that execute statement and check that it doesn't generate new fatal\n// failures in the current thread.\n//\n//   * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement);\n//\n// Examples:\n//\n//   EXPECT_NO_FATAL_FAILURE(Process());\n//   ASSERT_NO_FATAL_FAILURE(Process()) << \"Process() failed\";\n//\n#define ASSERT_NO_FATAL_FAILURE(statement) \\\n  GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_)\n#define EXPECT_NO_FATAL_FAILURE(statement) \\\n  GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_)\n\n// Causes a trace (including the given source file path and line number,\n// and the given message) to be included in every test failure message generated\n// by code in the scope of the lifetime of an instance of this class. The effect\n// is undone with the destruction of the instance.\n//\n// The message argument can be anything streamable to std::ostream.\n//\n// Example:\n//   testing::ScopedTrace trace(\"file.cc\", 123, \"message\");\n//\nclass GTEST_API_ ScopedTrace {\n public:\n  // The c'tor pushes the given source file location and message onto\n  // a trace stack maintained by Google Test.\n\n  // Template version. Uses Message() to convert the values into strings.\n  // Slow, but flexible.\n  template <typename T>\n  ScopedTrace(const char* file, int line, const T& message) {\n    PushTrace(file, line, (Message() << message).GetString());\n  }\n\n  // Optimize for some known types.\n  ScopedTrace(const char* file, int line, const char* message) {\n    PushTrace(file, line, message ? message : \"(null)\");\n  }\n\n  ScopedTrace(const char* file, int line, const std::string& message) {\n    PushTrace(file, line, message);\n  }\n\n  // The d'tor pops the info pushed by the c'tor.\n  //\n  // Note that the d'tor is not virtual in order to be efficient.\n  // Don't inherit from ScopedTrace!\n  ~ScopedTrace();\n\n private:\n  void PushTrace(const char* file, int line, std::string message);\n\n  ScopedTrace(const ScopedTrace&) = delete;\n  ScopedTrace& operator=(const ScopedTrace&) = delete;\n} GTEST_ATTRIBUTE_UNUSED_;  // A ScopedTrace object does its job in its\n                            // c'tor and d'tor.  Therefore it doesn't\n                            // need to be used otherwise.\n\n// Causes a trace (including the source file path, the current line\n// number, and the given message) to be included in every test failure\n// message generated by code in the current scope.  The effect is\n// undone when the control leaves the current scope.\n//\n// The message argument can be anything streamable to std::ostream.\n//\n// In the implementation, we include the current line number as part\n// of the dummy variable name, thus allowing multiple SCOPED_TRACE()s\n// to appear in the same block - as long as they are on different\n// lines.\n//\n// Assuming that each thread maintains its own stack of traces.\n// Therefore, a SCOPED_TRACE() would (correctly) only affect the\n// assertions in its own thread.\n#define SCOPED_TRACE(message)                                         \\\n  ::testing::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)( \\\n      __FILE__, __LINE__, (message))\n\n// Compile-time assertion for type equality.\n// StaticAssertTypeEq<type1, type2>() compiles if and only if type1 and type2\n// are the same type.  The value it returns is not interesting.\n//\n// Instead of making StaticAssertTypeEq a class template, we make it a\n// function template that invokes a helper class template.  This\n// prevents a user from misusing StaticAssertTypeEq<T1, T2> by\n// defining objects of that type.\n//\n// CAVEAT:\n//\n// When used inside a method of a class template,\n// StaticAssertTypeEq<T1, T2>() is effective ONLY IF the method is\n// instantiated.  For example, given:\n//\n//   template <typename T> class Foo {\n//    public:\n//     void Bar() { testing::StaticAssertTypeEq<int, T>(); }\n//   };\n//\n// the code:\n//\n//   void Test1() { Foo<bool> foo; }\n//\n// will NOT generate a compiler error, as Foo<bool>::Bar() is never\n// actually instantiated.  Instead, you need:\n//\n//   void Test2() { Foo<bool> foo; foo.Bar(); }\n//\n// to cause a compiler error.\ntemplate <typename T1, typename T2>\nconstexpr bool StaticAssertTypeEq() noexcept {\n  static_assert(std::is_same<T1, T2>::value, \"T1 and T2 are not the same type\");\n  return true;\n}\n\n// Defines a test.\n//\n// The first parameter is the name of the test suite, and the second\n// parameter is the name of the test within the test suite.\n//\n// The convention is to end the test suite name with \"Test\".  For\n// example, a test suite for the Foo class can be named FooTest.\n//\n// Test code should appear between braces after an invocation of\n// this macro.  Example:\n//\n//   TEST(FooTest, InitializesCorrectly) {\n//     Foo foo;\n//     EXPECT_TRUE(foo.StatusIsOK());\n//   }\n\n// Note that we call GetTestTypeId() instead of GetTypeId<\n// ::testing::Test>() here to get the type ID of testing::Test.  This\n// is to work around a suspected linker bug when using Google Test as\n// a framework on Mac OS X.  The bug causes GetTypeId<\n// ::testing::Test>() to return different values depending on whether\n// the call is from the Google Test framework itself or from user test\n// code.  GetTestTypeId() is guaranteed to always return the same\n// value, as it always calls GetTypeId<>() from the Google Test\n// framework.\n#define GTEST_TEST(test_suite_name, test_name)             \\\n  GTEST_TEST_(test_suite_name, test_name, ::testing::Test, \\\n              ::testing::internal::GetTestTypeId())\n\n// Define this macro to 1 to omit the definition of TEST(), which\n// is a generic name and clashes with some other libraries.\n#if !GTEST_DONT_DEFINE_TEST\n#define TEST(test_suite_name, test_name) GTEST_TEST(test_suite_name, test_name)\n#endif\n\n// Defines a test that uses a test fixture.\n//\n// The first parameter is the name of the test fixture class, which\n// also doubles as the test suite name.  The second parameter is the\n// name of the test within the test suite.\n//\n// A test fixture class must be declared earlier.  The user should put\n// the test code between braces after using this macro.  Example:\n//\n//   class FooTest : public testing::Test {\n//    protected:\n//     void SetUp() override { b_.AddElement(3); }\n//\n//     Foo a_;\n//     Foo b_;\n//   };\n//\n//   TEST_F(FooTest, InitializesCorrectly) {\n//     EXPECT_TRUE(a_.StatusIsOK());\n//   }\n//\n//   TEST_F(FooTest, ReturnsElementCountCorrectly) {\n//     EXPECT_EQ(a_.size(), 0);\n//     EXPECT_EQ(b_.size(), 1);\n//   }\n#define GTEST_TEST_F(test_fixture, test_name)        \\\n  GTEST_TEST_(test_fixture, test_name, test_fixture, \\\n              ::testing::internal::GetTypeId<test_fixture>())\n#if !GTEST_DONT_DEFINE_TEST_F\n#define TEST_F(test_fixture, test_name) GTEST_TEST_F(test_fixture, test_name)\n#endif\n\n// Returns a path to temporary directory.\n// Tries to determine an appropriate directory for the platform.\nGTEST_API_ std::string TempDir();\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n// Dynamically registers a test with the framework.\n//\n// This is an advanced API only to be used when the `TEST` macros are\n// insufficient. The macros should be preferred when possible, as they avoid\n// most of the complexity of calling this function.\n//\n// The `factory` argument is a factory callable (move-constructible) object or\n// function pointer that creates a new instance of the Test object. It\n// handles ownership to the caller. The signature of the callable is\n// `Fixture*()`, where `Fixture` is the test fixture class for the test. All\n// tests registered with the same `test_suite_name` must return the same\n// fixture type. This is checked at runtime.\n//\n// The framework will infer the fixture class from the factory and will call\n// the `SetUpTestSuite` and `TearDownTestSuite` for it.\n//\n// Must be called before `RUN_ALL_TESTS()` is invoked, otherwise behavior is\n// undefined.\n//\n// Use case example:\n//\n// class MyFixture : public ::testing::Test {\n//  public:\n//   // All of these optional, just like in regular macro usage.\n//   static void SetUpTestSuite() { ... }\n//   static void TearDownTestSuite() { ... }\n//   void SetUp() override { ... }\n//   void TearDown() override { ... }\n// };\n//\n// class MyTest : public MyFixture {\n//  public:\n//   explicit MyTest(int data) : data_(data) {}\n//   void TestBody() override { ... }\n//\n//  private:\n//   int data_;\n// };\n//\n// void RegisterMyTests(const std::vector<int>& values) {\n//   for (int v : values) {\n//     ::testing::RegisterTest(\n//         \"MyFixture\", (\"Test\" + std::to_string(v)).c_str(), nullptr,\n//         std::to_string(v).c_str(),\n//         __FILE__, __LINE__,\n//         // Important to use the fixture type as the return type here.\n//         [=]() -> MyFixture* { return new MyTest(v); });\n//   }\n// }\n// ...\n// int main(int argc, char** argv) {\n//   ::testing::InitGoogleTest(&argc, argv);\n//   std::vector<int> values_to_test = LoadValuesFromConfig();\n//   RegisterMyTests(values_to_test);\n//   ...\n//   return RUN_ALL_TESTS();\n// }\n//\ntemplate <int&... ExplicitParameterBarrier, typename Factory>\nTestInfo* RegisterTest(const char* test_suite_name, const char* test_name,\n                       const char* type_param, const char* value_param,\n                       const char* file, int line, Factory factory) {\n  using TestT = typename std::remove_pointer<decltype(factory())>::type;\n\n  class FactoryImpl : public internal::TestFactoryBase {\n   public:\n    explicit FactoryImpl(Factory f) : factory_(std::move(f)) {}\n    Test* CreateTest() override { return factory_(); }\n\n   private:\n    Factory factory_;\n  };\n\n  return internal::MakeAndRegisterTestInfo(\n      test_suite_name, test_name, type_param, value_param,\n      internal::CodeLocation(file, line), internal::GetTypeId<TestT>(),\n      internal::SuiteApiResolver<TestT>::GetSetUpCaseOrSuite(file, line),\n      internal::SuiteApiResolver<TestT>::GetTearDownCaseOrSuite(file, line),\n      new FactoryImpl{std::move(factory)});\n}\n\n}  // namespace testing\n\n// Use this function in main() to run all tests.  It returns 0 if all\n// tests are successful, or 1 otherwise.\n//\n// RUN_ALL_TESTS() should be invoked after the command line has been\n// parsed by InitGoogleTest().\n//\n// This function was formerly a macro; thus, it is in the global\n// namespace and has an all-caps name.\nint RUN_ALL_TESTS() GTEST_MUST_USE_RESULT_;\n\ninline int RUN_ALL_TESTS() { return ::testing::UnitTest::GetInstance()->Run(); }\n\nGTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251\n\n#endif  // GOOGLETEST_INCLUDE_GTEST_GTEST_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/include/gtest/gtest_pred_impl.h",
    "content": "// Copyright 2006, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Implements a family of generic predicate assertion macros.\n\n// IWYU pragma: private, include \"gtest/gtest.h\"\n// IWYU pragma: friend gtest/.*\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_\n#define GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_\n\n#include \"gtest/gtest-assertion-result.h\"\n#include \"gtest/internal/gtest-internal.h\"\n#include \"gtest/internal/gtest-port.h\"\n\nnamespace testing {\n\n// This header implements a family of generic predicate assertion\n// macros:\n//\n//   ASSERT_PRED_FORMAT1(pred_format, v1)\n//   ASSERT_PRED_FORMAT2(pred_format, v1, v2)\n//   ...\n//\n// where pred_format is a function or functor that takes n (in the\n// case of ASSERT_PRED_FORMATn) values and their source expression\n// text, and returns a testing::AssertionResult.  See the definition\n// of ASSERT_EQ in gtest.h for an example.\n//\n// If you don't care about formatting, you can use the more\n// restrictive version:\n//\n//   ASSERT_PRED1(pred, v1)\n//   ASSERT_PRED2(pred, v1, v2)\n//   ...\n//\n// where pred is an n-ary function or functor that returns bool,\n// and the values v1, v2, ..., must support the << operator for\n// streaming to std::ostream.\n//\n// We also define the EXPECT_* variations.\n//\n// For now we only support predicates whose arity is at most 5.\n// Please email googletestframework@googlegroups.com if you need\n// support for higher arities.\n\n// GTEST_ASSERT_ is the basic statement to which all of the assertions\n// in this file reduce.  Don't use this in your code.\n\n#define GTEST_ASSERT_(expression, on_failure)                   \\\n  GTEST_AMBIGUOUS_ELSE_BLOCKER_                                 \\\n  if (const ::testing::AssertionResult gtest_ar = (expression)) \\\n    ;                                                           \\\n  else                                                          \\\n    on_failure(gtest_ar.failure_message())\n\n// Helper function for implementing {EXPECT|ASSERT}_PRED1.  Don't use\n// this in your code.\ntemplate <typename Pred, typename T1>\nAssertionResult AssertPred1Helper(const char* pred_text, const char* e1,\n                                  Pred pred, const T1& v1) {\n  if (pred(v1)) return AssertionSuccess();\n\n  return AssertionFailure()\n         << pred_text << \"(\" << e1 << \") evaluates to false, where\"\n         << \"\\n\"\n         << e1 << \" evaluates to \" << ::testing::PrintToString(v1);\n}\n\n// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT1.\n// Don't use this in your code.\n#define GTEST_PRED_FORMAT1_(pred_format, v1, on_failure) \\\n  GTEST_ASSERT_(pred_format(#v1, v1), on_failure)\n\n// Internal macro for implementing {EXPECT|ASSERT}_PRED1.  Don't use\n// this in your code.\n#define GTEST_PRED1_(pred, v1, on_failure) \\\n  GTEST_ASSERT_(::testing::AssertPred1Helper(#pred, #v1, pred, v1), on_failure)\n\n// Unary predicate assertion macros.\n#define EXPECT_PRED_FORMAT1(pred_format, v1) \\\n  GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_NONFATAL_FAILURE_)\n#define EXPECT_PRED1(pred, v1) GTEST_PRED1_(pred, v1, GTEST_NONFATAL_FAILURE_)\n#define ASSERT_PRED_FORMAT1(pred_format, v1) \\\n  GTEST_PRED_FORMAT1_(pred_format, v1, GTEST_FATAL_FAILURE_)\n#define ASSERT_PRED1(pred, v1) GTEST_PRED1_(pred, v1, GTEST_FATAL_FAILURE_)\n\n// Helper function for implementing {EXPECT|ASSERT}_PRED2.  Don't use\n// this in your code.\ntemplate <typename Pred, typename T1, typename T2>\nAssertionResult AssertPred2Helper(const char* pred_text, const char* e1,\n                                  const char* e2, Pred pred, const T1& v1,\n                                  const T2& v2) {\n  if (pred(v1, v2)) return AssertionSuccess();\n\n  return AssertionFailure()\n         << pred_text << \"(\" << e1 << \", \" << e2\n         << \") evaluates to false, where\"\n         << \"\\n\"\n         << e1 << \" evaluates to \" << ::testing::PrintToString(v1) << \"\\n\"\n         << e2 << \" evaluates to \" << ::testing::PrintToString(v2);\n}\n\n// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT2.\n// Don't use this in your code.\n#define GTEST_PRED_FORMAT2_(pred_format, v1, v2, on_failure) \\\n  GTEST_ASSERT_(pred_format(#v1, #v2, v1, v2), on_failure)\n\n// Internal macro for implementing {EXPECT|ASSERT}_PRED2.  Don't use\n// this in your code.\n#define GTEST_PRED2_(pred, v1, v2, on_failure)                               \\\n  GTEST_ASSERT_(::testing::AssertPred2Helper(#pred, #v1, #v2, pred, v1, v2), \\\n                on_failure)\n\n// Binary predicate assertion macros.\n#define EXPECT_PRED_FORMAT2(pred_format, v1, v2) \\\n  GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_NONFATAL_FAILURE_)\n#define EXPECT_PRED2(pred, v1, v2) \\\n  GTEST_PRED2_(pred, v1, v2, GTEST_NONFATAL_FAILURE_)\n#define ASSERT_PRED_FORMAT2(pred_format, v1, v2) \\\n  GTEST_PRED_FORMAT2_(pred_format, v1, v2, GTEST_FATAL_FAILURE_)\n#define ASSERT_PRED2(pred, v1, v2) \\\n  GTEST_PRED2_(pred, v1, v2, GTEST_FATAL_FAILURE_)\n\n// Helper function for implementing {EXPECT|ASSERT}_PRED3.  Don't use\n// this in your code.\ntemplate <typename Pred, typename T1, typename T2, typename T3>\nAssertionResult AssertPred3Helper(const char* pred_text, const char* e1,\n                                  const char* e2, const char* e3, Pred pred,\n                                  const T1& v1, const T2& v2, const T3& v3) {\n  if (pred(v1, v2, v3)) return AssertionSuccess();\n\n  return AssertionFailure()\n         << pred_text << \"(\" << e1 << \", \" << e2 << \", \" << e3\n         << \") evaluates to false, where\"\n         << \"\\n\"\n         << e1 << \" evaluates to \" << ::testing::PrintToString(v1) << \"\\n\"\n         << e2 << \" evaluates to \" << ::testing::PrintToString(v2) << \"\\n\"\n         << e3 << \" evaluates to \" << ::testing::PrintToString(v3);\n}\n\n// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT3.\n// Don't use this in your code.\n#define GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, on_failure) \\\n  GTEST_ASSERT_(pred_format(#v1, #v2, #v3, v1, v2, v3), on_failure)\n\n// Internal macro for implementing {EXPECT|ASSERT}_PRED3.  Don't use\n// this in your code.\n#define GTEST_PRED3_(pred, v1, v2, v3, on_failure)                          \\\n  GTEST_ASSERT_(                                                            \\\n      ::testing::AssertPred3Helper(#pred, #v1, #v2, #v3, pred, v1, v2, v3), \\\n      on_failure)\n\n// Ternary predicate assertion macros.\n#define EXPECT_PRED_FORMAT3(pred_format, v1, v2, v3) \\\n  GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_NONFATAL_FAILURE_)\n#define EXPECT_PRED3(pred, v1, v2, v3) \\\n  GTEST_PRED3_(pred, v1, v2, v3, GTEST_NONFATAL_FAILURE_)\n#define ASSERT_PRED_FORMAT3(pred_format, v1, v2, v3) \\\n  GTEST_PRED_FORMAT3_(pred_format, v1, v2, v3, GTEST_FATAL_FAILURE_)\n#define ASSERT_PRED3(pred, v1, v2, v3) \\\n  GTEST_PRED3_(pred, v1, v2, v3, GTEST_FATAL_FAILURE_)\n\n// Helper function for implementing {EXPECT|ASSERT}_PRED4.  Don't use\n// this in your code.\ntemplate <typename Pred, typename T1, typename T2, typename T3, typename T4>\nAssertionResult AssertPred4Helper(const char* pred_text, const char* e1,\n                                  const char* e2, const char* e3,\n                                  const char* e4, Pred pred, const T1& v1,\n                                  const T2& v2, const T3& v3, const T4& v4) {\n  if (pred(v1, v2, v3, v4)) return AssertionSuccess();\n\n  return AssertionFailure()\n         << pred_text << \"(\" << e1 << \", \" << e2 << \", \" << e3 << \", \" << e4\n         << \") evaluates to false, where\"\n         << \"\\n\"\n         << e1 << \" evaluates to \" << ::testing::PrintToString(v1) << \"\\n\"\n         << e2 << \" evaluates to \" << ::testing::PrintToString(v2) << \"\\n\"\n         << e3 << \" evaluates to \" << ::testing::PrintToString(v3) << \"\\n\"\n         << e4 << \" evaluates to \" << ::testing::PrintToString(v4);\n}\n\n// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT4.\n// Don't use this in your code.\n#define GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, on_failure) \\\n  GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, v1, v2, v3, v4), on_failure)\n\n// Internal macro for implementing {EXPECT|ASSERT}_PRED4.  Don't use\n// this in your code.\n#define GTEST_PRED4_(pred, v1, v2, v3, v4, on_failure)                        \\\n  GTEST_ASSERT_(::testing::AssertPred4Helper(#pred, #v1, #v2, #v3, #v4, pred, \\\n                                             v1, v2, v3, v4),                 \\\n                on_failure)\n\n// 4-ary predicate assertion macros.\n#define EXPECT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \\\n  GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_)\n#define EXPECT_PRED4(pred, v1, v2, v3, v4) \\\n  GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_NONFATAL_FAILURE_)\n#define ASSERT_PRED_FORMAT4(pred_format, v1, v2, v3, v4) \\\n  GTEST_PRED_FORMAT4_(pred_format, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)\n#define ASSERT_PRED4(pred, v1, v2, v3, v4) \\\n  GTEST_PRED4_(pred, v1, v2, v3, v4, GTEST_FATAL_FAILURE_)\n\n// Helper function for implementing {EXPECT|ASSERT}_PRED5.  Don't use\n// this in your code.\ntemplate <typename Pred, typename T1, typename T2, typename T3, typename T4,\n          typename T5>\nAssertionResult AssertPred5Helper(const char* pred_text, const char* e1,\n                                  const char* e2, const char* e3,\n                                  const char* e4, const char* e5, Pred pred,\n                                  const T1& v1, const T2& v2, const T3& v3,\n                                  const T4& v4, const T5& v5) {\n  if (pred(v1, v2, v3, v4, v5)) return AssertionSuccess();\n\n  return AssertionFailure()\n         << pred_text << \"(\" << e1 << \", \" << e2 << \", \" << e3 << \", \" << e4\n         << \", \" << e5 << \") evaluates to false, where\"\n         << \"\\n\"\n         << e1 << \" evaluates to \" << ::testing::PrintToString(v1) << \"\\n\"\n         << e2 << \" evaluates to \" << ::testing::PrintToString(v2) << \"\\n\"\n         << e3 << \" evaluates to \" << ::testing::PrintToString(v3) << \"\\n\"\n         << e4 << \" evaluates to \" << ::testing::PrintToString(v4) << \"\\n\"\n         << e5 << \" evaluates to \" << ::testing::PrintToString(v5);\n}\n\n// Internal macro for implementing {EXPECT|ASSERT}_PRED_FORMAT5.\n// Don't use this in your code.\n#define GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, on_failure)  \\\n  GTEST_ASSERT_(pred_format(#v1, #v2, #v3, #v4, #v5, v1, v2, v3, v4, v5), \\\n                on_failure)\n\n// Internal macro for implementing {EXPECT|ASSERT}_PRED5.  Don't use\n// this in your code.\n#define GTEST_PRED5_(pred, v1, v2, v3, v4, v5, on_failure)                   \\\n  GTEST_ASSERT_(::testing::AssertPred5Helper(#pred, #v1, #v2, #v3, #v4, #v5, \\\n                                             pred, v1, v2, v3, v4, v5),      \\\n                on_failure)\n\n// 5-ary predicate assertion macros.\n#define EXPECT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \\\n  GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_)\n#define EXPECT_PRED5(pred, v1, v2, v3, v4, v5) \\\n  GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_NONFATAL_FAILURE_)\n#define ASSERT_PRED_FORMAT5(pred_format, v1, v2, v3, v4, v5) \\\n  GTEST_PRED_FORMAT5_(pred_format, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)\n#define ASSERT_PRED5(pred, v1, v2, v3, v4, v5) \\\n  GTEST_PRED5_(pred, v1, v2, v3, v4, v5, GTEST_FATAL_FAILURE_)\n\n}  // namespace testing\n\n#endif  // GOOGLETEST_INCLUDE_GTEST_GTEST_PRED_IMPL_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/include/gtest/gtest_prod.h",
    "content": "// Copyright 2006, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google C++ Testing and Mocking Framework definitions useful in production\n// code.\n\n#ifndef GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_\n#define GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_\n\n// When you need to test the private or protected members of a class,\n// use the FRIEND_TEST macro to declare your tests as friends of the\n// class.  For example:\n//\n// class MyClass {\n//  private:\n//   void PrivateMethod();\n//   FRIEND_TEST(MyClassTest, PrivateMethodWorks);\n// };\n//\n// class MyClassTest : public testing::Test {\n//   // ...\n// };\n//\n// TEST_F(MyClassTest, PrivateMethodWorks) {\n//   // Can call MyClass::PrivateMethod() here.\n// }\n//\n// Note: The test class must be in the same namespace as the class being tested.\n// For example, putting MyClassTest in an anonymous namespace will not work.\n\n#define FRIEND_TEST(test_case_name, test_name) \\\n  friend class test_case_name##_##test_name##_Test\n\n#endif  // GOOGLETEST_INCLUDE_GTEST_GTEST_PROD_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/include/gtest/internal/custom/README.md",
    "content": "# Customization Points\n\nThe custom directory is an injection point for custom user configurations.\n\n## Header `gtest.h`\n\n### The following macros can be defined:\n\n*   `GTEST_OS_STACK_TRACE_GETTER_` - The name of an implementation of\n    `OsStackTraceGetterInterface`.\n*   `GTEST_CUSTOM_TEMPDIR_FUNCTION_` - An override for `testing::TempDir()`. See\n    `testing::TempDir` for semantics and signature.\n\n## Header `gtest-port.h`\n\nThe following macros can be defined:\n\n### Logging:\n\n*   `GTEST_LOG_(severity)`\n*   `GTEST_CHECK_(condition)`\n*   Functions `LogToStderr()` and `FlushInfoLog()` have to be provided too.\n\n### Threading:\n\n*   `GTEST_HAS_NOTIFICATION_` - Enabled if Notification is already provided.\n*   `GTEST_HAS_MUTEX_AND_THREAD_LOCAL_` - Enabled if `Mutex` and `ThreadLocal`\n    are already provided. Must also provide `GTEST_DECLARE_STATIC_MUTEX_(mutex)`\n    and `GTEST_DEFINE_STATIC_MUTEX_(mutex)`\n*   `GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)`\n*   `GTEST_LOCK_EXCLUDED_(locks)`\n\n### Underlying library support features\n\n*   `GTEST_HAS_CXXABI_H_`\n\n### Exporting API symbols:\n\n*   `GTEST_API_` - Specifier for exported symbols.\n\n## Header `gtest-printers.h`\n\n*   See documentation at `gtest/gtest-printers.h` for details on how to define a\n    custom printer.\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/include/gtest/internal/custom/gtest-port.h",
    "content": "// Copyright 2015, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Injection point for custom user configurations. See README for details\n//\n// ** Custom implementation starts here **\n\n#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_\n#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_\n\n#endif  // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PORT_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/include/gtest/internal/custom/gtest-printers.h",
    "content": "// Copyright 2015, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// This file provides an injection point for custom printers in a local\n// installation of gTest.\n// It will be included from gtest-printers.h and the overrides in this file\n// will be visible to everyone.\n//\n// Injection point for custom user configurations. See README for details\n//\n// ** Custom implementation starts here **\n\n#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_\n#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_\n\n#endif  // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_PRINTERS_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/include/gtest/internal/custom/gtest.h",
    "content": "// Copyright 2015, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Injection point for custom user configurations. See README for details\n//\n// ** Custom implementation starts here **\n\n#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_\n#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_\n\n#endif  // GOOGLETEST_INCLUDE_GTEST_INTERNAL_CUSTOM_GTEST_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/include/gtest/internal/gtest-death-test-internal.h",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// The Google C++ Testing and Mocking Framework (Google Test)\n//\n// This header file defines internal utilities needed for implementing\n// death tests.  They are subject to change without notice.\n\n// IWYU pragma: private, include \"gtest/gtest.h\"\n// IWYU pragma: friend gtest/.*\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_\n#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_\n\n#include <stdio.h>\n\n#include <memory>\n\n#include \"gtest/gtest-matchers.h\"\n#include \"gtest/internal/gtest-internal.h\"\n\nGTEST_DECLARE_string_(internal_run_death_test);\n\nnamespace testing {\nnamespace internal {\n\n// Names of the flags (needed for parsing Google Test flags).\nconst char kDeathTestStyleFlag[] = \"death_test_style\";\nconst char kDeathTestUseFork[] = \"death_test_use_fork\";\nconst char kInternalRunDeathTestFlag[] = \"internal_run_death_test\";\n\n#if GTEST_HAS_DEATH_TEST\n\nGTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \\\n/* class A needs to have dll-interface to be used by clients of class B */)\n\n// DeathTest is a class that hides much of the complexity of the\n// GTEST_DEATH_TEST_ macro.  It is abstract; its static Create method\n// returns a concrete class that depends on the prevailing death test\n// style, as defined by the --gtest_death_test_style and/or\n// --gtest_internal_run_death_test flags.\n\n// In describing the results of death tests, these terms are used with\n// the corresponding definitions:\n//\n// exit status:  The integer exit information in the format specified\n//               by wait(2)\n// exit code:    The integer code passed to exit(3), _exit(2), or\n//               returned from main()\nclass GTEST_API_ DeathTest {\n public:\n  // Create returns false if there was an error determining the\n  // appropriate action to take for the current death test; for example,\n  // if the gtest_death_test_style flag is set to an invalid value.\n  // The LastMessage method will return a more detailed message in that\n  // case.  Otherwise, the DeathTest pointer pointed to by the \"test\"\n  // argument is set.  If the death test should be skipped, the pointer\n  // is set to NULL; otherwise, it is set to the address of a new concrete\n  // DeathTest object that controls the execution of the current test.\n  static bool Create(const char* statement, Matcher<const std::string&> matcher,\n                     const char* file, int line, DeathTest** test);\n  DeathTest();\n  virtual ~DeathTest() {}\n\n  // A helper class that aborts a death test when it's deleted.\n  class ReturnSentinel {\n   public:\n    explicit ReturnSentinel(DeathTest* test) : test_(test) {}\n    ~ReturnSentinel() { test_->Abort(TEST_ENCOUNTERED_RETURN_STATEMENT); }\n\n   private:\n    DeathTest* const test_;\n    ReturnSentinel(const ReturnSentinel&) = delete;\n    ReturnSentinel& operator=(const ReturnSentinel&) = delete;\n  } GTEST_ATTRIBUTE_UNUSED_;\n\n  // An enumeration of possible roles that may be taken when a death\n  // test is encountered.  EXECUTE means that the death test logic should\n  // be executed immediately.  OVERSEE means that the program should prepare\n  // the appropriate environment for a child process to execute the death\n  // test, then wait for it to complete.\n  enum TestRole { OVERSEE_TEST, EXECUTE_TEST };\n\n  // An enumeration of the three reasons that a test might be aborted.\n  enum AbortReason {\n    TEST_ENCOUNTERED_RETURN_STATEMENT,\n    TEST_THREW_EXCEPTION,\n    TEST_DID_NOT_DIE\n  };\n\n  // Assumes one of the above roles.\n  virtual TestRole AssumeRole() = 0;\n\n  // Waits for the death test to finish and returns its status.\n  virtual int Wait() = 0;\n\n  // Returns true if the death test passed; that is, the test process\n  // exited during the test, its exit status matches a user-supplied\n  // predicate, and its stderr output matches a user-supplied regular\n  // expression.\n  // The user-supplied predicate may be a macro expression rather\n  // than a function pointer or functor, or else Wait and Passed could\n  // be combined.\n  virtual bool Passed(bool exit_status_ok) = 0;\n\n  // Signals that the death test did not die as expected.\n  virtual void Abort(AbortReason reason) = 0;\n\n  // Returns a human-readable outcome message regarding the outcome of\n  // the last death test.\n  static const char* LastMessage();\n\n  static void set_last_death_test_message(const std::string& message);\n\n private:\n  // A string containing a description of the outcome of the last death test.\n  static std::string last_death_test_message_;\n\n  DeathTest(const DeathTest&) = delete;\n  DeathTest& operator=(const DeathTest&) = delete;\n};\n\nGTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251\n\n// Factory interface for death tests.  May be mocked out for testing.\nclass DeathTestFactory {\n public:\n  virtual ~DeathTestFactory() {}\n  virtual bool Create(const char* statement,\n                      Matcher<const std::string&> matcher, const char* file,\n                      int line, DeathTest** test) = 0;\n};\n\n// A concrete DeathTestFactory implementation for normal use.\nclass DefaultDeathTestFactory : public DeathTestFactory {\n public:\n  bool Create(const char* statement, Matcher<const std::string&> matcher,\n              const char* file, int line, DeathTest** test) override;\n};\n\n// Returns true if exit_status describes a process that was terminated\n// by a signal, or exited normally with a nonzero exit code.\nGTEST_API_ bool ExitedUnsuccessfully(int exit_status);\n\n// A string passed to EXPECT_DEATH (etc.) is caught by one of these overloads\n// and interpreted as a regex (rather than an Eq matcher) for legacy\n// compatibility.\ninline Matcher<const ::std::string&> MakeDeathTestMatcher(\n    ::testing::internal::RE regex) {\n  return ContainsRegex(regex.pattern());\n}\ninline Matcher<const ::std::string&> MakeDeathTestMatcher(const char* regex) {\n  return ContainsRegex(regex);\n}\ninline Matcher<const ::std::string&> MakeDeathTestMatcher(\n    const ::std::string& regex) {\n  return ContainsRegex(regex);\n}\n\n// If a Matcher<const ::std::string&> is passed to EXPECT_DEATH (etc.), it's\n// used directly.\ninline Matcher<const ::std::string&> MakeDeathTestMatcher(\n    Matcher<const ::std::string&> matcher) {\n  return matcher;\n}\n\n// Traps C++ exceptions escaping statement and reports them as test\n// failures. Note that trapping SEH exceptions is not implemented here.\n#if GTEST_HAS_EXCEPTIONS\n#define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test)           \\\n  try {                                                                      \\\n    GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement);               \\\n  } catch (const ::std::exception& gtest_exception) {                        \\\n    fprintf(                                                                 \\\n        stderr,                                                              \\\n        \"\\n%s: Caught std::exception-derived exception escaping the \"        \\\n        \"death test statement. Exception message: %s\\n\",                     \\\n        ::testing::internal::FormatFileLocation(__FILE__, __LINE__).c_str(), \\\n        gtest_exception.what());                                             \\\n    fflush(stderr);                                                          \\\n    death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \\\n  } catch (...) {                                                            \\\n    death_test->Abort(::testing::internal::DeathTest::TEST_THREW_EXCEPTION); \\\n  }\n\n#else\n#define GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, death_test) \\\n  GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement)\n\n#endif\n\n// This macro is for implementing ASSERT_DEATH*, EXPECT_DEATH*,\n// ASSERT_EXIT*, and EXPECT_EXIT*.\n#define GTEST_DEATH_TEST_(statement, predicate, regex_or_matcher, fail)        \\\n  GTEST_AMBIGUOUS_ELSE_BLOCKER_                                                \\\n  if (::testing::internal::AlwaysTrue()) {                                     \\\n    ::testing::internal::DeathTest* gtest_dt;                                  \\\n    if (!::testing::internal::DeathTest::Create(                               \\\n            #statement,                                                        \\\n            ::testing::internal::MakeDeathTestMatcher(regex_or_matcher),       \\\n            __FILE__, __LINE__, &gtest_dt)) {                                  \\\n      goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__);                        \\\n    }                                                                          \\\n    if (gtest_dt != nullptr) {                                                 \\\n      std::unique_ptr< ::testing::internal::DeathTest> gtest_dt_ptr(gtest_dt); \\\n      switch (gtest_dt->AssumeRole()) {                                        \\\n        case ::testing::internal::DeathTest::OVERSEE_TEST:                     \\\n          if (!gtest_dt->Passed(predicate(gtest_dt->Wait()))) {                \\\n            goto GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__);                  \\\n          }                                                                    \\\n          break;                                                               \\\n        case ::testing::internal::DeathTest::EXECUTE_TEST: {                   \\\n          ::testing::internal::DeathTest::ReturnSentinel gtest_sentinel(       \\\n              gtest_dt);                                                       \\\n          GTEST_EXECUTE_DEATH_TEST_STATEMENT_(statement, gtest_dt);            \\\n          gtest_dt->Abort(::testing::internal::DeathTest::TEST_DID_NOT_DIE);   \\\n          break;                                                               \\\n        }                                                                      \\\n      }                                                                        \\\n    }                                                                          \\\n  } else                                                                       \\\n    GTEST_CONCAT_TOKEN_(gtest_label_, __LINE__)                                \\\n        : fail(::testing::internal::DeathTest::LastMessage())\n// The symbol \"fail\" here expands to something into which a message\n// can be streamed.\n\n// This macro is for implementing ASSERT/EXPECT_DEBUG_DEATH when compiled in\n// NDEBUG mode. In this case we need the statements to be executed and the macro\n// must accept a streamed message even though the message is never printed.\n// The regex object is not evaluated, but it is used to prevent \"unused\"\n// warnings and to avoid an expression that doesn't compile in debug mode.\n#define GTEST_EXECUTE_STATEMENT_(statement, regex_or_matcher)    \\\n  GTEST_AMBIGUOUS_ELSE_BLOCKER_                                  \\\n  if (::testing::internal::AlwaysTrue()) {                       \\\n    GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement);   \\\n  } else if (!::testing::internal::AlwaysTrue()) {               \\\n    ::testing::internal::MakeDeathTestMatcher(regex_or_matcher); \\\n  } else                                                         \\\n    ::testing::Message()\n\n// A class representing the parsed contents of the\n// --gtest_internal_run_death_test flag, as it existed when\n// RUN_ALL_TESTS was called.\nclass InternalRunDeathTestFlag {\n public:\n  InternalRunDeathTestFlag(const std::string& a_file, int a_line, int an_index,\n                           int a_write_fd)\n      : file_(a_file), line_(a_line), index_(an_index), write_fd_(a_write_fd) {}\n\n  ~InternalRunDeathTestFlag() {\n    if (write_fd_ >= 0) posix::Close(write_fd_);\n  }\n\n  const std::string& file() const { return file_; }\n  int line() const { return line_; }\n  int index() const { return index_; }\n  int write_fd() const { return write_fd_; }\n\n private:\n  std::string file_;\n  int line_;\n  int index_;\n  int write_fd_;\n\n  InternalRunDeathTestFlag(const InternalRunDeathTestFlag&) = delete;\n  InternalRunDeathTestFlag& operator=(const InternalRunDeathTestFlag&) = delete;\n};\n\n// Returns a newly created InternalRunDeathTestFlag object with fields\n// initialized from the GTEST_FLAG(internal_run_death_test) flag if\n// the flag is specified; otherwise returns NULL.\nInternalRunDeathTestFlag* ParseInternalRunDeathTestFlag();\n\n#endif  // GTEST_HAS_DEATH_TEST\n\n}  // namespace internal\n}  // namespace testing\n\n#endif  // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_DEATH_TEST_INTERNAL_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/include/gtest/internal/gtest-filepath.h",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Test filepath utilities\n//\n// This header file declares classes and functions used internally by\n// Google Test.  They are subject to change without notice.\n//\n// This file is #included in gtest/internal/gtest-internal.h.\n// Do not include this header file separately!\n\n// IWYU pragma: private, include \"gtest/gtest.h\"\n// IWYU pragma: friend gtest/.*\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_\n#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_\n\n#include \"gtest/internal/gtest-string.h\"\n\nGTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \\\n/* class A needs to have dll-interface to be used by clients of class B */)\n\nnamespace testing {\nnamespace internal {\n\n// FilePath - a class for file and directory pathname manipulation which\n// handles platform-specific conventions (like the pathname separator).\n// Used for helper functions for naming files in a directory for xml output.\n// Except for Set methods, all methods are const or static, which provides an\n// \"immutable value object\" -- useful for peace of mind.\n// A FilePath with a value ending in a path separator (\"like/this/\") represents\n// a directory, otherwise it is assumed to represent a file. In either case,\n// it may or may not represent an actual file or directory in the file system.\n// Names are NOT checked for syntax correctness -- no checking for illegal\n// characters, malformed paths, etc.\n\nclass GTEST_API_ FilePath {\n public:\n  FilePath() : pathname_(\"\") {}\n  FilePath(const FilePath& rhs) : pathname_(rhs.pathname_) {}\n\n  explicit FilePath(const std::string& pathname) : pathname_(pathname) {\n    Normalize();\n  }\n\n  FilePath& operator=(const FilePath& rhs) {\n    Set(rhs);\n    return *this;\n  }\n\n  void Set(const FilePath& rhs) { pathname_ = rhs.pathname_; }\n\n  const std::string& string() const { return pathname_; }\n  const char* c_str() const { return pathname_.c_str(); }\n\n  // Returns the current working directory, or \"\" if unsuccessful.\n  static FilePath GetCurrentDir();\n\n  // Given directory = \"dir\", base_name = \"test\", number = 0,\n  // extension = \"xml\", returns \"dir/test.xml\". If number is greater\n  // than zero (e.g., 12), returns \"dir/test_12.xml\".\n  // On Windows platform, uses \\ as the separator rather than /.\n  static FilePath MakeFileName(const FilePath& directory,\n                               const FilePath& base_name, int number,\n                               const char* extension);\n\n  // Given directory = \"dir\", relative_path = \"test.xml\",\n  // returns \"dir/test.xml\".\n  // On Windows, uses \\ as the separator rather than /.\n  static FilePath ConcatPaths(const FilePath& directory,\n                              const FilePath& relative_path);\n\n  // Returns a pathname for a file that does not currently exist. The pathname\n  // will be directory/base_name.extension or\n  // directory/base_name_<number>.extension if directory/base_name.extension\n  // already exists. The number will be incremented until a pathname is found\n  // that does not already exist.\n  // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.\n  // There could be a race condition if two or more processes are calling this\n  // function at the same time -- they could both pick the same filename.\n  static FilePath GenerateUniqueFileName(const FilePath& directory,\n                                         const FilePath& base_name,\n                                         const char* extension);\n\n  // Returns true if and only if the path is \"\".\n  bool IsEmpty() const { return pathname_.empty(); }\n\n  // If input name has a trailing separator character, removes it and returns\n  // the name, otherwise return the name string unmodified.\n  // On Windows platform, uses \\ as the separator, other platforms use /.\n  FilePath RemoveTrailingPathSeparator() const;\n\n  // Returns a copy of the FilePath with the directory part removed.\n  // Example: FilePath(\"path/to/file\").RemoveDirectoryName() returns\n  // FilePath(\"file\"). If there is no directory part (\"just_a_file\"), it returns\n  // the FilePath unmodified. If there is no file part (\"just_a_dir/\") it\n  // returns an empty FilePath (\"\").\n  // On Windows platform, '\\' is the path separator, otherwise it is '/'.\n  FilePath RemoveDirectoryName() const;\n\n  // RemoveFileName returns the directory path with the filename removed.\n  // Example: FilePath(\"path/to/file\").RemoveFileName() returns \"path/to/\".\n  // If the FilePath is \"a_file\" or \"/a_file\", RemoveFileName returns\n  // FilePath(\"./\") or, on Windows, FilePath(\".\\\\\"). If the filepath does\n  // not have a file, like \"just/a/dir/\", it returns the FilePath unmodified.\n  // On Windows platform, '\\' is the path separator, otherwise it is '/'.\n  FilePath RemoveFileName() const;\n\n  // Returns a copy of the FilePath with the case-insensitive extension removed.\n  // Example: FilePath(\"dir/file.exe\").RemoveExtension(\"EXE\") returns\n  // FilePath(\"dir/file\"). If a case-insensitive extension is not\n  // found, returns a copy of the original FilePath.\n  FilePath RemoveExtension(const char* extension) const;\n\n  // Creates directories so that path exists. Returns true if successful or if\n  // the directories already exist; returns false if unable to create\n  // directories for any reason. Will also return false if the FilePath does\n  // not represent a directory (that is, it doesn't end with a path separator).\n  bool CreateDirectoriesRecursively() const;\n\n  // Create the directory so that path exists. Returns true if successful or\n  // if the directory already exists; returns false if unable to create the\n  // directory for any reason, including if the parent directory does not\n  // exist. Not named \"CreateDirectory\" because that's a macro on Windows.\n  bool CreateFolder() const;\n\n  // Returns true if FilePath describes something in the file-system,\n  // either a file, directory, or whatever, and that something exists.\n  bool FileOrDirectoryExists() const;\n\n  // Returns true if pathname describes a directory in the file-system\n  // that exists.\n  bool DirectoryExists() const;\n\n  // Returns true if FilePath ends with a path separator, which indicates that\n  // it is intended to represent a directory. Returns false otherwise.\n  // This does NOT check that a directory (or file) actually exists.\n  bool IsDirectory() const;\n\n  // Returns true if pathname describes a root directory. (Windows has one\n  // root directory per disk drive.)\n  bool IsRootDirectory() const;\n\n  // Returns true if pathname describes an absolute path.\n  bool IsAbsolutePath() const;\n\n private:\n  // Replaces multiple consecutive separators with a single separator.\n  // For example, \"bar///foo\" becomes \"bar/foo\". Does not eliminate other\n  // redundancies that might be in a pathname involving \".\" or \"..\".\n  //\n  // A pathname with multiple consecutive separators may occur either through\n  // user error or as a result of some scripts or APIs that generate a pathname\n  // with a trailing separator. On other platforms the same API or script\n  // may NOT generate a pathname with a trailing \"/\". Then elsewhere that\n  // pathname may have another \"/\" and pathname components added to it,\n  // without checking for the separator already being there.\n  // The script language and operating system may allow paths like \"foo//bar\"\n  // but some of the functions in FilePath will not handle that correctly. In\n  // particular, RemoveTrailingPathSeparator() only removes one separator, and\n  // it is called in CreateDirectoriesRecursively() assuming that it will change\n  // a pathname from directory syntax (trailing separator) to filename syntax.\n  //\n  // On Windows this method also replaces the alternate path separator '/' with\n  // the primary path separator '\\\\', so that for example \"bar\\\\/\\\\foo\" becomes\n  // \"bar\\\\foo\".\n\n  void Normalize();\n\n  // Returns a pointer to the last occurrence of a valid path separator in\n  // the FilePath. On Windows, for example, both '/' and '\\' are valid path\n  // separators. Returns NULL if no path separator was found.\n  const char* FindLastPathSeparator() const;\n\n  std::string pathname_;\n};  // class FilePath\n\n}  // namespace internal\n}  // namespace testing\n\nGTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251\n\n#endif  // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_FILEPATH_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/include/gtest/internal/gtest-internal.h",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// The Google C++ Testing and Mocking Framework (Google Test)\n//\n// This header file declares functions and macros used internally by\n// Google Test.  They are subject to change without notice.\n\n// IWYU pragma: private, include \"gtest/gtest.h\"\n// IWYU pragma: friend gtest/.*\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_\n#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_\n\n#include \"gtest/internal/gtest-port.h\"\n\n#if GTEST_OS_LINUX\n#include <stdlib.h>\n#include <sys/types.h>\n#include <sys/wait.h>\n#include <unistd.h>\n#endif  // GTEST_OS_LINUX\n\n#if GTEST_HAS_EXCEPTIONS\n#include <stdexcept>\n#endif\n\n#include <ctype.h>\n#include <float.h>\n#include <string.h>\n\n#include <cstdint>\n#include <iomanip>\n#include <limits>\n#include <map>\n#include <set>\n#include <string>\n#include <type_traits>\n#include <vector>\n\n#include \"gtest/gtest-message.h\"\n#include \"gtest/internal/gtest-filepath.h\"\n#include \"gtest/internal/gtest-string.h\"\n#include \"gtest/internal/gtest-type-util.h\"\n\n// Due to C++ preprocessor weirdness, we need double indirection to\n// concatenate two tokens when one of them is __LINE__.  Writing\n//\n//   foo ## __LINE__\n//\n// will result in the token foo__LINE__, instead of foo followed by\n// the current line number.  For more details, see\n// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.6\n#define GTEST_CONCAT_TOKEN_(foo, bar) GTEST_CONCAT_TOKEN_IMPL_(foo, bar)\n#define GTEST_CONCAT_TOKEN_IMPL_(foo, bar) foo##bar\n\n// Stringifies its argument.\n// Work around a bug in visual studio which doesn't accept code like this:\n//\n//   #define GTEST_STRINGIFY_(name) #name\n//   #define MACRO(a, b, c) ... GTEST_STRINGIFY_(a) ...\n//   MACRO(, x, y)\n//\n// Complaining about the argument to GTEST_STRINGIFY_ being empty.\n// This is allowed by the spec.\n#define GTEST_STRINGIFY_HELPER_(name, ...) #name\n#define GTEST_STRINGIFY_(...) GTEST_STRINGIFY_HELPER_(__VA_ARGS__, )\n\nnamespace proto2 {\nclass MessageLite;\n}\n\nnamespace testing {\n\n// Forward declarations.\n\nclass AssertionResult;  // Result of an assertion.\nclass Message;          // Represents a failure message.\nclass Test;             // Represents a test.\nclass TestInfo;         // Information about a test.\nclass TestPartResult;   // Result of a test part.\nclass UnitTest;         // A collection of test suites.\n\ntemplate <typename T>\n::std::string PrintToString(const T& value);\n\nnamespace internal {\n\nstruct TraceInfo;    // Information about a trace point.\nclass TestInfoImpl;  // Opaque implementation of TestInfo\nclass UnitTestImpl;  // Opaque implementation of UnitTest\n\n// The text used in failure messages to indicate the start of the\n// stack trace.\nGTEST_API_ extern const char kStackTraceMarker[];\n\n// An IgnoredValue object can be implicitly constructed from ANY value.\nclass IgnoredValue {\n  struct Sink {};\n\n public:\n  // This constructor template allows any value to be implicitly\n  // converted to IgnoredValue.  The object has no data member and\n  // doesn't try to remember anything about the argument.  We\n  // deliberately omit the 'explicit' keyword in order to allow the\n  // conversion to be implicit.\n  // Disable the conversion if T already has a magical conversion operator.\n  // Otherwise we get ambiguity.\n  template <typename T,\n            typename std::enable_if<!std::is_convertible<T, Sink>::value,\n                                    int>::type = 0>\n  IgnoredValue(const T& /* ignored */) {}  // NOLINT(runtime/explicit)\n};\n\n// Appends the user-supplied message to the Google-Test-generated message.\nGTEST_API_ std::string AppendUserMessage(const std::string& gtest_msg,\n                                         const Message& user_msg);\n\n#if GTEST_HAS_EXCEPTIONS\n\nGTEST_DISABLE_MSC_WARNINGS_PUSH_(\n    4275 /* an exported class was derived from a class that was not exported */)\n\n// This exception is thrown by (and only by) a failed Google Test\n// assertion when GTEST_FLAG(throw_on_failure) is true (if exceptions\n// are enabled).  We derive it from std::runtime_error, which is for\n// errors presumably detectable only at run time.  Since\n// std::runtime_error inherits from std::exception, many testing\n// frameworks know how to extract and print the message inside it.\nclass GTEST_API_ GoogleTestFailureException : public ::std::runtime_error {\n public:\n  explicit GoogleTestFailureException(const TestPartResult& failure);\n};\n\nGTEST_DISABLE_MSC_WARNINGS_POP_()  //  4275\n\n#endif  // GTEST_HAS_EXCEPTIONS\n\nnamespace edit_distance {\n// Returns the optimal edits to go from 'left' to 'right'.\n// All edits cost the same, with replace having lower priority than\n// add/remove.\n// Simple implementation of the Wagner-Fischer algorithm.\n// See http://en.wikipedia.org/wiki/Wagner-Fischer_algorithm\nenum EditType { kMatch, kAdd, kRemove, kReplace };\nGTEST_API_ std::vector<EditType> CalculateOptimalEdits(\n    const std::vector<size_t>& left, const std::vector<size_t>& right);\n\n// Same as above, but the input is represented as strings.\nGTEST_API_ std::vector<EditType> CalculateOptimalEdits(\n    const std::vector<std::string>& left,\n    const std::vector<std::string>& right);\n\n// Create a diff of the input strings in Unified diff format.\nGTEST_API_ std::string CreateUnifiedDiff(const std::vector<std::string>& left,\n                                         const std::vector<std::string>& right,\n                                         size_t context = 2);\n\n}  // namespace edit_distance\n\n// Constructs and returns the message for an equality assertion\n// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.\n//\n// The first four parameters are the expressions used in the assertion\n// and their values, as strings.  For example, for ASSERT_EQ(foo, bar)\n// where foo is 5 and bar is 6, we have:\n//\n//   expected_expression: \"foo\"\n//   actual_expression:   \"bar\"\n//   expected_value:      \"5\"\n//   actual_value:        \"6\"\n//\n// The ignoring_case parameter is true if and only if the assertion is a\n// *_STRCASEEQ*.  When it's true, the string \" (ignoring case)\" will\n// be inserted into the message.\nGTEST_API_ AssertionResult EqFailure(const char* expected_expression,\n                                     const char* actual_expression,\n                                     const std::string& expected_value,\n                                     const std::string& actual_value,\n                                     bool ignoring_case);\n\n// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.\nGTEST_API_ std::string GetBoolAssertionFailureMessage(\n    const AssertionResult& assertion_result, const char* expression_text,\n    const char* actual_predicate_value, const char* expected_predicate_value);\n\n// This template class represents an IEEE floating-point number\n// (either single-precision or double-precision, depending on the\n// template parameters).\n//\n// The purpose of this class is to do more sophisticated number\n// comparison.  (Due to round-off error, etc, it's very unlikely that\n// two floating-points will be equal exactly.  Hence a naive\n// comparison by the == operation often doesn't work.)\n//\n// Format of IEEE floating-point:\n//\n//   The most-significant bit being the leftmost, an IEEE\n//   floating-point looks like\n//\n//     sign_bit exponent_bits fraction_bits\n//\n//   Here, sign_bit is a single bit that designates the sign of the\n//   number.\n//\n//   For float, there are 8 exponent bits and 23 fraction bits.\n//\n//   For double, there are 11 exponent bits and 52 fraction bits.\n//\n//   More details can be found at\n//   http://en.wikipedia.org/wiki/IEEE_floating-point_standard.\n//\n// Template parameter:\n//\n//   RawType: the raw floating-point type (either float or double)\ntemplate <typename RawType>\nclass FloatingPoint {\n public:\n  // Defines the unsigned integer type that has the same size as the\n  // floating point number.\n  typedef typename TypeWithSize<sizeof(RawType)>::UInt Bits;\n\n  // Constants.\n\n  // # of bits in a number.\n  static const size_t kBitCount = 8 * sizeof(RawType);\n\n  // # of fraction bits in a number.\n  static const size_t kFractionBitCount =\n      std::numeric_limits<RawType>::digits - 1;\n\n  // # of exponent bits in a number.\n  static const size_t kExponentBitCount = kBitCount - 1 - kFractionBitCount;\n\n  // The mask for the sign bit.\n  static const Bits kSignBitMask = static_cast<Bits>(1) << (kBitCount - 1);\n\n  // The mask for the fraction bits.\n  static const Bits kFractionBitMask = ~static_cast<Bits>(0) >>\n                                       (kExponentBitCount + 1);\n\n  // The mask for the exponent bits.\n  static const Bits kExponentBitMask = ~(kSignBitMask | kFractionBitMask);\n\n  // How many ULP's (Units in the Last Place) we want to tolerate when\n  // comparing two numbers.  The larger the value, the more error we\n  // allow.  A 0 value means that two numbers must be exactly the same\n  // to be considered equal.\n  //\n  // The maximum error of a single floating-point operation is 0.5\n  // units in the last place.  On Intel CPU's, all floating-point\n  // calculations are done with 80-bit precision, while double has 64\n  // bits.  Therefore, 4 should be enough for ordinary use.\n  //\n  // See the following article for more details on ULP:\n  // http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/\n  static const uint32_t kMaxUlps = 4;\n\n  // Constructs a FloatingPoint from a raw floating-point number.\n  //\n  // On an Intel CPU, passing a non-normalized NAN (Not a Number)\n  // around may change its bits, although the new value is guaranteed\n  // to be also a NAN.  Therefore, don't expect this constructor to\n  // preserve the bits in x when x is a NAN.\n  explicit FloatingPoint(const RawType& x) { u_.value_ = x; }\n\n  // Static methods\n\n  // Reinterprets a bit pattern as a floating-point number.\n  //\n  // This function is needed to test the AlmostEquals() method.\n  static RawType ReinterpretBits(const Bits bits) {\n    FloatingPoint fp(0);\n    fp.u_.bits_ = bits;\n    return fp.u_.value_;\n  }\n\n  // Returns the floating-point number that represent positive infinity.\n  static RawType Infinity() { return ReinterpretBits(kExponentBitMask); }\n\n  // Returns the maximum representable finite floating-point number.\n  static RawType Max();\n\n  // Non-static methods\n\n  // Returns the bits that represents this number.\n  const Bits& bits() const { return u_.bits_; }\n\n  // Returns the exponent bits of this number.\n  Bits exponent_bits() const { return kExponentBitMask & u_.bits_; }\n\n  // Returns the fraction bits of this number.\n  Bits fraction_bits() const { return kFractionBitMask & u_.bits_; }\n\n  // Returns the sign bit of this number.\n  Bits sign_bit() const { return kSignBitMask & u_.bits_; }\n\n  // Returns true if and only if this is NAN (not a number).\n  bool is_nan() const {\n    // It's a NAN if the exponent bits are all ones and the fraction\n    // bits are not entirely zeros.\n    return (exponent_bits() == kExponentBitMask) && (fraction_bits() != 0);\n  }\n\n  // Returns true if and only if this number is at most kMaxUlps ULP's away\n  // from rhs.  In particular, this function:\n  //\n  //   - returns false if either number is (or both are) NAN.\n  //   - treats really large numbers as almost equal to infinity.\n  //   - thinks +0.0 and -0.0 are 0 DLP's apart.\n  bool AlmostEquals(const FloatingPoint& rhs) const {\n    // The IEEE standard says that any comparison operation involving\n    // a NAN must return false.\n    if (is_nan() || rhs.is_nan()) return false;\n\n    return DistanceBetweenSignAndMagnitudeNumbers(u_.bits_, rhs.u_.bits_) <=\n           kMaxUlps;\n  }\n\n private:\n  // The data type used to store the actual floating-point number.\n  union FloatingPointUnion {\n    RawType value_;  // The raw floating-point number.\n    Bits bits_;      // The bits that represent the number.\n  };\n\n  // Converts an integer from the sign-and-magnitude representation to\n  // the biased representation.  More precisely, let N be 2 to the\n  // power of (kBitCount - 1), an integer x is represented by the\n  // unsigned number x + N.\n  //\n  // For instance,\n  //\n  //   -N + 1 (the most negative number representable using\n  //          sign-and-magnitude) is represented by 1;\n  //   0      is represented by N; and\n  //   N - 1  (the biggest number representable using\n  //          sign-and-magnitude) is represented by 2N - 1.\n  //\n  // Read http://en.wikipedia.org/wiki/Signed_number_representations\n  // for more details on signed number representations.\n  static Bits SignAndMagnitudeToBiased(const Bits& sam) {\n    if (kSignBitMask & sam) {\n      // sam represents a negative number.\n      return ~sam + 1;\n    } else {\n      // sam represents a positive number.\n      return kSignBitMask | sam;\n    }\n  }\n\n  // Given two numbers in the sign-and-magnitude representation,\n  // returns the distance between them as an unsigned number.\n  static Bits DistanceBetweenSignAndMagnitudeNumbers(const Bits& sam1,\n                                                     const Bits& sam2) {\n    const Bits biased1 = SignAndMagnitudeToBiased(sam1);\n    const Bits biased2 = SignAndMagnitudeToBiased(sam2);\n    return (biased1 >= biased2) ? (biased1 - biased2) : (biased2 - biased1);\n  }\n\n  FloatingPointUnion u_;\n};\n\n// We cannot use std::numeric_limits<T>::max() as it clashes with the max()\n// macro defined by <windows.h>.\ntemplate <>\ninline float FloatingPoint<float>::Max() {\n  return FLT_MAX;\n}\ntemplate <>\ninline double FloatingPoint<double>::Max() {\n  return DBL_MAX;\n}\n\n// Typedefs the instances of the FloatingPoint template class that we\n// care to use.\ntypedef FloatingPoint<float> Float;\ntypedef FloatingPoint<double> Double;\n\n// In order to catch the mistake of putting tests that use different\n// test fixture classes in the same test suite, we need to assign\n// unique IDs to fixture classes and compare them.  The TypeId type is\n// used to hold such IDs.  The user should treat TypeId as an opaque\n// type: the only operation allowed on TypeId values is to compare\n// them for equality using the == operator.\ntypedef const void* TypeId;\n\ntemplate <typename T>\nclass TypeIdHelper {\n public:\n  // dummy_ must not have a const type.  Otherwise an overly eager\n  // compiler (e.g. MSVC 7.1 & 8.0) may try to merge\n  // TypeIdHelper<T>::dummy_ for different Ts as an \"optimization\".\n  static bool dummy_;\n};\n\ntemplate <typename T>\nbool TypeIdHelper<T>::dummy_ = false;\n\n// GetTypeId<T>() returns the ID of type T.  Different values will be\n// returned for different types.  Calling the function twice with the\n// same type argument is guaranteed to return the same ID.\ntemplate <typename T>\nTypeId GetTypeId() {\n  // The compiler is required to allocate a different\n  // TypeIdHelper<T>::dummy_ variable for each T used to instantiate\n  // the template.  Therefore, the address of dummy_ is guaranteed to\n  // be unique.\n  return &(TypeIdHelper<T>::dummy_);\n}\n\n// Returns the type ID of ::testing::Test.  Always call this instead\n// of GetTypeId< ::testing::Test>() to get the type ID of\n// ::testing::Test, as the latter may give the wrong result due to a\n// suspected linker bug when compiling Google Test as a Mac OS X\n// framework.\nGTEST_API_ TypeId GetTestTypeId();\n\n// Defines the abstract factory interface that creates instances\n// of a Test object.\nclass TestFactoryBase {\n public:\n  virtual ~TestFactoryBase() {}\n\n  // Creates a test instance to run. The instance is both created and destroyed\n  // within TestInfoImpl::Run()\n  virtual Test* CreateTest() = 0;\n\n protected:\n  TestFactoryBase() {}\n\n private:\n  TestFactoryBase(const TestFactoryBase&) = delete;\n  TestFactoryBase& operator=(const TestFactoryBase&) = delete;\n};\n\n// This class provides implementation of TeastFactoryBase interface.\n// It is used in TEST and TEST_F macros.\ntemplate <class TestClass>\nclass TestFactoryImpl : public TestFactoryBase {\n public:\n  Test* CreateTest() override { return new TestClass; }\n};\n\n#if GTEST_OS_WINDOWS\n\n// Predicate-formatters for implementing the HRESULT checking macros\n// {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}\n// We pass a long instead of HRESULT to avoid causing an\n// include dependency for the HRESULT type.\nGTEST_API_ AssertionResult IsHRESULTSuccess(const char* expr,\n                                            long hr);  // NOLINT\nGTEST_API_ AssertionResult IsHRESULTFailure(const char* expr,\n                                            long hr);  // NOLINT\n\n#endif  // GTEST_OS_WINDOWS\n\n// Types of SetUpTestSuite() and TearDownTestSuite() functions.\nusing SetUpTestSuiteFunc = void (*)();\nusing TearDownTestSuiteFunc = void (*)();\n\nstruct CodeLocation {\n  CodeLocation(const std::string& a_file, int a_line)\n      : file(a_file), line(a_line) {}\n\n  std::string file;\n  int line;\n};\n\n//  Helper to identify which setup function for TestCase / TestSuite to call.\n//  Only one function is allowed, either TestCase or TestSute but not both.\n\n// Utility functions to help SuiteApiResolver\nusing SetUpTearDownSuiteFuncType = void (*)();\n\ninline SetUpTearDownSuiteFuncType GetNotDefaultOrNull(\n    SetUpTearDownSuiteFuncType a, SetUpTearDownSuiteFuncType def) {\n  return a == def ? nullptr : a;\n}\n\ntemplate <typename T>\n//  Note that SuiteApiResolver inherits from T because\n//  SetUpTestSuite()/TearDownTestSuite() could be protected. This way\n//  SuiteApiResolver can access them.\nstruct SuiteApiResolver : T {\n  // testing::Test is only forward declared at this point. So we make it a\n  // dependent class for the compiler to be OK with it.\n  using Test =\n      typename std::conditional<sizeof(T) != 0, ::testing::Test, void>::type;\n\n  static SetUpTearDownSuiteFuncType GetSetUpCaseOrSuite(const char* filename,\n                                                        int line_num) {\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n    SetUpTearDownSuiteFuncType test_case_fp =\n        GetNotDefaultOrNull(&T::SetUpTestCase, &Test::SetUpTestCase);\n    SetUpTearDownSuiteFuncType test_suite_fp =\n        GetNotDefaultOrNull(&T::SetUpTestSuite, &Test::SetUpTestSuite);\n\n    GTEST_CHECK_(!test_case_fp || !test_suite_fp)\n        << \"Test can not provide both SetUpTestSuite and SetUpTestCase, please \"\n           \"make sure there is only one present at \"\n        << filename << \":\" << line_num;\n\n    return test_case_fp != nullptr ? test_case_fp : test_suite_fp;\n#else\n    (void)(filename);\n    (void)(line_num);\n    return &T::SetUpTestSuite;\n#endif\n  }\n\n  static SetUpTearDownSuiteFuncType GetTearDownCaseOrSuite(const char* filename,\n                                                           int line_num) {\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n    SetUpTearDownSuiteFuncType test_case_fp =\n        GetNotDefaultOrNull(&T::TearDownTestCase, &Test::TearDownTestCase);\n    SetUpTearDownSuiteFuncType test_suite_fp =\n        GetNotDefaultOrNull(&T::TearDownTestSuite, &Test::TearDownTestSuite);\n\n    GTEST_CHECK_(!test_case_fp || !test_suite_fp)\n        << \"Test can not provide both TearDownTestSuite and TearDownTestCase,\"\n           \" please make sure there is only one present at\"\n        << filename << \":\" << line_num;\n\n    return test_case_fp != nullptr ? test_case_fp : test_suite_fp;\n#else\n    (void)(filename);\n    (void)(line_num);\n    return &T::TearDownTestSuite;\n#endif\n  }\n};\n\n// Creates a new TestInfo object and registers it with Google Test;\n// returns the created object.\n//\n// Arguments:\n//\n//   test_suite_name:  name of the test suite\n//   name:             name of the test\n//   type_param:       the name of the test's type parameter, or NULL if\n//                     this is not a typed or a type-parameterized test.\n//   value_param:      text representation of the test's value parameter,\n//                     or NULL if this is not a type-parameterized test.\n//   code_location:    code location where the test is defined\n//   fixture_class_id: ID of the test fixture class\n//   set_up_tc:        pointer to the function that sets up the test suite\n//   tear_down_tc:     pointer to the function that tears down the test suite\n//   factory:          pointer to the factory that creates a test object.\n//                     The newly created TestInfo instance will assume\n//                     ownership of the factory object.\nGTEST_API_ TestInfo* MakeAndRegisterTestInfo(\n    const char* test_suite_name, const char* name, const char* type_param,\n    const char* value_param, CodeLocation code_location,\n    TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,\n    TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory);\n\n// If *pstr starts with the given prefix, modifies *pstr to be right\n// past the prefix and returns true; otherwise leaves *pstr unchanged\n// and returns false.  None of pstr, *pstr, and prefix can be NULL.\nGTEST_API_ bool SkipPrefix(const char* prefix, const char** pstr);\n\nGTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \\\n/* class A needs to have dll-interface to be used by clients of class B */)\n\n// State of the definition of a type-parameterized test suite.\nclass GTEST_API_ TypedTestSuitePState {\n public:\n  TypedTestSuitePState() : registered_(false) {}\n\n  // Adds the given test name to defined_test_names_ and return true\n  // if the test suite hasn't been registered; otherwise aborts the\n  // program.\n  bool AddTestName(const char* file, int line, const char* case_name,\n                   const char* test_name) {\n    if (registered_) {\n      fprintf(stderr,\n              \"%s Test %s must be defined before \"\n              \"REGISTER_TYPED_TEST_SUITE_P(%s, ...).\\n\",\n              FormatFileLocation(file, line).c_str(), test_name, case_name);\n      fflush(stderr);\n      posix::Abort();\n    }\n    registered_tests_.insert(\n        ::std::make_pair(test_name, CodeLocation(file, line)));\n    return true;\n  }\n\n  bool TestExists(const std::string& test_name) const {\n    return registered_tests_.count(test_name) > 0;\n  }\n\n  const CodeLocation& GetCodeLocation(const std::string& test_name) const {\n    RegisteredTestsMap::const_iterator it = registered_tests_.find(test_name);\n    GTEST_CHECK_(it != registered_tests_.end());\n    return it->second;\n  }\n\n  // Verifies that registered_tests match the test names in\n  // defined_test_names_; returns registered_tests if successful, or\n  // aborts the program otherwise.\n  const char* VerifyRegisteredTestNames(const char* test_suite_name,\n                                        const char* file, int line,\n                                        const char* registered_tests);\n\n private:\n  typedef ::std::map<std::string, CodeLocation> RegisteredTestsMap;\n\n  bool registered_;\n  RegisteredTestsMap registered_tests_;\n};\n\n//  Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\nusing TypedTestCasePState = TypedTestSuitePState;\n#endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\nGTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251\n\n// Skips to the first non-space char after the first comma in 'str';\n// returns NULL if no comma is found in 'str'.\ninline const char* SkipComma(const char* str) {\n  const char* comma = strchr(str, ',');\n  if (comma == nullptr) {\n    return nullptr;\n  }\n  while (IsSpace(*(++comma))) {\n  }\n  return comma;\n}\n\n// Returns the prefix of 'str' before the first comma in it; returns\n// the entire string if it contains no comma.\ninline std::string GetPrefixUntilComma(const char* str) {\n  const char* comma = strchr(str, ',');\n  return comma == nullptr ? str : std::string(str, comma);\n}\n\n// Splits a given string on a given delimiter, populating a given\n// vector with the fields.\nvoid SplitString(const ::std::string& str, char delimiter,\n                 ::std::vector<::std::string>* dest);\n\n// The default argument to the template below for the case when the user does\n// not provide a name generator.\nstruct DefaultNameGenerator {\n  template <typename T>\n  static std::string GetName(int i) {\n    return StreamableToString(i);\n  }\n};\n\ntemplate <typename Provided = DefaultNameGenerator>\nstruct NameGeneratorSelector {\n  typedef Provided type;\n};\n\ntemplate <typename NameGenerator>\nvoid GenerateNamesRecursively(internal::None, std::vector<std::string>*, int) {}\n\ntemplate <typename NameGenerator, typename Types>\nvoid GenerateNamesRecursively(Types, std::vector<std::string>* result, int i) {\n  result->push_back(NameGenerator::template GetName<typename Types::Head>(i));\n  GenerateNamesRecursively<NameGenerator>(typename Types::Tail(), result,\n                                          i + 1);\n}\n\ntemplate <typename NameGenerator, typename Types>\nstd::vector<std::string> GenerateNames() {\n  std::vector<std::string> result;\n  GenerateNamesRecursively<NameGenerator>(Types(), &result, 0);\n  return result;\n}\n\n// TypeParameterizedTest<Fixture, TestSel, Types>::Register()\n// registers a list of type-parameterized tests with Google Test.  The\n// return value is insignificant - we just need to return something\n// such that we can call this function in a namespace scope.\n//\n// Implementation note: The GTEST_TEMPLATE_ macro declares a template\n// template parameter.  It's defined in gtest-type-util.h.\ntemplate <GTEST_TEMPLATE_ Fixture, class TestSel, typename Types>\nclass TypeParameterizedTest {\n public:\n  // 'index' is the index of the test in the type list 'Types'\n  // specified in INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, TestSuite,\n  // Types).  Valid values for 'index' are [0, N - 1] where N is the\n  // length of Types.\n  static bool Register(const char* prefix, const CodeLocation& code_location,\n                       const char* case_name, const char* test_names, int index,\n                       const std::vector<std::string>& type_names =\n                           GenerateNames<DefaultNameGenerator, Types>()) {\n    typedef typename Types::Head Type;\n    typedef Fixture<Type> FixtureClass;\n    typedef typename GTEST_BIND_(TestSel, Type) TestClass;\n\n    // First, registers the first type-parameterized test in the type\n    // list.\n    MakeAndRegisterTestInfo(\n        (std::string(prefix) + (prefix[0] == '\\0' ? \"\" : \"/\") + case_name +\n         \"/\" + type_names[static_cast<size_t>(index)])\n            .c_str(),\n        StripTrailingSpaces(GetPrefixUntilComma(test_names)).c_str(),\n        GetTypeName<Type>().c_str(),\n        nullptr,  // No value parameter.\n        code_location, GetTypeId<FixtureClass>(),\n        SuiteApiResolver<TestClass>::GetSetUpCaseOrSuite(\n            code_location.file.c_str(), code_location.line),\n        SuiteApiResolver<TestClass>::GetTearDownCaseOrSuite(\n            code_location.file.c_str(), code_location.line),\n        new TestFactoryImpl<TestClass>);\n\n    // Next, recurses (at compile time) with the tail of the type list.\n    return TypeParameterizedTest<Fixture, TestSel,\n                                 typename Types::Tail>::Register(prefix,\n                                                                 code_location,\n                                                                 case_name,\n                                                                 test_names,\n                                                                 index + 1,\n                                                                 type_names);\n  }\n};\n\n// The base case for the compile time recursion.\ntemplate <GTEST_TEMPLATE_ Fixture, class TestSel>\nclass TypeParameterizedTest<Fixture, TestSel, internal::None> {\n public:\n  static bool Register(const char* /*prefix*/, const CodeLocation&,\n                       const char* /*case_name*/, const char* /*test_names*/,\n                       int /*index*/,\n                       const std::vector<std::string>& =\n                           std::vector<std::string>() /*type_names*/) {\n    return true;\n  }\n};\n\nGTEST_API_ void RegisterTypeParameterizedTestSuite(const char* test_suite_name,\n                                                   CodeLocation code_location);\nGTEST_API_ void RegisterTypeParameterizedTestSuiteInstantiation(\n    const char* case_name);\n\n// TypeParameterizedTestSuite<Fixture, Tests, Types>::Register()\n// registers *all combinations* of 'Tests' and 'Types' with Google\n// Test.  The return value is insignificant - we just need to return\n// something such that we can call this function in a namespace scope.\ntemplate <GTEST_TEMPLATE_ Fixture, typename Tests, typename Types>\nclass TypeParameterizedTestSuite {\n public:\n  static bool Register(const char* prefix, CodeLocation code_location,\n                       const TypedTestSuitePState* state, const char* case_name,\n                       const char* test_names,\n                       const std::vector<std::string>& type_names =\n                           GenerateNames<DefaultNameGenerator, Types>()) {\n    RegisterTypeParameterizedTestSuiteInstantiation(case_name);\n    std::string test_name =\n        StripTrailingSpaces(GetPrefixUntilComma(test_names));\n    if (!state->TestExists(test_name)) {\n      fprintf(stderr, \"Failed to get code location for test %s.%s at %s.\",\n              case_name, test_name.c_str(),\n              FormatFileLocation(code_location.file.c_str(), code_location.line)\n                  .c_str());\n      fflush(stderr);\n      posix::Abort();\n    }\n    const CodeLocation& test_location = state->GetCodeLocation(test_name);\n\n    typedef typename Tests::Head Head;\n\n    // First, register the first test in 'Test' for each type in 'Types'.\n    TypeParameterizedTest<Fixture, Head, Types>::Register(\n        prefix, test_location, case_name, test_names, 0, type_names);\n\n    // Next, recurses (at compile time) with the tail of the test list.\n    return TypeParameterizedTestSuite<Fixture, typename Tests::Tail,\n                                      Types>::Register(prefix, code_location,\n                                                       state, case_name,\n                                                       SkipComma(test_names),\n                                                       type_names);\n  }\n};\n\n// The base case for the compile time recursion.\ntemplate <GTEST_TEMPLATE_ Fixture, typename Types>\nclass TypeParameterizedTestSuite<Fixture, internal::None, Types> {\n public:\n  static bool Register(const char* /*prefix*/, const CodeLocation&,\n                       const TypedTestSuitePState* /*state*/,\n                       const char* /*case_name*/, const char* /*test_names*/,\n                       const std::vector<std::string>& =\n                           std::vector<std::string>() /*type_names*/) {\n    return true;\n  }\n};\n\n// Returns the current OS stack trace as an std::string.\n//\n// The maximum number of stack frames to be included is specified by\n// the gtest_stack_trace_depth flag.  The skip_count parameter\n// specifies the number of top frames to be skipped, which doesn't\n// count against the number of frames to be included.\n//\n// For example, if Foo() calls Bar(), which in turn calls\n// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in\n// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.\nGTEST_API_ std::string GetCurrentOsStackTraceExceptTop(UnitTest* unit_test,\n                                                       int skip_count);\n\n// Helpers for suppressing warnings on unreachable code or constant\n// condition.\n\n// Always returns true.\nGTEST_API_ bool AlwaysTrue();\n\n// Always returns false.\ninline bool AlwaysFalse() { return !AlwaysTrue(); }\n\n// Helper for suppressing false warning from Clang on a const char*\n// variable declared in a conditional expression always being NULL in\n// the else branch.\nstruct GTEST_API_ ConstCharPtr {\n  ConstCharPtr(const char* str) : value(str) {}\n  operator bool() const { return true; }\n  const char* value;\n};\n\n// Helper for declaring std::string within 'if' statement\n// in pre C++17 build environment.\nstruct TrueWithString {\n  TrueWithString() = default;\n  explicit TrueWithString(const char* str) : value(str) {}\n  explicit TrueWithString(const std::string& str) : value(str) {}\n  explicit operator bool() const { return true; }\n  std::string value;\n};\n\n// A simple Linear Congruential Generator for generating random\n// numbers with a uniform distribution.  Unlike rand() and srand(), it\n// doesn't use global state (and therefore can't interfere with user\n// code).  Unlike rand_r(), it's portable.  An LCG isn't very random,\n// but it's good enough for our purposes.\nclass GTEST_API_ Random {\n public:\n  static const uint32_t kMaxRange = 1u << 31;\n\n  explicit Random(uint32_t seed) : state_(seed) {}\n\n  void Reseed(uint32_t seed) { state_ = seed; }\n\n  // Generates a random number from [0, range).  Crashes if 'range' is\n  // 0 or greater than kMaxRange.\n  uint32_t Generate(uint32_t range);\n\n private:\n  uint32_t state_;\n  Random(const Random&) = delete;\n  Random& operator=(const Random&) = delete;\n};\n\n// Turns const U&, U&, const U, and U all into U.\n#define GTEST_REMOVE_REFERENCE_AND_CONST_(T) \\\n  typename std::remove_const<typename std::remove_reference<T>::type>::type\n\n// HasDebugStringAndShortDebugString<T>::value is a compile-time bool constant\n// that's true if and only if T has methods DebugString() and ShortDebugString()\n// that return std::string.\ntemplate <typename T>\nclass HasDebugStringAndShortDebugString {\n private:\n  template <typename C>\n  static auto CheckDebugString(C*) -> typename std::is_same<\n      std::string, decltype(std::declval<const C>().DebugString())>::type;\n  template <typename>\n  static std::false_type CheckDebugString(...);\n\n  template <typename C>\n  static auto CheckShortDebugString(C*) -> typename std::is_same<\n      std::string, decltype(std::declval<const C>().ShortDebugString())>::type;\n  template <typename>\n  static std::false_type CheckShortDebugString(...);\n\n  using HasDebugStringType = decltype(CheckDebugString<T>(nullptr));\n  using HasShortDebugStringType = decltype(CheckShortDebugString<T>(nullptr));\n\n public:\n  static constexpr bool value =\n      HasDebugStringType::value && HasShortDebugStringType::value;\n};\n\ntemplate <typename T>\nconstexpr bool HasDebugStringAndShortDebugString<T>::value;\n\n// When the compiler sees expression IsContainerTest<C>(0), if C is an\n// STL-style container class, the first overload of IsContainerTest\n// will be viable (since both C::iterator* and C::const_iterator* are\n// valid types and NULL can be implicitly converted to them).  It will\n// be picked over the second overload as 'int' is a perfect match for\n// the type of argument 0.  If C::iterator or C::const_iterator is not\n// a valid type, the first overload is not viable, and the second\n// overload will be picked.  Therefore, we can determine whether C is\n// a container class by checking the type of IsContainerTest<C>(0).\n// The value of the expression is insignificant.\n//\n// In C++11 mode we check the existence of a const_iterator and that an\n// iterator is properly implemented for the container.\n//\n// For pre-C++11 that we look for both C::iterator and C::const_iterator.\n// The reason is that C++ injects the name of a class as a member of the\n// class itself (e.g. you can refer to class iterator as either\n// 'iterator' or 'iterator::iterator').  If we look for C::iterator\n// only, for example, we would mistakenly think that a class named\n// iterator is an STL container.\n//\n// Also note that the simpler approach of overloading\n// IsContainerTest(typename C::const_iterator*) and\n// IsContainerTest(...) doesn't work with Visual Age C++ and Sun C++.\ntypedef int IsContainer;\ntemplate <class C,\n          class Iterator = decltype(::std::declval<const C&>().begin()),\n          class = decltype(::std::declval<const C&>().end()),\n          class = decltype(++::std::declval<Iterator&>()),\n          class = decltype(*::std::declval<Iterator>()),\n          class = typename C::const_iterator>\nIsContainer IsContainerTest(int /* dummy */) {\n  return 0;\n}\n\ntypedef char IsNotContainer;\ntemplate <class C>\nIsNotContainer IsContainerTest(long /* dummy */) {\n  return '\\0';\n}\n\n// Trait to detect whether a type T is a hash table.\n// The heuristic used is that the type contains an inner type `hasher` and does\n// not contain an inner type `reverse_iterator`.\n// If the container is iterable in reverse, then order might actually matter.\ntemplate <typename T>\nstruct IsHashTable {\n private:\n  template <typename U>\n  static char test(typename U::hasher*, typename U::reverse_iterator*);\n  template <typename U>\n  static int test(typename U::hasher*, ...);\n  template <typename U>\n  static char test(...);\n\n public:\n  static const bool value = sizeof(test<T>(nullptr, nullptr)) == sizeof(int);\n};\n\ntemplate <typename T>\nconst bool IsHashTable<T>::value;\n\ntemplate <typename C,\n          bool = sizeof(IsContainerTest<C>(0)) == sizeof(IsContainer)>\nstruct IsRecursiveContainerImpl;\n\ntemplate <typename C>\nstruct IsRecursiveContainerImpl<C, false> : public std::false_type {};\n\n// Since the IsRecursiveContainerImpl depends on the IsContainerTest we need to\n// obey the same inconsistencies as the IsContainerTest, namely check if\n// something is a container is relying on only const_iterator in C++11 and\n// is relying on both const_iterator and iterator otherwise\ntemplate <typename C>\nstruct IsRecursiveContainerImpl<C, true> {\n  using value_type = decltype(*std::declval<typename C::const_iterator>());\n  using type =\n      std::is_same<typename std::remove_const<\n                       typename std::remove_reference<value_type>::type>::type,\n                   C>;\n};\n\n// IsRecursiveContainer<Type> is a unary compile-time predicate that\n// evaluates whether C is a recursive container type. A recursive container\n// type is a container type whose value_type is equal to the container type\n// itself. An example for a recursive container type is\n// boost::filesystem::path, whose iterator has a value_type that is equal to\n// boost::filesystem::path.\ntemplate <typename C>\nstruct IsRecursiveContainer : public IsRecursiveContainerImpl<C>::type {};\n\n// Utilities for native arrays.\n\n// ArrayEq() compares two k-dimensional native arrays using the\n// elements' operator==, where k can be any integer >= 0.  When k is\n// 0, ArrayEq() degenerates into comparing a single pair of values.\n\ntemplate <typename T, typename U>\nbool ArrayEq(const T* lhs, size_t size, const U* rhs);\n\n// This generic version is used when k is 0.\ntemplate <typename T, typename U>\ninline bool ArrayEq(const T& lhs, const U& rhs) {\n  return lhs == rhs;\n}\n\n// This overload is used when k >= 1.\ntemplate <typename T, typename U, size_t N>\ninline bool ArrayEq(const T (&lhs)[N], const U (&rhs)[N]) {\n  return internal::ArrayEq(lhs, N, rhs);\n}\n\n// This helper reduces code bloat.  If we instead put its logic inside\n// the previous ArrayEq() function, arrays with different sizes would\n// lead to different copies of the template code.\ntemplate <typename T, typename U>\nbool ArrayEq(const T* lhs, size_t size, const U* rhs) {\n  for (size_t i = 0; i != size; i++) {\n    if (!internal::ArrayEq(lhs[i], rhs[i])) return false;\n  }\n  return true;\n}\n\n// Finds the first element in the iterator range [begin, end) that\n// equals elem.  Element may be a native array type itself.\ntemplate <typename Iter, typename Element>\nIter ArrayAwareFind(Iter begin, Iter end, const Element& elem) {\n  for (Iter it = begin; it != end; ++it) {\n    if (internal::ArrayEq(*it, elem)) return it;\n  }\n  return end;\n}\n\n// CopyArray() copies a k-dimensional native array using the elements'\n// operator=, where k can be any integer >= 0.  When k is 0,\n// CopyArray() degenerates into copying a single value.\n\ntemplate <typename T, typename U>\nvoid CopyArray(const T* from, size_t size, U* to);\n\n// This generic version is used when k is 0.\ntemplate <typename T, typename U>\ninline void CopyArray(const T& from, U* to) {\n  *to = from;\n}\n\n// This overload is used when k >= 1.\ntemplate <typename T, typename U, size_t N>\ninline void CopyArray(const T (&from)[N], U (*to)[N]) {\n  internal::CopyArray(from, N, *to);\n}\n\n// This helper reduces code bloat.  If we instead put its logic inside\n// the previous CopyArray() function, arrays with different sizes\n// would lead to different copies of the template code.\ntemplate <typename T, typename U>\nvoid CopyArray(const T* from, size_t size, U* to) {\n  for (size_t i = 0; i != size; i++) {\n    internal::CopyArray(from[i], to + i);\n  }\n}\n\n// The relation between an NativeArray object (see below) and the\n// native array it represents.\n// We use 2 different structs to allow non-copyable types to be used, as long\n// as RelationToSourceReference() is passed.\nstruct RelationToSourceReference {};\nstruct RelationToSourceCopy {};\n\n// Adapts a native array to a read-only STL-style container.  Instead\n// of the complete STL container concept, this adaptor only implements\n// members useful for Google Mock's container matchers.  New members\n// should be added as needed.  To simplify the implementation, we only\n// support Element being a raw type (i.e. having no top-level const or\n// reference modifier).  It's the client's responsibility to satisfy\n// this requirement.  Element can be an array type itself (hence\n// multi-dimensional arrays are supported).\ntemplate <typename Element>\nclass NativeArray {\n public:\n  // STL-style container typedefs.\n  typedef Element value_type;\n  typedef Element* iterator;\n  typedef const Element* const_iterator;\n\n  // Constructs from a native array. References the source.\n  NativeArray(const Element* array, size_t count, RelationToSourceReference) {\n    InitRef(array, count);\n  }\n\n  // Constructs from a native array. Copies the source.\n  NativeArray(const Element* array, size_t count, RelationToSourceCopy) {\n    InitCopy(array, count);\n  }\n\n  // Copy constructor.\n  NativeArray(const NativeArray& rhs) {\n    (this->*rhs.clone_)(rhs.array_, rhs.size_);\n  }\n\n  ~NativeArray() {\n    if (clone_ != &NativeArray::InitRef) delete[] array_;\n  }\n\n  // STL-style container methods.\n  size_t size() const { return size_; }\n  const_iterator begin() const { return array_; }\n  const_iterator end() const { return array_ + size_; }\n  bool operator==(const NativeArray& rhs) const {\n    return size() == rhs.size() && ArrayEq(begin(), size(), rhs.begin());\n  }\n\n private:\n  static_assert(!std::is_const<Element>::value, \"Type must not be const\");\n  static_assert(!std::is_reference<Element>::value,\n                \"Type must not be a reference\");\n\n  // Initializes this object with a copy of the input.\n  void InitCopy(const Element* array, size_t a_size) {\n    Element* const copy = new Element[a_size];\n    CopyArray(array, a_size, copy);\n    array_ = copy;\n    size_ = a_size;\n    clone_ = &NativeArray::InitCopy;\n  }\n\n  // Initializes this object with a reference of the input.\n  void InitRef(const Element* array, size_t a_size) {\n    array_ = array;\n    size_ = a_size;\n    clone_ = &NativeArray::InitRef;\n  }\n\n  const Element* array_;\n  size_t size_;\n  void (NativeArray::*clone_)(const Element*, size_t);\n};\n\n// Backport of std::index_sequence.\ntemplate <size_t... Is>\nstruct IndexSequence {\n  using type = IndexSequence;\n};\n\n// Double the IndexSequence, and one if plus_one is true.\ntemplate <bool plus_one, typename T, size_t sizeofT>\nstruct DoubleSequence;\ntemplate <size_t... I, size_t sizeofT>\nstruct DoubleSequence<true, IndexSequence<I...>, sizeofT> {\n  using type = IndexSequence<I..., (sizeofT + I)..., 2 * sizeofT>;\n};\ntemplate <size_t... I, size_t sizeofT>\nstruct DoubleSequence<false, IndexSequence<I...>, sizeofT> {\n  using type = IndexSequence<I..., (sizeofT + I)...>;\n};\n\n// Backport of std::make_index_sequence.\n// It uses O(ln(N)) instantiation depth.\ntemplate <size_t N>\nstruct MakeIndexSequenceImpl\n    : DoubleSequence<N % 2 == 1, typename MakeIndexSequenceImpl<N / 2>::type,\n                     N / 2>::type {};\n\ntemplate <>\nstruct MakeIndexSequenceImpl<0> : IndexSequence<> {};\n\ntemplate <size_t N>\nusing MakeIndexSequence = typename MakeIndexSequenceImpl<N>::type;\n\ntemplate <typename... T>\nusing IndexSequenceFor = typename MakeIndexSequence<sizeof...(T)>::type;\n\ntemplate <size_t>\nstruct Ignore {\n  Ignore(...);  // NOLINT\n};\n\ntemplate <typename>\nstruct ElemFromListImpl;\ntemplate <size_t... I>\nstruct ElemFromListImpl<IndexSequence<I...>> {\n  // We make Ignore a template to solve a problem with MSVC.\n  // A non-template Ignore would work fine with `decltype(Ignore(I))...`, but\n  // MSVC doesn't understand how to deal with that pack expansion.\n  // Use `0 * I` to have a single instantiation of Ignore.\n  template <typename R>\n  static R Apply(Ignore<0 * I>..., R (*)(), ...);\n};\n\ntemplate <size_t N, typename... T>\nstruct ElemFromList {\n  using type =\n      decltype(ElemFromListImpl<typename MakeIndexSequence<N>::type>::Apply(\n          static_cast<T (*)()>(nullptr)...));\n};\n\nstruct FlatTupleConstructTag {};\n\ntemplate <typename... T>\nclass FlatTuple;\n\ntemplate <typename Derived, size_t I>\nstruct FlatTupleElemBase;\n\ntemplate <typename... T, size_t I>\nstruct FlatTupleElemBase<FlatTuple<T...>, I> {\n  using value_type = typename ElemFromList<I, T...>::type;\n  FlatTupleElemBase() = default;\n  template <typename Arg>\n  explicit FlatTupleElemBase(FlatTupleConstructTag, Arg&& t)\n      : value(std::forward<Arg>(t)) {}\n  value_type value;\n};\n\ntemplate <typename Derived, typename Idx>\nstruct FlatTupleBase;\n\ntemplate <size_t... Idx, typename... T>\nstruct FlatTupleBase<FlatTuple<T...>, IndexSequence<Idx...>>\n    : FlatTupleElemBase<FlatTuple<T...>, Idx>... {\n  using Indices = IndexSequence<Idx...>;\n  FlatTupleBase() = default;\n  template <typename... Args>\n  explicit FlatTupleBase(FlatTupleConstructTag, Args&&... args)\n      : FlatTupleElemBase<FlatTuple<T...>, Idx>(FlatTupleConstructTag{},\n                                                std::forward<Args>(args))... {}\n\n  template <size_t I>\n  const typename ElemFromList<I, T...>::type& Get() const {\n    return FlatTupleElemBase<FlatTuple<T...>, I>::value;\n  }\n\n  template <size_t I>\n  typename ElemFromList<I, T...>::type& Get() {\n    return FlatTupleElemBase<FlatTuple<T...>, I>::value;\n  }\n\n  template <typename F>\n  auto Apply(F&& f) -> decltype(std::forward<F>(f)(this->Get<Idx>()...)) {\n    return std::forward<F>(f)(Get<Idx>()...);\n  }\n\n  template <typename F>\n  auto Apply(F&& f) const -> decltype(std::forward<F>(f)(this->Get<Idx>()...)) {\n    return std::forward<F>(f)(Get<Idx>()...);\n  }\n};\n\n// Analog to std::tuple but with different tradeoffs.\n// This class minimizes the template instantiation depth, thus allowing more\n// elements than std::tuple would. std::tuple has been seen to require an\n// instantiation depth of more than 10x the number of elements in some\n// implementations.\n// FlatTuple and ElemFromList are not recursive and have a fixed depth\n// regardless of T...\n// MakeIndexSequence, on the other hand, it is recursive but with an\n// instantiation depth of O(ln(N)).\ntemplate <typename... T>\nclass FlatTuple\n    : private FlatTupleBase<FlatTuple<T...>,\n                            typename MakeIndexSequence<sizeof...(T)>::type> {\n  using Indices = typename FlatTupleBase<\n      FlatTuple<T...>, typename MakeIndexSequence<sizeof...(T)>::type>::Indices;\n\n public:\n  FlatTuple() = default;\n  template <typename... Args>\n  explicit FlatTuple(FlatTupleConstructTag tag, Args&&... args)\n      : FlatTuple::FlatTupleBase(tag, std::forward<Args>(args)...) {}\n\n  using FlatTuple::FlatTupleBase::Apply;\n  using FlatTuple::FlatTupleBase::Get;\n};\n\n// Utility functions to be called with static_assert to induce deprecation\n// warnings.\nGTEST_INTERNAL_DEPRECATED(\n    \"INSTANTIATE_TEST_CASE_P is deprecated, please use \"\n    \"INSTANTIATE_TEST_SUITE_P\")\nconstexpr bool InstantiateTestCase_P_IsDeprecated() { return true; }\n\nGTEST_INTERNAL_DEPRECATED(\n    \"TYPED_TEST_CASE_P is deprecated, please use \"\n    \"TYPED_TEST_SUITE_P\")\nconstexpr bool TypedTestCase_P_IsDeprecated() { return true; }\n\nGTEST_INTERNAL_DEPRECATED(\n    \"TYPED_TEST_CASE is deprecated, please use \"\n    \"TYPED_TEST_SUITE\")\nconstexpr bool TypedTestCaseIsDeprecated() { return true; }\n\nGTEST_INTERNAL_DEPRECATED(\n    \"REGISTER_TYPED_TEST_CASE_P is deprecated, please use \"\n    \"REGISTER_TYPED_TEST_SUITE_P\")\nconstexpr bool RegisterTypedTestCase_P_IsDeprecated() { return true; }\n\nGTEST_INTERNAL_DEPRECATED(\n    \"INSTANTIATE_TYPED_TEST_CASE_P is deprecated, please use \"\n    \"INSTANTIATE_TYPED_TEST_SUITE_P\")\nconstexpr bool InstantiateTypedTestCase_P_IsDeprecated() { return true; }\n\n}  // namespace internal\n}  // namespace testing\n\nnamespace std {\n// Some standard library implementations use `struct tuple_size` and some use\n// `class tuple_size`. Clang warns about the mismatch.\n// https://reviews.llvm.org/D55466\n#ifdef __clang__\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wmismatched-tags\"\n#endif\ntemplate <typename... Ts>\nstruct tuple_size<testing::internal::FlatTuple<Ts...>>\n    : std::integral_constant<size_t, sizeof...(Ts)> {};\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n}  // namespace std\n\n#define GTEST_MESSAGE_AT_(file, line, message, result_type)             \\\n  ::testing::internal::AssertHelper(result_type, file, line, message) = \\\n      ::testing::Message()\n\n#define GTEST_MESSAGE_(message, result_type) \\\n  GTEST_MESSAGE_AT_(__FILE__, __LINE__, message, result_type)\n\n#define GTEST_FATAL_FAILURE_(message) \\\n  return GTEST_MESSAGE_(message, ::testing::TestPartResult::kFatalFailure)\n\n#define GTEST_NONFATAL_FAILURE_(message) \\\n  GTEST_MESSAGE_(message, ::testing::TestPartResult::kNonFatalFailure)\n\n#define GTEST_SUCCESS_(message) \\\n  GTEST_MESSAGE_(message, ::testing::TestPartResult::kSuccess)\n\n#define GTEST_SKIP_(message) \\\n  return GTEST_MESSAGE_(message, ::testing::TestPartResult::kSkip)\n\n// Suppress MSVC warning 4072 (unreachable code) for the code following\n// statement if it returns or throws (or doesn't return or throw in some\n// situations).\n// NOTE: The \"else\" is important to keep this expansion to prevent a top-level\n// \"else\" from attaching to our \"if\".\n#define GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) \\\n  if (::testing::internal::AlwaysTrue()) {                        \\\n    statement;                                                    \\\n  } else                     /* NOLINT */                         \\\n    static_assert(true, \"\")  // User must have a semicolon after expansion.\n\n#if GTEST_HAS_EXCEPTIONS\n\nnamespace testing {\nnamespace internal {\n\nclass NeverThrown {\n public:\n  const char* what() const noexcept {\n    return \"this exception should never be thrown\";\n  }\n};\n\n}  // namespace internal\n}  // namespace testing\n\n#if GTEST_HAS_RTTI\n\n#define GTEST_EXCEPTION_TYPE_(e) ::testing::internal::GetTypeName(typeid(e))\n\n#else  // GTEST_HAS_RTTI\n\n#define GTEST_EXCEPTION_TYPE_(e) \\\n  std::string { \"an std::exception-derived error\" }\n\n#endif  // GTEST_HAS_RTTI\n\n#define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception)   \\\n  catch (typename std::conditional<                                            \\\n         std::is_same<typename std::remove_cv<typename std::remove_reference<  \\\n                          expected_exception>::type>::type,                    \\\n                      std::exception>::value,                                  \\\n         const ::testing::internal::NeverThrown&, const std::exception&>::type \\\n             e) {                                                              \\\n    gtest_msg.value = \"Expected: \" #statement                                  \\\n                      \" throws an exception of type \" #expected_exception      \\\n                      \".\\n  Actual: it throws \";                               \\\n    gtest_msg.value += GTEST_EXCEPTION_TYPE_(e);                               \\\n    gtest_msg.value += \" with description \\\"\";                                 \\\n    gtest_msg.value += e.what();                                               \\\n    gtest_msg.value += \"\\\".\";                                                  \\\n    goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__);                \\\n  }\n\n#else  // GTEST_HAS_EXCEPTIONS\n\n#define GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception)\n\n#endif  // GTEST_HAS_EXCEPTIONS\n\n#define GTEST_TEST_THROW_(statement, expected_exception, fail)              \\\n  GTEST_AMBIGUOUS_ELSE_BLOCKER_                                             \\\n  if (::testing::internal::TrueWithString gtest_msg{}) {                    \\\n    bool gtest_caught_expected = false;                                     \\\n    try {                                                                   \\\n      GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement);            \\\n    } catch (expected_exception const&) {                                   \\\n      gtest_caught_expected = true;                                         \\\n    }                                                                       \\\n    GTEST_TEST_THROW_CATCH_STD_EXCEPTION_(statement, expected_exception)    \\\n    catch (...) {                                                           \\\n      gtest_msg.value = \"Expected: \" #statement                             \\\n                        \" throws an exception of type \" #expected_exception \\\n                        \".\\n  Actual: it throws a different type.\";         \\\n      goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__);           \\\n    }                                                                       \\\n    if (!gtest_caught_expected) {                                           \\\n      gtest_msg.value = \"Expected: \" #statement                             \\\n                        \" throws an exception of type \" #expected_exception \\\n                        \".\\n  Actual: it throws nothing.\";                  \\\n      goto GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__);           \\\n    }                                                                       \\\n  } else /*NOLINT*/                                                         \\\n    GTEST_CONCAT_TOKEN_(gtest_label_testthrow_, __LINE__)                   \\\n        : fail(gtest_msg.value.c_str())\n\n#if GTEST_HAS_EXCEPTIONS\n\n#define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_()                \\\n  catch (std::exception const& e) {                               \\\n    gtest_msg.value = \"it throws \";                               \\\n    gtest_msg.value += GTEST_EXCEPTION_TYPE_(e);                  \\\n    gtest_msg.value += \" with description \\\"\";                    \\\n    gtest_msg.value += e.what();                                  \\\n    gtest_msg.value += \"\\\".\";                                     \\\n    goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__); \\\n  }\n\n#else  // GTEST_HAS_EXCEPTIONS\n\n#define GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_()\n\n#endif  // GTEST_HAS_EXCEPTIONS\n\n#define GTEST_TEST_NO_THROW_(statement, fail)                            \\\n  GTEST_AMBIGUOUS_ELSE_BLOCKER_                                          \\\n  if (::testing::internal::TrueWithString gtest_msg{}) {                 \\\n    try {                                                                \\\n      GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement);         \\\n    }                                                                    \\\n    GTEST_TEST_NO_THROW_CATCH_STD_EXCEPTION_()                           \\\n    catch (...) {                                                        \\\n      gtest_msg.value = \"it throws.\";                                    \\\n      goto GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__);      \\\n    }                                                                    \\\n  } else                                                                 \\\n    GTEST_CONCAT_TOKEN_(gtest_label_testnothrow_, __LINE__)              \\\n        : fail((\"Expected: \" #statement \" doesn't throw an exception.\\n\" \\\n                \"  Actual: \" +                                           \\\n                gtest_msg.value)                                         \\\n                   .c_str())\n\n#define GTEST_TEST_ANY_THROW_(statement, fail)                       \\\n  GTEST_AMBIGUOUS_ELSE_BLOCKER_                                      \\\n  if (::testing::internal::AlwaysTrue()) {                           \\\n    bool gtest_caught_any = false;                                   \\\n    try {                                                            \\\n      GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement);     \\\n    } catch (...) {                                                  \\\n      gtest_caught_any = true;                                       \\\n    }                                                                \\\n    if (!gtest_caught_any) {                                         \\\n      goto GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__); \\\n    }                                                                \\\n  } else                                                             \\\n    GTEST_CONCAT_TOKEN_(gtest_label_testanythrow_, __LINE__)         \\\n        : fail(\"Expected: \" #statement                               \\\n               \" throws an exception.\\n\"                             \\\n               \"  Actual: it doesn't.\")\n\n// Implements Boolean test assertions such as EXPECT_TRUE. expression can be\n// either a boolean expression or an AssertionResult. text is a textual\n// representation of expression as it was passed into the EXPECT_TRUE.\n#define GTEST_TEST_BOOLEAN_(expression, text, actual, expected, fail) \\\n  GTEST_AMBIGUOUS_ELSE_BLOCKER_                                       \\\n  if (const ::testing::AssertionResult gtest_ar_ =                    \\\n          ::testing::AssertionResult(expression))                     \\\n    ;                                                                 \\\n  else                                                                \\\n    fail(::testing::internal::GetBoolAssertionFailureMessage(         \\\n             gtest_ar_, text, #actual, #expected)                     \\\n             .c_str())\n\n#define GTEST_TEST_NO_FATAL_FAILURE_(statement, fail)                          \\\n  GTEST_AMBIGUOUS_ELSE_BLOCKER_                                                \\\n  if (::testing::internal::AlwaysTrue()) {                                     \\\n    ::testing::internal::HasNewFatalFailureHelper gtest_fatal_failure_checker; \\\n    GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement);                 \\\n    if (gtest_fatal_failure_checker.has_new_fatal_failure()) {                 \\\n      goto GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__);            \\\n    }                                                                          \\\n  } else                                                                       \\\n    GTEST_CONCAT_TOKEN_(gtest_label_testnofatal_, __LINE__)                    \\\n        : fail(\"Expected: \" #statement                                         \\\n               \" doesn't generate new fatal \"                                  \\\n               \"failures in the current thread.\\n\"                             \\\n               \"  Actual: it does.\")\n\n// Expands to the name of the class that implements the given test.\n#define GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) \\\n  test_suite_name##_##test_name##_Test\n\n// Helper macro for defining tests.\n#define GTEST_TEST_(test_suite_name, test_name, parent_class, parent_id)       \\\n  static_assert(sizeof(GTEST_STRINGIFY_(test_suite_name)) > 1,                 \\\n                \"test_suite_name must not be empty\");                          \\\n  static_assert(sizeof(GTEST_STRINGIFY_(test_name)) > 1,                       \\\n                \"test_name must not be empty\");                                \\\n  class GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)                     \\\n      : public parent_class {                                                  \\\n   public:                                                                     \\\n    GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() = default;            \\\n    ~GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)() override = default;  \\\n    GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)                         \\\n    (const GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) &) = delete;     \\\n    GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) & operator=(            \\\n        const GTEST_TEST_CLASS_NAME_(test_suite_name,                          \\\n                                     test_name) &) = delete; /* NOLINT */      \\\n    GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)                         \\\n    (GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) &&) noexcept = delete; \\\n    GTEST_TEST_CLASS_NAME_(test_suite_name, test_name) & operator=(            \\\n        GTEST_TEST_CLASS_NAME_(test_suite_name,                                \\\n                               test_name) &&) noexcept = delete; /* NOLINT */  \\\n                                                                               \\\n   private:                                                                    \\\n    void TestBody() override;                                                  \\\n    static ::testing::TestInfo* const test_info_ GTEST_ATTRIBUTE_UNUSED_;      \\\n  };                                                                           \\\n                                                                               \\\n  ::testing::TestInfo* const GTEST_TEST_CLASS_NAME_(test_suite_name,           \\\n                                                    test_name)::test_info_ =   \\\n      ::testing::internal::MakeAndRegisterTestInfo(                            \\\n          #test_suite_name, #test_name, nullptr, nullptr,                      \\\n          ::testing::internal::CodeLocation(__FILE__, __LINE__), (parent_id),  \\\n          ::testing::internal::SuiteApiResolver<                               \\\n              parent_class>::GetSetUpCaseOrSuite(__FILE__, __LINE__),          \\\n          ::testing::internal::SuiteApiResolver<                               \\\n              parent_class>::GetTearDownCaseOrSuite(__FILE__, __LINE__),       \\\n          new ::testing::internal::TestFactoryImpl<GTEST_TEST_CLASS_NAME_(     \\\n              test_suite_name, test_name)>);                                   \\\n  void GTEST_TEST_CLASS_NAME_(test_suite_name, test_name)::TestBody()\n\n#endif  // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_INTERNAL_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/include/gtest/internal/gtest-param-util.h",
    "content": "// Copyright 2008 Google Inc.\n// All Rights Reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Type and function utilities for implementing parameterized tests.\n\n// IWYU pragma: private, include \"gtest/gtest.h\"\n// IWYU pragma: friend gtest/.*\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_\n#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_\n\n#include <ctype.h>\n\n#include <cassert>\n#include <iterator>\n#include <memory>\n#include <set>\n#include <tuple>\n#include <type_traits>\n#include <utility>\n#include <vector>\n\n#include \"gtest/gtest-printers.h\"\n#include \"gtest/gtest-test-part.h\"\n#include \"gtest/internal/gtest-internal.h\"\n#include \"gtest/internal/gtest-port.h\"\n\nnamespace testing {\n// Input to a parameterized test name generator, describing a test parameter.\n// Consists of the parameter value and the integer parameter index.\ntemplate <class ParamType>\nstruct TestParamInfo {\n  TestParamInfo(const ParamType& a_param, size_t an_index)\n      : param(a_param), index(an_index) {}\n  ParamType param;\n  size_t index;\n};\n\n// A builtin parameterized test name generator which returns the result of\n// testing::PrintToString.\nstruct PrintToStringParamName {\n  template <class ParamType>\n  std::string operator()(const TestParamInfo<ParamType>& info) const {\n    return PrintToString(info.param);\n  }\n};\n\nnamespace internal {\n\n// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.\n// Utility Functions\n\n// Outputs a message explaining invalid registration of different\n// fixture class for the same test suite. This may happen when\n// TEST_P macro is used to define two tests with the same name\n// but in different namespaces.\nGTEST_API_ void ReportInvalidTestSuiteType(const char* test_suite_name,\n                                           CodeLocation code_location);\n\ntemplate <typename>\nclass ParamGeneratorInterface;\ntemplate <typename>\nclass ParamGenerator;\n\n// Interface for iterating over elements provided by an implementation\n// of ParamGeneratorInterface<T>.\ntemplate <typename T>\nclass ParamIteratorInterface {\n public:\n  virtual ~ParamIteratorInterface() {}\n  // A pointer to the base generator instance.\n  // Used only for the purposes of iterator comparison\n  // to make sure that two iterators belong to the same generator.\n  virtual const ParamGeneratorInterface<T>* BaseGenerator() const = 0;\n  // Advances iterator to point to the next element\n  // provided by the generator. The caller is responsible\n  // for not calling Advance() on an iterator equal to\n  // BaseGenerator()->End().\n  virtual void Advance() = 0;\n  // Clones the iterator object. Used for implementing copy semantics\n  // of ParamIterator<T>.\n  virtual ParamIteratorInterface* Clone() const = 0;\n  // Dereferences the current iterator and provides (read-only) access\n  // to the pointed value. It is the caller's responsibility not to call\n  // Current() on an iterator equal to BaseGenerator()->End().\n  // Used for implementing ParamGenerator<T>::operator*().\n  virtual const T* Current() const = 0;\n  // Determines whether the given iterator and other point to the same\n  // element in the sequence generated by the generator.\n  // Used for implementing ParamGenerator<T>::operator==().\n  virtual bool Equals(const ParamIteratorInterface& other) const = 0;\n};\n\n// Class iterating over elements provided by an implementation of\n// ParamGeneratorInterface<T>. It wraps ParamIteratorInterface<T>\n// and implements the const forward iterator concept.\ntemplate <typename T>\nclass ParamIterator {\n public:\n  typedef T value_type;\n  typedef const T& reference;\n  typedef ptrdiff_t difference_type;\n\n  // ParamIterator assumes ownership of the impl_ pointer.\n  ParamIterator(const ParamIterator& other) : impl_(other.impl_->Clone()) {}\n  ParamIterator& operator=(const ParamIterator& other) {\n    if (this != &other) impl_.reset(other.impl_->Clone());\n    return *this;\n  }\n\n  const T& operator*() const { return *impl_->Current(); }\n  const T* operator->() const { return impl_->Current(); }\n  // Prefix version of operator++.\n  ParamIterator& operator++() {\n    impl_->Advance();\n    return *this;\n  }\n  // Postfix version of operator++.\n  ParamIterator operator++(int /*unused*/) {\n    ParamIteratorInterface<T>* clone = impl_->Clone();\n    impl_->Advance();\n    return ParamIterator(clone);\n  }\n  bool operator==(const ParamIterator& other) const {\n    return impl_.get() == other.impl_.get() || impl_->Equals(*other.impl_);\n  }\n  bool operator!=(const ParamIterator& other) const {\n    return !(*this == other);\n  }\n\n private:\n  friend class ParamGenerator<T>;\n  explicit ParamIterator(ParamIteratorInterface<T>* impl) : impl_(impl) {}\n  std::unique_ptr<ParamIteratorInterface<T>> impl_;\n};\n\n// ParamGeneratorInterface<T> is the binary interface to access generators\n// defined in other translation units.\ntemplate <typename T>\nclass ParamGeneratorInterface {\n public:\n  typedef T ParamType;\n\n  virtual ~ParamGeneratorInterface() {}\n\n  // Generator interface definition\n  virtual ParamIteratorInterface<T>* Begin() const = 0;\n  virtual ParamIteratorInterface<T>* End() const = 0;\n};\n\n// Wraps ParamGeneratorInterface<T> and provides general generator syntax\n// compatible with the STL Container concept.\n// This class implements copy initialization semantics and the contained\n// ParamGeneratorInterface<T> instance is shared among all copies\n// of the original object. This is possible because that instance is immutable.\ntemplate <typename T>\nclass ParamGenerator {\n public:\n  typedef ParamIterator<T> iterator;\n\n  explicit ParamGenerator(ParamGeneratorInterface<T>* impl) : impl_(impl) {}\n  ParamGenerator(const ParamGenerator& other) : impl_(other.impl_) {}\n\n  ParamGenerator& operator=(const ParamGenerator& other) {\n    impl_ = other.impl_;\n    return *this;\n  }\n\n  iterator begin() const { return iterator(impl_->Begin()); }\n  iterator end() const { return iterator(impl_->End()); }\n\n private:\n  std::shared_ptr<const ParamGeneratorInterface<T>> impl_;\n};\n\n// Generates values from a range of two comparable values. Can be used to\n// generate sequences of user-defined types that implement operator+() and\n// operator<().\n// This class is used in the Range() function.\ntemplate <typename T, typename IncrementT>\nclass RangeGenerator : public ParamGeneratorInterface<T> {\n public:\n  RangeGenerator(T begin, T end, IncrementT step)\n      : begin_(begin),\n        end_(end),\n        step_(step),\n        end_index_(CalculateEndIndex(begin, end, step)) {}\n  ~RangeGenerator() override {}\n\n  ParamIteratorInterface<T>* Begin() const override {\n    return new Iterator(this, begin_, 0, step_);\n  }\n  ParamIteratorInterface<T>* End() const override {\n    return new Iterator(this, end_, end_index_, step_);\n  }\n\n private:\n  class Iterator : public ParamIteratorInterface<T> {\n   public:\n    Iterator(const ParamGeneratorInterface<T>* base, T value, int index,\n             IncrementT step)\n        : base_(base), value_(value), index_(index), step_(step) {}\n    ~Iterator() override {}\n\n    const ParamGeneratorInterface<T>* BaseGenerator() const override {\n      return base_;\n    }\n    void Advance() override {\n      value_ = static_cast<T>(value_ + step_);\n      index_++;\n    }\n    ParamIteratorInterface<T>* Clone() const override {\n      return new Iterator(*this);\n    }\n    const T* Current() const override { return &value_; }\n    bool Equals(const ParamIteratorInterface<T>& other) const override {\n      // Having the same base generator guarantees that the other\n      // iterator is of the same type and we can downcast.\n      GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())\n          << \"The program attempted to compare iterators \"\n          << \"from different generators.\" << std::endl;\n      const int other_index =\n          CheckedDowncastToActualType<const Iterator>(&other)->index_;\n      return index_ == other_index;\n    }\n\n   private:\n    Iterator(const Iterator& other)\n        : ParamIteratorInterface<T>(),\n          base_(other.base_),\n          value_(other.value_),\n          index_(other.index_),\n          step_(other.step_) {}\n\n    // No implementation - assignment is unsupported.\n    void operator=(const Iterator& other);\n\n    const ParamGeneratorInterface<T>* const base_;\n    T value_;\n    int index_;\n    const IncrementT step_;\n  };  // class RangeGenerator::Iterator\n\n  static int CalculateEndIndex(const T& begin, const T& end,\n                               const IncrementT& step) {\n    int end_index = 0;\n    for (T i = begin; i < end; i = static_cast<T>(i + step)) end_index++;\n    return end_index;\n  }\n\n  // No implementation - assignment is unsupported.\n  void operator=(const RangeGenerator& other);\n\n  const T begin_;\n  const T end_;\n  const IncrementT step_;\n  // The index for the end() iterator. All the elements in the generated\n  // sequence are indexed (0-based) to aid iterator comparison.\n  const int end_index_;\n};  // class RangeGenerator\n\n// Generates values from a pair of STL-style iterators. Used in the\n// ValuesIn() function. The elements are copied from the source range\n// since the source can be located on the stack, and the generator\n// is likely to persist beyond that stack frame.\ntemplate <typename T>\nclass ValuesInIteratorRangeGenerator : public ParamGeneratorInterface<T> {\n public:\n  template <typename ForwardIterator>\n  ValuesInIteratorRangeGenerator(ForwardIterator begin, ForwardIterator end)\n      : container_(begin, end) {}\n  ~ValuesInIteratorRangeGenerator() override {}\n\n  ParamIteratorInterface<T>* Begin() const override {\n    return new Iterator(this, container_.begin());\n  }\n  ParamIteratorInterface<T>* End() const override {\n    return new Iterator(this, container_.end());\n  }\n\n private:\n  typedef typename ::std::vector<T> ContainerType;\n\n  class Iterator : public ParamIteratorInterface<T> {\n   public:\n    Iterator(const ParamGeneratorInterface<T>* base,\n             typename ContainerType::const_iterator iterator)\n        : base_(base), iterator_(iterator) {}\n    ~Iterator() override {}\n\n    const ParamGeneratorInterface<T>* BaseGenerator() const override {\n      return base_;\n    }\n    void Advance() override {\n      ++iterator_;\n      value_.reset();\n    }\n    ParamIteratorInterface<T>* Clone() const override {\n      return new Iterator(*this);\n    }\n    // We need to use cached value referenced by iterator_ because *iterator_\n    // can return a temporary object (and of type other then T), so just\n    // having \"return &*iterator_;\" doesn't work.\n    // value_ is updated here and not in Advance() because Advance()\n    // can advance iterator_ beyond the end of the range, and we cannot\n    // detect that fact. The client code, on the other hand, is\n    // responsible for not calling Current() on an out-of-range iterator.\n    const T* Current() const override {\n      if (value_.get() == nullptr) value_.reset(new T(*iterator_));\n      return value_.get();\n    }\n    bool Equals(const ParamIteratorInterface<T>& other) const override {\n      // Having the same base generator guarantees that the other\n      // iterator is of the same type and we can downcast.\n      GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())\n          << \"The program attempted to compare iterators \"\n          << \"from different generators.\" << std::endl;\n      return iterator_ ==\n             CheckedDowncastToActualType<const Iterator>(&other)->iterator_;\n    }\n\n   private:\n    Iterator(const Iterator& other)\n        // The explicit constructor call suppresses a false warning\n        // emitted by gcc when supplied with the -Wextra option.\n        : ParamIteratorInterface<T>(),\n          base_(other.base_),\n          iterator_(other.iterator_) {}\n\n    const ParamGeneratorInterface<T>* const base_;\n    typename ContainerType::const_iterator iterator_;\n    // A cached value of *iterator_. We keep it here to allow access by\n    // pointer in the wrapping iterator's operator->().\n    // value_ needs to be mutable to be accessed in Current().\n    // Use of std::unique_ptr helps manage cached value's lifetime,\n    // which is bound by the lifespan of the iterator itself.\n    mutable std::unique_ptr<const T> value_;\n  };  // class ValuesInIteratorRangeGenerator::Iterator\n\n  // No implementation - assignment is unsupported.\n  void operator=(const ValuesInIteratorRangeGenerator& other);\n\n  const ContainerType container_;\n};  // class ValuesInIteratorRangeGenerator\n\n// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.\n//\n// Default parameterized test name generator, returns a string containing the\n// integer test parameter index.\ntemplate <class ParamType>\nstd::string DefaultParamName(const TestParamInfo<ParamType>& info) {\n  Message name_stream;\n  name_stream << info.index;\n  return name_stream.GetString();\n}\n\ntemplate <typename T = int>\nvoid TestNotEmpty() {\n  static_assert(sizeof(T) == 0, \"Empty arguments are not allowed.\");\n}\ntemplate <typename T = int>\nvoid TestNotEmpty(const T&) {}\n\n// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.\n//\n// Stores a parameter value and later creates tests parameterized with that\n// value.\ntemplate <class TestClass>\nclass ParameterizedTestFactory : public TestFactoryBase {\n public:\n  typedef typename TestClass::ParamType ParamType;\n  explicit ParameterizedTestFactory(ParamType parameter)\n      : parameter_(parameter) {}\n  Test* CreateTest() override {\n    TestClass::SetParam(&parameter_);\n    return new TestClass();\n  }\n\n private:\n  const ParamType parameter_;\n\n  ParameterizedTestFactory(const ParameterizedTestFactory&) = delete;\n  ParameterizedTestFactory& operator=(const ParameterizedTestFactory&) = delete;\n};\n\n// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.\n//\n// TestMetaFactoryBase is a base class for meta-factories that create\n// test factories for passing into MakeAndRegisterTestInfo function.\ntemplate <class ParamType>\nclass TestMetaFactoryBase {\n public:\n  virtual ~TestMetaFactoryBase() {}\n\n  virtual TestFactoryBase* CreateTestFactory(ParamType parameter) = 0;\n};\n\n// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.\n//\n// TestMetaFactory creates test factories for passing into\n// MakeAndRegisterTestInfo function. Since MakeAndRegisterTestInfo receives\n// ownership of test factory pointer, same factory object cannot be passed\n// into that method twice. But ParameterizedTestSuiteInfo is going to call\n// it for each Test/Parameter value combination. Thus it needs meta factory\n// creator class.\ntemplate <class TestSuite>\nclass TestMetaFactory\n    : public TestMetaFactoryBase<typename TestSuite::ParamType> {\n public:\n  using ParamType = typename TestSuite::ParamType;\n\n  TestMetaFactory() {}\n\n  TestFactoryBase* CreateTestFactory(ParamType parameter) override {\n    return new ParameterizedTestFactory<TestSuite>(parameter);\n  }\n\n private:\n  TestMetaFactory(const TestMetaFactory&) = delete;\n  TestMetaFactory& operator=(const TestMetaFactory&) = delete;\n};\n\n// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.\n//\n// ParameterizedTestSuiteInfoBase is a generic interface\n// to ParameterizedTestSuiteInfo classes. ParameterizedTestSuiteInfoBase\n// accumulates test information provided by TEST_P macro invocations\n// and generators provided by INSTANTIATE_TEST_SUITE_P macro invocations\n// and uses that information to register all resulting test instances\n// in RegisterTests method. The ParameterizeTestSuiteRegistry class holds\n// a collection of pointers to the ParameterizedTestSuiteInfo objects\n// and calls RegisterTests() on each of them when asked.\nclass ParameterizedTestSuiteInfoBase {\n public:\n  virtual ~ParameterizedTestSuiteInfoBase() {}\n\n  // Base part of test suite name for display purposes.\n  virtual const std::string& GetTestSuiteName() const = 0;\n  // Test suite id to verify identity.\n  virtual TypeId GetTestSuiteTypeId() const = 0;\n  // UnitTest class invokes this method to register tests in this\n  // test suite right before running them in RUN_ALL_TESTS macro.\n  // This method should not be called more than once on any single\n  // instance of a ParameterizedTestSuiteInfoBase derived class.\n  virtual void RegisterTests() = 0;\n\n protected:\n  ParameterizedTestSuiteInfoBase() {}\n\n private:\n  ParameterizedTestSuiteInfoBase(const ParameterizedTestSuiteInfoBase&) =\n      delete;\n  ParameterizedTestSuiteInfoBase& operator=(\n      const ParameterizedTestSuiteInfoBase&) = delete;\n};\n\n// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.\n//\n// Report a the name of a test_suit as safe to ignore\n// as the side effect of construction of this type.\nstruct GTEST_API_ MarkAsIgnored {\n  explicit MarkAsIgnored(const char* test_suite);\n};\n\nGTEST_API_ void InsertSyntheticTestCase(const std::string& name,\n                                        CodeLocation location, bool has_test_p);\n\n// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.\n//\n// ParameterizedTestSuiteInfo accumulates tests obtained from TEST_P\n// macro invocations for a particular test suite and generators\n// obtained from INSTANTIATE_TEST_SUITE_P macro invocations for that\n// test suite. It registers tests with all values generated by all\n// generators when asked.\ntemplate <class TestSuite>\nclass ParameterizedTestSuiteInfo : public ParameterizedTestSuiteInfoBase {\n public:\n  // ParamType and GeneratorCreationFunc are private types but are required\n  // for declarations of public methods AddTestPattern() and\n  // AddTestSuiteInstantiation().\n  using ParamType = typename TestSuite::ParamType;\n  // A function that returns an instance of appropriate generator type.\n  typedef ParamGenerator<ParamType>(GeneratorCreationFunc)();\n  using ParamNameGeneratorFunc = std::string(const TestParamInfo<ParamType>&);\n\n  explicit ParameterizedTestSuiteInfo(const char* name,\n                                      CodeLocation code_location)\n      : test_suite_name_(name), code_location_(code_location) {}\n\n  // Test suite base name for display purposes.\n  const std::string& GetTestSuiteName() const override {\n    return test_suite_name_;\n  }\n  // Test suite id to verify identity.\n  TypeId GetTestSuiteTypeId() const override { return GetTypeId<TestSuite>(); }\n  // TEST_P macro uses AddTestPattern() to record information\n  // about a single test in a LocalTestInfo structure.\n  // test_suite_name is the base name of the test suite (without invocation\n  // prefix). test_base_name is the name of an individual test without\n  // parameter index. For the test SequenceA/FooTest.DoBar/1 FooTest is\n  // test suite base name and DoBar is test base name.\n  void AddTestPattern(const char* test_suite_name, const char* test_base_name,\n                      TestMetaFactoryBase<ParamType>* meta_factory,\n                      CodeLocation code_location) {\n    tests_.push_back(std::shared_ptr<TestInfo>(new TestInfo(\n        test_suite_name, test_base_name, meta_factory, code_location)));\n  }\n  // INSTANTIATE_TEST_SUITE_P macro uses AddGenerator() to record information\n  // about a generator.\n  int AddTestSuiteInstantiation(const std::string& instantiation_name,\n                                GeneratorCreationFunc* func,\n                                ParamNameGeneratorFunc* name_func,\n                                const char* file, int line) {\n    instantiations_.push_back(\n        InstantiationInfo(instantiation_name, func, name_func, file, line));\n    return 0;  // Return value used only to run this method in namespace scope.\n  }\n  // UnitTest class invokes this method to register tests in this test suite\n  // right before running tests in RUN_ALL_TESTS macro.\n  // This method should not be called more than once on any single\n  // instance of a ParameterizedTestSuiteInfoBase derived class.\n  // UnitTest has a guard to prevent from calling this method more than once.\n  void RegisterTests() override {\n    bool generated_instantiations = false;\n\n    for (typename TestInfoContainer::iterator test_it = tests_.begin();\n         test_it != tests_.end(); ++test_it) {\n      std::shared_ptr<TestInfo> test_info = *test_it;\n      for (typename InstantiationContainer::iterator gen_it =\n               instantiations_.begin();\n           gen_it != instantiations_.end(); ++gen_it) {\n        const std::string& instantiation_name = gen_it->name;\n        ParamGenerator<ParamType> generator((*gen_it->generator)());\n        ParamNameGeneratorFunc* name_func = gen_it->name_func;\n        const char* file = gen_it->file;\n        int line = gen_it->line;\n\n        std::string test_suite_name;\n        if (!instantiation_name.empty())\n          test_suite_name = instantiation_name + \"/\";\n        test_suite_name += test_info->test_suite_base_name;\n\n        size_t i = 0;\n        std::set<std::string> test_param_names;\n        for (typename ParamGenerator<ParamType>::iterator param_it =\n                 generator.begin();\n             param_it != generator.end(); ++param_it, ++i) {\n          generated_instantiations = true;\n\n          Message test_name_stream;\n\n          std::string param_name =\n              name_func(TestParamInfo<ParamType>(*param_it, i));\n\n          GTEST_CHECK_(IsValidParamName(param_name))\n              << \"Parameterized test name '\" << param_name\n              << \"' is invalid, in \" << file << \" line \" << line << std::endl;\n\n          GTEST_CHECK_(test_param_names.count(param_name) == 0)\n              << \"Duplicate parameterized test name '\" << param_name << \"', in \"\n              << file << \" line \" << line << std::endl;\n\n          test_param_names.insert(param_name);\n\n          if (!test_info->test_base_name.empty()) {\n            test_name_stream << test_info->test_base_name << \"/\";\n          }\n          test_name_stream << param_name;\n          MakeAndRegisterTestInfo(\n              test_suite_name.c_str(), test_name_stream.GetString().c_str(),\n              nullptr,  // No type parameter.\n              PrintToString(*param_it).c_str(), test_info->code_location,\n              GetTestSuiteTypeId(),\n              SuiteApiResolver<TestSuite>::GetSetUpCaseOrSuite(file, line),\n              SuiteApiResolver<TestSuite>::GetTearDownCaseOrSuite(file, line),\n              test_info->test_meta_factory->CreateTestFactory(*param_it));\n        }  // for param_it\n      }    // for gen_it\n    }      // for test_it\n\n    if (!generated_instantiations) {\n      // There are no generaotrs, or they all generate nothing ...\n      InsertSyntheticTestCase(GetTestSuiteName(), code_location_,\n                              !tests_.empty());\n    }\n  }  // RegisterTests\n\n private:\n  // LocalTestInfo structure keeps information about a single test registered\n  // with TEST_P macro.\n  struct TestInfo {\n    TestInfo(const char* a_test_suite_base_name, const char* a_test_base_name,\n             TestMetaFactoryBase<ParamType>* a_test_meta_factory,\n             CodeLocation a_code_location)\n        : test_suite_base_name(a_test_suite_base_name),\n          test_base_name(a_test_base_name),\n          test_meta_factory(a_test_meta_factory),\n          code_location(a_code_location) {}\n\n    const std::string test_suite_base_name;\n    const std::string test_base_name;\n    const std::unique_ptr<TestMetaFactoryBase<ParamType>> test_meta_factory;\n    const CodeLocation code_location;\n  };\n  using TestInfoContainer = ::std::vector<std::shared_ptr<TestInfo>>;\n  // Records data received from INSTANTIATE_TEST_SUITE_P macros:\n  //  <Instantiation name, Sequence generator creation function,\n  //     Name generator function, Source file, Source line>\n  struct InstantiationInfo {\n    InstantiationInfo(const std::string& name_in,\n                      GeneratorCreationFunc* generator_in,\n                      ParamNameGeneratorFunc* name_func_in, const char* file_in,\n                      int line_in)\n        : name(name_in),\n          generator(generator_in),\n          name_func(name_func_in),\n          file(file_in),\n          line(line_in) {}\n\n    std::string name;\n    GeneratorCreationFunc* generator;\n    ParamNameGeneratorFunc* name_func;\n    const char* file;\n    int line;\n  };\n  typedef ::std::vector<InstantiationInfo> InstantiationContainer;\n\n  static bool IsValidParamName(const std::string& name) {\n    // Check for empty string\n    if (name.empty()) return false;\n\n    // Check for invalid characters\n    for (std::string::size_type index = 0; index < name.size(); ++index) {\n      if (!IsAlNum(name[index]) && name[index] != '_') return false;\n    }\n\n    return true;\n  }\n\n  const std::string test_suite_name_;\n  CodeLocation code_location_;\n  TestInfoContainer tests_;\n  InstantiationContainer instantiations_;\n\n  ParameterizedTestSuiteInfo(const ParameterizedTestSuiteInfo&) = delete;\n  ParameterizedTestSuiteInfo& operator=(const ParameterizedTestSuiteInfo&) =\n      delete;\n};  // class ParameterizedTestSuiteInfo\n\n//  Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\ntemplate <class TestCase>\nusing ParameterizedTestCaseInfo = ParameterizedTestSuiteInfo<TestCase>;\n#endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.\n//\n// ParameterizedTestSuiteRegistry contains a map of\n// ParameterizedTestSuiteInfoBase classes accessed by test suite names. TEST_P\n// and INSTANTIATE_TEST_SUITE_P macros use it to locate their corresponding\n// ParameterizedTestSuiteInfo descriptors.\nclass ParameterizedTestSuiteRegistry {\n public:\n  ParameterizedTestSuiteRegistry() {}\n  ~ParameterizedTestSuiteRegistry() {\n    for (auto& test_suite_info : test_suite_infos_) {\n      delete test_suite_info;\n    }\n  }\n\n  // Looks up or creates and returns a structure containing information about\n  // tests and instantiations of a particular test suite.\n  template <class TestSuite>\n  ParameterizedTestSuiteInfo<TestSuite>* GetTestSuitePatternHolder(\n      const char* test_suite_name, CodeLocation code_location) {\n    ParameterizedTestSuiteInfo<TestSuite>* typed_test_info = nullptr;\n    for (auto& test_suite_info : test_suite_infos_) {\n      if (test_suite_info->GetTestSuiteName() == test_suite_name) {\n        if (test_suite_info->GetTestSuiteTypeId() != GetTypeId<TestSuite>()) {\n          // Complain about incorrect usage of Google Test facilities\n          // and terminate the program since we cannot guaranty correct\n          // test suite setup and tear-down in this case.\n          ReportInvalidTestSuiteType(test_suite_name, code_location);\n          posix::Abort();\n        } else {\n          // At this point we are sure that the object we found is of the same\n          // type we are looking for, so we downcast it to that type\n          // without further checks.\n          typed_test_info = CheckedDowncastToActualType<\n              ParameterizedTestSuiteInfo<TestSuite>>(test_suite_info);\n        }\n        break;\n      }\n    }\n    if (typed_test_info == nullptr) {\n      typed_test_info = new ParameterizedTestSuiteInfo<TestSuite>(\n          test_suite_name, code_location);\n      test_suite_infos_.push_back(typed_test_info);\n    }\n    return typed_test_info;\n  }\n  void RegisterTests() {\n    for (auto& test_suite_info : test_suite_infos_) {\n      test_suite_info->RegisterTests();\n    }\n  }\n//  Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  template <class TestCase>\n  ParameterizedTestCaseInfo<TestCase>* GetTestCasePatternHolder(\n      const char* test_case_name, CodeLocation code_location) {\n    return GetTestSuitePatternHolder<TestCase>(test_case_name, code_location);\n  }\n\n#endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n private:\n  using TestSuiteInfoContainer = ::std::vector<ParameterizedTestSuiteInfoBase*>;\n\n  TestSuiteInfoContainer test_suite_infos_;\n\n  ParameterizedTestSuiteRegistry(const ParameterizedTestSuiteRegistry&) =\n      delete;\n  ParameterizedTestSuiteRegistry& operator=(\n      const ParameterizedTestSuiteRegistry&) = delete;\n};\n\n// Keep track of what type-parameterized test suite are defined and\n// where as well as which are intatiated. This allows susequently\n// identifying suits that are defined but never used.\nclass TypeParameterizedTestSuiteRegistry {\n public:\n  // Add a suite definition\n  void RegisterTestSuite(const char* test_suite_name,\n                         CodeLocation code_location);\n\n  // Add an instantiation of a suit.\n  void RegisterInstantiation(const char* test_suite_name);\n\n  // For each suit repored as defined but not reported as instantiation,\n  // emit a test that reports that fact (configurably, as an error).\n  void CheckForInstantiations();\n\n private:\n  struct TypeParameterizedTestSuiteInfo {\n    explicit TypeParameterizedTestSuiteInfo(CodeLocation c)\n        : code_location(c), instantiated(false) {}\n\n    CodeLocation code_location;\n    bool instantiated;\n  };\n\n  std::map<std::string, TypeParameterizedTestSuiteInfo> suites_;\n};\n\n}  // namespace internal\n\n// Forward declarations of ValuesIn(), which is implemented in\n// include/gtest/gtest-param-test.h.\ntemplate <class Container>\ninternal::ParamGenerator<typename Container::value_type> ValuesIn(\n    const Container& container);\n\nnamespace internal {\n// Used in the Values() function to provide polymorphic capabilities.\n\n#ifdef _MSC_VER\n#pragma warning(push)\n#pragma warning(disable : 4100)\n#endif\n\ntemplate <typename... Ts>\nclass ValueArray {\n public:\n  explicit ValueArray(Ts... v) : v_(FlatTupleConstructTag{}, std::move(v)...) {}\n\n  template <typename T>\n  operator ParamGenerator<T>() const {  // NOLINT\n    return ValuesIn(MakeVector<T>(MakeIndexSequence<sizeof...(Ts)>()));\n  }\n\n private:\n  template <typename T, size_t... I>\n  std::vector<T> MakeVector(IndexSequence<I...>) const {\n    return std::vector<T>{static_cast<T>(v_.template Get<I>())...};\n  }\n\n  FlatTuple<Ts...> v_;\n};\n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\ntemplate <typename... T>\nclass CartesianProductGenerator\n    : public ParamGeneratorInterface<::std::tuple<T...>> {\n public:\n  typedef ::std::tuple<T...> ParamType;\n\n  CartesianProductGenerator(const std::tuple<ParamGenerator<T>...>& g)\n      : generators_(g) {}\n  ~CartesianProductGenerator() override {}\n\n  ParamIteratorInterface<ParamType>* Begin() const override {\n    return new Iterator(this, generators_, false);\n  }\n  ParamIteratorInterface<ParamType>* End() const override {\n    return new Iterator(this, generators_, true);\n  }\n\n private:\n  template <class I>\n  class IteratorImpl;\n  template <size_t... I>\n  class IteratorImpl<IndexSequence<I...>>\n      : public ParamIteratorInterface<ParamType> {\n   public:\n    IteratorImpl(const ParamGeneratorInterface<ParamType>* base,\n                 const std::tuple<ParamGenerator<T>...>& generators,\n                 bool is_end)\n        : base_(base),\n          begin_(std::get<I>(generators).begin()...),\n          end_(std::get<I>(generators).end()...),\n          current_(is_end ? end_ : begin_) {\n      ComputeCurrentValue();\n    }\n    ~IteratorImpl() override {}\n\n    const ParamGeneratorInterface<ParamType>* BaseGenerator() const override {\n      return base_;\n    }\n    // Advance should not be called on beyond-of-range iterators\n    // so no component iterators must be beyond end of range, either.\n    void Advance() override {\n      assert(!AtEnd());\n      // Advance the last iterator.\n      ++std::get<sizeof...(T) - 1>(current_);\n      // if that reaches end, propagate that up.\n      AdvanceIfEnd<sizeof...(T) - 1>();\n      ComputeCurrentValue();\n    }\n    ParamIteratorInterface<ParamType>* Clone() const override {\n      return new IteratorImpl(*this);\n    }\n\n    const ParamType* Current() const override { return current_value_.get(); }\n\n    bool Equals(const ParamIteratorInterface<ParamType>& other) const override {\n      // Having the same base generator guarantees that the other\n      // iterator is of the same type and we can downcast.\n      GTEST_CHECK_(BaseGenerator() == other.BaseGenerator())\n          << \"The program attempted to compare iterators \"\n          << \"from different generators.\" << std::endl;\n      const IteratorImpl* typed_other =\n          CheckedDowncastToActualType<const IteratorImpl>(&other);\n\n      // We must report iterators equal if they both point beyond their\n      // respective ranges. That can happen in a variety of fashions,\n      // so we have to consult AtEnd().\n      if (AtEnd() && typed_other->AtEnd()) return true;\n\n      bool same = true;\n      bool dummy[] = {\n          (same = same && std::get<I>(current_) ==\n                              std::get<I>(typed_other->current_))...};\n      (void)dummy;\n      return same;\n    }\n\n   private:\n    template <size_t ThisI>\n    void AdvanceIfEnd() {\n      if (std::get<ThisI>(current_) != std::get<ThisI>(end_)) return;\n\n      bool last = ThisI == 0;\n      if (last) {\n        // We are done. Nothing else to propagate.\n        return;\n      }\n\n      constexpr size_t NextI = ThisI - (ThisI != 0);\n      std::get<ThisI>(current_) = std::get<ThisI>(begin_);\n      ++std::get<NextI>(current_);\n      AdvanceIfEnd<NextI>();\n    }\n\n    void ComputeCurrentValue() {\n      if (!AtEnd())\n        current_value_ = std::make_shared<ParamType>(*std::get<I>(current_)...);\n    }\n    bool AtEnd() const {\n      bool at_end = false;\n      bool dummy[] = {\n          (at_end = at_end || std::get<I>(current_) == std::get<I>(end_))...};\n      (void)dummy;\n      return at_end;\n    }\n\n    const ParamGeneratorInterface<ParamType>* const base_;\n    std::tuple<typename ParamGenerator<T>::iterator...> begin_;\n    std::tuple<typename ParamGenerator<T>::iterator...> end_;\n    std::tuple<typename ParamGenerator<T>::iterator...> current_;\n    std::shared_ptr<ParamType> current_value_;\n  };\n\n  using Iterator = IteratorImpl<typename MakeIndexSequence<sizeof...(T)>::type>;\n\n  std::tuple<ParamGenerator<T>...> generators_;\n};\n\ntemplate <class... Gen>\nclass CartesianProductHolder {\n public:\n  CartesianProductHolder(const Gen&... g) : generators_(g...) {}\n  template <typename... T>\n  operator ParamGenerator<::std::tuple<T...>>() const {\n    return ParamGenerator<::std::tuple<T...>>(\n        new CartesianProductGenerator<T...>(generators_));\n  }\n\n private:\n  std::tuple<Gen...> generators_;\n};\n\n}  // namespace internal\n}  // namespace testing\n\n#endif  // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PARAM_UTIL_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/include/gtest/internal/gtest-port-arch.h",
    "content": "// Copyright 2015, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// The Google C++ Testing and Mocking Framework (Google Test)\n//\n// This header file defines the GTEST_OS_* macro.\n// It is separate from gtest-port.h so that custom/gtest-port.h can include it.\n\n#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_\n#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_\n\n// Determines the platform on which Google Test is compiled.\n#ifdef __CYGWIN__\n#define GTEST_OS_CYGWIN 1\n#elif defined(__MINGW__) || defined(__MINGW32__) || defined(__MINGW64__)\n#define GTEST_OS_WINDOWS_MINGW 1\n#define GTEST_OS_WINDOWS 1\n#elif defined _WIN32\n#define GTEST_OS_WINDOWS 1\n#ifdef _WIN32_WCE\n#define GTEST_OS_WINDOWS_MOBILE 1\n#elif defined(WINAPI_FAMILY)\n#include <winapifamily.h>\n#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)\n#define GTEST_OS_WINDOWS_DESKTOP 1\n#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP)\n#define GTEST_OS_WINDOWS_PHONE 1\n#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)\n#define GTEST_OS_WINDOWS_RT 1\n#elif WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_TV_TITLE)\n#define GTEST_OS_WINDOWS_PHONE 1\n#define GTEST_OS_WINDOWS_TV_TITLE 1\n#else\n// WINAPI_FAMILY defined but no known partition matched.\n// Default to desktop.\n#define GTEST_OS_WINDOWS_DESKTOP 1\n#endif\n#else\n#define GTEST_OS_WINDOWS_DESKTOP 1\n#endif  // _WIN32_WCE\n#elif defined __OS2__\n#define GTEST_OS_OS2 1\n#elif defined __APPLE__\n#define GTEST_OS_MAC 1\n#include <TargetConditionals.h>\n#if TARGET_OS_IPHONE\n#define GTEST_OS_IOS 1\n#endif\n#elif defined __DragonFly__\n#define GTEST_OS_DRAGONFLY 1\n#elif defined __FreeBSD__\n#define GTEST_OS_FREEBSD 1\n#elif defined __Fuchsia__\n#define GTEST_OS_FUCHSIA 1\n#elif defined(__GNU__)\n#define GTEST_OS_GNU_HURD 1\n#elif defined(__GLIBC__) && defined(__FreeBSD_kernel__)\n#define GTEST_OS_GNU_KFREEBSD 1\n#elif defined __linux__\n#define GTEST_OS_LINUX 1\n#if defined __ANDROID__\n#define GTEST_OS_LINUX_ANDROID 1\n#endif\n#elif defined __MVS__\n#define GTEST_OS_ZOS 1\n#elif defined(__sun) && defined(__SVR4)\n#define GTEST_OS_SOLARIS 1\n#elif defined(_AIX)\n#define GTEST_OS_AIX 1\n#elif defined(__hpux)\n#define GTEST_OS_HPUX 1\n#elif defined __native_client__\n#define GTEST_OS_NACL 1\n#elif defined __NetBSD__\n#define GTEST_OS_NETBSD 1\n#elif defined __OpenBSD__\n#define GTEST_OS_OPENBSD 1\n#elif defined __QNX__\n#define GTEST_OS_QNX 1\n#elif defined(__HAIKU__)\n#define GTEST_OS_HAIKU 1\n#elif defined ESP8266\n#define GTEST_OS_ESP8266 1\n#elif defined ESP32\n#define GTEST_OS_ESP32 1\n#elif defined(__XTENSA__)\n#define GTEST_OS_XTENSA 1\n#endif  // __CYGWIN__\n\n#endif  // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_ARCH_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/include/gtest/internal/gtest-port.h",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Low-level types and utilities for porting Google Test to various\n// platforms.  All macros ending with _ and symbols defined in an\n// internal namespace are subject to change without notice.  Code\n// outside Google Test MUST NOT USE THEM DIRECTLY.  Macros that don't\n// end with _ are part of Google Test's public API and can be used by\n// code outside Google Test.\n//\n// This file is fundamental to Google Test.  All other Google Test source\n// files are expected to #include this.  Therefore, it cannot #include\n// any other Google Test header.\n\n// IWYU pragma: private, include \"gtest/gtest.h\"\n// IWYU pragma: friend gtest/.*\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_\n#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_\n\n// Environment-describing macros\n// -----------------------------\n//\n// Google Test can be used in many different environments.  Macros in\n// this section tell Google Test what kind of environment it is being\n// used in, such that Google Test can provide environment-specific\n// features and implementations.\n//\n// Google Test tries to automatically detect the properties of its\n// environment, so users usually don't need to worry about these\n// macros.  However, the automatic detection is not perfect.\n// Sometimes it's necessary for a user to define some of the following\n// macros in the build script to override Google Test's decisions.\n//\n// If the user doesn't define a macro in the list, Google Test will\n// provide a default definition.  After this header is #included, all\n// macros in this list will be defined to either 1 or 0.\n//\n// Notes to maintainers:\n//   - Each macro here is a user-tweakable knob; do not grow the list\n//     lightly.\n//   - Use #if to key off these macros.  Don't use #ifdef or \"#if\n//     defined(...)\", which will not work as these macros are ALWAYS\n//     defined.\n//\n//   GTEST_HAS_CLONE          - Define it to 1/0 to indicate that clone(2)\n//                              is/isn't available.\n//   GTEST_HAS_EXCEPTIONS     - Define it to 1/0 to indicate that exceptions\n//                              are enabled.\n//   GTEST_HAS_POSIX_RE       - Define it to 1/0 to indicate that POSIX regular\n//                              expressions are/aren't available.\n//   GTEST_HAS_PTHREAD        - Define it to 1/0 to indicate that <pthread.h>\n//                              is/isn't available.\n//   GTEST_HAS_RTTI           - Define it to 1/0 to indicate that RTTI is/isn't\n//                              enabled.\n//   GTEST_HAS_STD_WSTRING    - Define it to 1/0 to indicate that\n//                              std::wstring does/doesn't work (Google Test can\n//                              be used where std::wstring is unavailable).\n//   GTEST_HAS_SEH            - Define it to 1/0 to indicate whether the\n//                              compiler supports Microsoft's \"Structured\n//                              Exception Handling\".\n//   GTEST_HAS_STREAM_REDIRECTION\n//                            - Define it to 1/0 to indicate whether the\n//                              platform supports I/O stream redirection using\n//                              dup() and dup2().\n//   GTEST_LINKED_AS_SHARED_LIBRARY\n//                            - Define to 1 when compiling tests that use\n//                              Google Test as a shared library (known as\n//                              DLL on Windows).\n//   GTEST_CREATE_SHARED_LIBRARY\n//                            - Define to 1 when compiling Google Test itself\n//                              as a shared library.\n//   GTEST_DEFAULT_DEATH_TEST_STYLE\n//                            - The default value of --gtest_death_test_style.\n//                              The legacy default has been \"fast\" in the open\n//                              source version since 2008. The recommended value\n//                              is \"threadsafe\", and can be set in\n//                              custom/gtest-port.h.\n\n// Platform-indicating macros\n// --------------------------\n//\n// Macros indicating the platform on which Google Test is being used\n// (a macro is defined to 1 if compiled on the given platform;\n// otherwise UNDEFINED -- it's never defined to 0.).  Google Test\n// defines these macros automatically.  Code outside Google Test MUST\n// NOT define them.\n//\n//   GTEST_OS_AIX      - IBM AIX\n//   GTEST_OS_CYGWIN   - Cygwin\n//   GTEST_OS_DRAGONFLY - DragonFlyBSD\n//   GTEST_OS_FREEBSD  - FreeBSD\n//   GTEST_OS_FUCHSIA  - Fuchsia\n//   GTEST_OS_GNU_HURD - GNU/Hurd\n//   GTEST_OS_GNU_KFREEBSD - GNU/kFreeBSD\n//   GTEST_OS_HAIKU    - Haiku\n//   GTEST_OS_HPUX     - HP-UX\n//   GTEST_OS_LINUX    - Linux\n//     GTEST_OS_LINUX_ANDROID - Google Android\n//   GTEST_OS_MAC      - Mac OS X\n//     GTEST_OS_IOS    - iOS\n//   GTEST_OS_NACL     - Google Native Client (NaCl)\n//   GTEST_OS_NETBSD   - NetBSD\n//   GTEST_OS_OPENBSD  - OpenBSD\n//   GTEST_OS_OS2      - OS/2\n//   GTEST_OS_QNX      - QNX\n//   GTEST_OS_SOLARIS  - Sun Solaris\n//   GTEST_OS_WINDOWS  - Windows (Desktop, MinGW, or Mobile)\n//     GTEST_OS_WINDOWS_DESKTOP  - Windows Desktop\n//     GTEST_OS_WINDOWS_MINGW    - MinGW\n//     GTEST_OS_WINDOWS_MOBILE   - Windows Mobile\n//     GTEST_OS_WINDOWS_PHONE    - Windows Phone\n//     GTEST_OS_WINDOWS_RT       - Windows Store App/WinRT\n//   GTEST_OS_ZOS      - z/OS\n//\n// Among the platforms, Cygwin, Linux, Mac OS X, and Windows have the\n// most stable support.  Since core members of the Google Test project\n// don't have access to other platforms, support for them may be less\n// stable.  If you notice any problems on your platform, please notify\n// googletestframework@googlegroups.com (patches for fixing them are\n// even more welcome!).\n//\n// It is possible that none of the GTEST_OS_* macros are defined.\n\n// Feature-indicating macros\n// -------------------------\n//\n// Macros indicating which Google Test features are available (a macro\n// is defined to 1 if the corresponding feature is supported;\n// otherwise UNDEFINED -- it's never defined to 0.).  Google Test\n// defines these macros automatically.  Code outside Google Test MUST\n// NOT define them.\n//\n// These macros are public so that portable tests can be written.\n// Such tests typically surround code using a feature with an #if\n// which controls that code.  For example:\n//\n// #if GTEST_HAS_DEATH_TEST\n//   EXPECT_DEATH(DoSomethingDeadly());\n// #endif\n//\n//   GTEST_HAS_DEATH_TEST   - death tests\n//   GTEST_HAS_TYPED_TEST   - typed tests\n//   GTEST_HAS_TYPED_TEST_P - type-parameterized tests\n//   GTEST_IS_THREADSAFE    - Google Test is thread-safe.\n//   GTEST_USES_RE2         - the RE2 regular expression library is used\n//   GTEST_USES_POSIX_RE    - enhanced POSIX regex is used. Do not confuse with\n//                            GTEST_HAS_POSIX_RE (see above) which users can\n//                            define themselves.\n//   GTEST_USES_SIMPLE_RE   - our own simple regex is used;\n//                            the above RE\\b(s) are mutually exclusive.\n\n// Misc public macros\n// ------------------\n//\n//   GTEST_FLAG(flag_name)  - references the variable corresponding to\n//                            the given Google Test flag.\n\n// Internal utilities\n// ------------------\n//\n// The following macros and utilities are for Google Test's INTERNAL\n// use only.  Code outside Google Test MUST NOT USE THEM DIRECTLY.\n//\n// Macros for basic C++ coding:\n//   GTEST_AMBIGUOUS_ELSE_BLOCKER_ - for disabling a gcc warning.\n//   GTEST_ATTRIBUTE_UNUSED_  - declares that a class' instances or a\n//                              variable don't have to be used.\n//   GTEST_MUST_USE_RESULT_   - declares that a function's result must be used.\n//   GTEST_INTENTIONAL_CONST_COND_PUSH_ - start code section where MSVC C4127 is\n//                                        suppressed (constant conditional).\n//   GTEST_INTENTIONAL_CONST_COND_POP_  - finish code section where MSVC C4127\n//                                        is suppressed.\n//   GTEST_INTERNAL_HAS_ANY - for enabling UniversalPrinter<std::any> or\n//                            UniversalPrinter<absl::any> specializations.\n//   GTEST_INTERNAL_HAS_OPTIONAL - for enabling UniversalPrinter<std::optional>\n//   or\n//                                 UniversalPrinter<absl::optional>\n//                                 specializations.\n//   GTEST_INTERNAL_HAS_STRING_VIEW - for enabling Matcher<std::string_view> or\n//                                    Matcher<absl::string_view>\n//                                    specializations.\n//   GTEST_INTERNAL_HAS_VARIANT - for enabling UniversalPrinter<std::variant> or\n//                                UniversalPrinter<absl::variant>\n//                                specializations.\n//\n// Synchronization:\n//   Mutex, MutexLock, ThreadLocal, GetThreadCount()\n//                            - synchronization primitives.\n//\n// Regular expressions:\n//   RE             - a simple regular expression class using\n//                     1) the RE2 syntax on all platforms when built with RE2\n//                        and Abseil as dependencies\n//                     2) the POSIX Extended Regular Expression syntax on\n//                        UNIX-like platforms,\n//                     3) A reduced regular exception syntax on other platforms,\n//                        including Windows.\n// Logging:\n//   GTEST_LOG_()   - logs messages at the specified severity level.\n//   LogToStderr()  - directs all log messages to stderr.\n//   FlushInfoLog() - flushes informational log messages.\n//\n// Stdout and stderr capturing:\n//   CaptureStdout()     - starts capturing stdout.\n//   GetCapturedStdout() - stops capturing stdout and returns the captured\n//                         string.\n//   CaptureStderr()     - starts capturing stderr.\n//   GetCapturedStderr() - stops capturing stderr and returns the captured\n//                         string.\n//\n// Integer types:\n//   TypeWithSize   - maps an integer to a int type.\n//   TimeInMillis   - integers of known sizes.\n//   BiggestInt     - the biggest signed integer type.\n//\n// Command-line utilities:\n//   GetInjectableArgvs() - returns the command line as a vector of strings.\n//\n// Environment variable utilities:\n//   GetEnv()             - gets the value of an environment variable.\n//   BoolFromGTestEnv()   - parses a bool environment variable.\n//   Int32FromGTestEnv()  - parses an int32_t environment variable.\n//   StringFromGTestEnv() - parses a string environment variable.\n//\n// Deprecation warnings:\n//   GTEST_INTERNAL_DEPRECATED(message) - attribute marking a function as\n//                                        deprecated; calling a marked function\n//                                        should generate a compiler warning\n\n#include <ctype.h>   // for isspace, etc\n#include <stddef.h>  // for ptrdiff_t\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <cerrno>\n// #include <condition_variable>  // Guarded by GTEST_IS_THREADSAFE below\n#include <cstdint>\n#include <iostream>\n#include <limits>\n#include <locale>\n#include <memory>\n#include <string>\n// #include <mutex>  // Guarded by GTEST_IS_THREADSAFE below\n#include <tuple>\n#include <type_traits>\n#include <vector>\n\n#ifndef _WIN32_WCE\n#include <sys/stat.h>\n#include <sys/types.h>\n#endif  // !_WIN32_WCE\n\n#if defined __APPLE__\n#include <AvailabilityMacros.h>\n#include <TargetConditionals.h>\n#endif\n\n#include \"gtest/internal/custom/gtest-port.h\"\n#include \"gtest/internal/gtest-port-arch.h\"\n\n#if GTEST_HAS_ABSL\n#include \"absl/flags/declare.h\"\n#include \"absl/flags/flag.h\"\n#include \"absl/flags/reflection.h\"\n#endif\n\n#if !defined(GTEST_DEV_EMAIL_)\n#define GTEST_DEV_EMAIL_ \"googletestframework@@googlegroups.com\"\n#define GTEST_FLAG_PREFIX_ \"gtest_\"\n#define GTEST_FLAG_PREFIX_DASH_ \"gtest-\"\n#define GTEST_FLAG_PREFIX_UPPER_ \"GTEST_\"\n#define GTEST_NAME_ \"Google Test\"\n#define GTEST_PROJECT_URL_ \"https://github.com/google/googletest/\"\n#endif  // !defined(GTEST_DEV_EMAIL_)\n\n#if !defined(GTEST_INIT_GOOGLE_TEST_NAME_)\n#define GTEST_INIT_GOOGLE_TEST_NAME_ \"testing::InitGoogleTest\"\n#endif  // !defined(GTEST_INIT_GOOGLE_TEST_NAME_)\n\n// Determines the version of gcc that is used to compile this.\n#ifdef __GNUC__\n// 40302 means version 4.3.2.\n#define GTEST_GCC_VER_ \\\n  (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)\n#endif  // __GNUC__\n\n// Macros for disabling Microsoft Visual C++ warnings.\n//\n//   GTEST_DISABLE_MSC_WARNINGS_PUSH_(4800 4385)\n//   /* code that triggers warnings C4800 and C4385 */\n//   GTEST_DISABLE_MSC_WARNINGS_POP_()\n#if defined(_MSC_VER)\n#define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings) \\\n  __pragma(warning(push)) __pragma(warning(disable : warnings))\n#define GTEST_DISABLE_MSC_WARNINGS_POP_() __pragma(warning(pop))\n#else\n// Not all compilers are MSVC\n#define GTEST_DISABLE_MSC_WARNINGS_PUSH_(warnings)\n#define GTEST_DISABLE_MSC_WARNINGS_POP_()\n#endif\n\n// Clang on Windows does not understand MSVC's pragma warning.\n// We need clang-specific way to disable function deprecation warning.\n#ifdef __clang__\n#define GTEST_DISABLE_MSC_DEPRECATED_PUSH_()                            \\\n  _Pragma(\"clang diagnostic push\")                                      \\\n      _Pragma(\"clang diagnostic ignored \\\"-Wdeprecated-declarations\\\"\") \\\n          _Pragma(\"clang diagnostic ignored \\\"-Wdeprecated-implementations\\\"\")\n#define GTEST_DISABLE_MSC_DEPRECATED_POP_() _Pragma(\"clang diagnostic pop\")\n#else\n#define GTEST_DISABLE_MSC_DEPRECATED_PUSH_() \\\n  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)\n#define GTEST_DISABLE_MSC_DEPRECATED_POP_() GTEST_DISABLE_MSC_WARNINGS_POP_()\n#endif\n\n// Brings in definitions for functions used in the testing::internal::posix\n// namespace (read, write, close, chdir, isatty, stat). We do not currently\n// use them on Windows Mobile.\n#if GTEST_OS_WINDOWS\n#if !GTEST_OS_WINDOWS_MOBILE\n#include <direct.h>\n#include <io.h>\n#endif\n// In order to avoid having to include <windows.h>, use forward declaration\n#if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR)\n// MinGW defined _CRITICAL_SECTION and _RTL_CRITICAL_SECTION as two\n// separate (equivalent) structs, instead of using typedef\ntypedef struct _CRITICAL_SECTION GTEST_CRITICAL_SECTION;\n#else\n// Assume CRITICAL_SECTION is a typedef of _RTL_CRITICAL_SECTION.\n// This assumption is verified by\n// WindowsTypesTest.CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION.\ntypedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION;\n#endif\n#elif GTEST_OS_XTENSA\n#include <unistd.h>\n// Xtensa toolchains define strcasecmp in the string.h header instead of\n// strings.h. string.h is already included.\n#else\n// This assumes that non-Windows OSes provide unistd.h. For OSes where this\n// is not the case, we need to include headers that provide the functions\n// mentioned above.\n#include <strings.h>\n#include <unistd.h>\n#endif  // GTEST_OS_WINDOWS\n\n#if GTEST_OS_LINUX_ANDROID\n// Used to define __ANDROID_API__ matching the target NDK API level.\n#include <android/api-level.h>  // NOLINT\n#endif\n\n// Defines this to true if and only if Google Test can use POSIX regular\n// expressions.\n#ifndef GTEST_HAS_POSIX_RE\n#if GTEST_OS_LINUX_ANDROID\n// On Android, <regex.h> is only available starting with Gingerbread.\n#define GTEST_HAS_POSIX_RE (__ANDROID_API__ >= 9)\n#else\n#define GTEST_HAS_POSIX_RE (!GTEST_OS_WINDOWS && !GTEST_OS_XTENSA)\n#endif\n#endif\n\n// Select the regular expression implementation.\n#if GTEST_HAS_ABSL\n// When using Abseil, RE2 is required.\n#include \"absl/strings/string_view.h\"\n#include \"re2/re2.h\"\n#define GTEST_USES_RE2 1\n#elif GTEST_HAS_POSIX_RE\n#include <regex.h>  // NOLINT\n#define GTEST_USES_POSIX_RE 1\n#else\n// Use our own simple regex implementation.\n#define GTEST_USES_SIMPLE_RE 1\n#endif\n\n#ifndef GTEST_HAS_EXCEPTIONS\n// The user didn't tell us whether exceptions are enabled, so we need\n// to figure it out.\n#if defined(_MSC_VER) && defined(_CPPUNWIND)\n// MSVC defines _CPPUNWIND to 1 if and only if exceptions are enabled.\n#define GTEST_HAS_EXCEPTIONS 1\n#elif defined(__BORLANDC__)\n// C++Builder's implementation of the STL uses the _HAS_EXCEPTIONS\n// macro to enable exceptions, so we'll do the same.\n// Assumes that exceptions are enabled by default.\n#ifndef _HAS_EXCEPTIONS\n#define _HAS_EXCEPTIONS 1\n#endif  // _HAS_EXCEPTIONS\n#define GTEST_HAS_EXCEPTIONS _HAS_EXCEPTIONS\n#elif defined(__clang__)\n// clang defines __EXCEPTIONS if and only if exceptions are enabled before clang\n// 220714, but if and only if cleanups are enabled after that. In Obj-C++ files,\n// there can be cleanups for ObjC exceptions which also need cleanups, even if\n// C++ exceptions are disabled. clang has __has_feature(cxx_exceptions) which\n// checks for C++ exceptions starting at clang r206352, but which checked for\n// cleanups prior to that. To reliably check for C++ exception availability with\n// clang, check for\n// __EXCEPTIONS && __has_feature(cxx_exceptions).\n#define GTEST_HAS_EXCEPTIONS (__EXCEPTIONS && __has_feature(cxx_exceptions))\n#elif defined(__GNUC__) && __EXCEPTIONS\n// gcc defines __EXCEPTIONS to 1 if and only if exceptions are enabled.\n#define GTEST_HAS_EXCEPTIONS 1\n#elif defined(__SUNPRO_CC)\n// Sun Pro CC supports exceptions.  However, there is no compile-time way of\n// detecting whether they are enabled or not.  Therefore, we assume that\n// they are enabled unless the user tells us otherwise.\n#define GTEST_HAS_EXCEPTIONS 1\n#elif defined(__IBMCPP__) && __EXCEPTIONS\n// xlC defines __EXCEPTIONS to 1 if and only if exceptions are enabled.\n#define GTEST_HAS_EXCEPTIONS 1\n#elif defined(__HP_aCC)\n// Exception handling is in effect by default in HP aCC compiler. It has to\n// be turned of by +noeh compiler option if desired.\n#define GTEST_HAS_EXCEPTIONS 1\n#else\n// For other compilers, we assume exceptions are disabled to be\n// conservative.\n#define GTEST_HAS_EXCEPTIONS 0\n#endif  // defined(_MSC_VER) || defined(__BORLANDC__)\n#endif  // GTEST_HAS_EXCEPTIONS\n\n#ifndef GTEST_HAS_STD_WSTRING\n// The user didn't tell us whether ::std::wstring is available, so we need\n// to figure it out.\n// Cygwin 1.7 and below doesn't support ::std::wstring.\n// Solaris' libc++ doesn't support it either.  Android has\n// no support for it at least as recent as Froyo (2.2).\n#define GTEST_HAS_STD_WSTRING                                         \\\n  (!(GTEST_OS_LINUX_ANDROID || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS || \\\n     GTEST_OS_HAIKU || GTEST_OS_ESP32 || GTEST_OS_ESP8266 || GTEST_OS_XTENSA))\n\n#endif  // GTEST_HAS_STD_WSTRING\n\n// Determines whether RTTI is available.\n#ifndef GTEST_HAS_RTTI\n// The user didn't tell us whether RTTI is enabled, so we need to\n// figure it out.\n\n#ifdef _MSC_VER\n\n#ifdef _CPPRTTI  // MSVC defines this macro if and only if RTTI is enabled.\n#define GTEST_HAS_RTTI 1\n#else\n#define GTEST_HAS_RTTI 0\n#endif\n\n// Starting with version 4.3.2, gcc defines __GXX_RTTI if and only if RTTI is\n// enabled.\n#elif defined(__GNUC__)\n\n#ifdef __GXX_RTTI\n// When building against STLport with the Android NDK and with\n// -frtti -fno-exceptions, the build fails at link time with undefined\n// references to __cxa_bad_typeid. Note sure if STL or toolchain bug,\n// so disable RTTI when detected.\n#if GTEST_OS_LINUX_ANDROID && defined(_STLPORT_MAJOR) && !defined(__EXCEPTIONS)\n#define GTEST_HAS_RTTI 0\n#else\n#define GTEST_HAS_RTTI 1\n#endif  // GTEST_OS_LINUX_ANDROID && __STLPORT_MAJOR && !__EXCEPTIONS\n#else\n#define GTEST_HAS_RTTI 0\n#endif  // __GXX_RTTI\n\n// Clang defines __GXX_RTTI starting with version 3.0, but its manual recommends\n// using has_feature instead. has_feature(cxx_rtti) is supported since 2.7, the\n// first version with C++ support.\n#elif defined(__clang__)\n\n#define GTEST_HAS_RTTI __has_feature(cxx_rtti)\n\n// Starting with version 9.0 IBM Visual Age defines __RTTI_ALL__ to 1 if\n// both the typeid and dynamic_cast features are present.\n#elif defined(__IBMCPP__) && (__IBMCPP__ >= 900)\n\n#ifdef __RTTI_ALL__\n#define GTEST_HAS_RTTI 1\n#else\n#define GTEST_HAS_RTTI 0\n#endif\n\n#else\n\n// For all other compilers, we assume RTTI is enabled.\n#define GTEST_HAS_RTTI 1\n\n#endif  // _MSC_VER\n\n#endif  // GTEST_HAS_RTTI\n\n// It's this header's responsibility to #include <typeinfo> when RTTI\n// is enabled.\n#if GTEST_HAS_RTTI\n#include <typeinfo>\n#endif\n\n// Determines whether Google Test can use the pthreads library.\n#ifndef GTEST_HAS_PTHREAD\n// The user didn't tell us explicitly, so we make reasonable assumptions about\n// which platforms have pthreads support.\n//\n// To disable threading support in Google Test, add -DGTEST_HAS_PTHREAD=0\n// to your compiler flags.\n#define GTEST_HAS_PTHREAD                                                      \\\n  (GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_HPUX || GTEST_OS_QNX ||          \\\n   GTEST_OS_FREEBSD || GTEST_OS_NACL || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA || \\\n   GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_OPENBSD ||          \\\n   GTEST_OS_HAIKU || GTEST_OS_GNU_HURD)\n#endif  // GTEST_HAS_PTHREAD\n\n#if GTEST_HAS_PTHREAD\n// gtest-port.h guarantees to #include <pthread.h> when GTEST_HAS_PTHREAD is\n// true.\n#include <pthread.h>  // NOLINT\n\n// For timespec and nanosleep, used below.\n#include <time.h>  // NOLINT\n#endif\n\n// Determines whether clone(2) is supported.\n// Usually it will only be available on Linux, excluding\n// Linux on the Itanium architecture.\n// Also see http://linux.die.net/man/2/clone.\n#ifndef GTEST_HAS_CLONE\n// The user didn't tell us, so we need to figure it out.\n\n#if GTEST_OS_LINUX && !defined(__ia64__)\n#if GTEST_OS_LINUX_ANDROID\n// On Android, clone() became available at different API levels for each 32-bit\n// architecture.\n#if defined(__LP64__) || (defined(__arm__) && __ANDROID_API__ >= 9) || \\\n    (defined(__mips__) && __ANDROID_API__ >= 12) ||                    \\\n    (defined(__i386__) && __ANDROID_API__ >= 17)\n#define GTEST_HAS_CLONE 1\n#else\n#define GTEST_HAS_CLONE 0\n#endif\n#else\n#define GTEST_HAS_CLONE 1\n#endif\n#else\n#define GTEST_HAS_CLONE 0\n#endif  // GTEST_OS_LINUX && !defined(__ia64__)\n\n#endif  // GTEST_HAS_CLONE\n\n// Determines whether to support stream redirection. This is used to test\n// output correctness and to implement death tests.\n#ifndef GTEST_HAS_STREAM_REDIRECTION\n// By default, we assume that stream redirection is supported on all\n// platforms except known mobile ones.\n#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \\\n    GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_XTENSA\n#define GTEST_HAS_STREAM_REDIRECTION 0\n#else\n#define GTEST_HAS_STREAM_REDIRECTION 1\n#endif  // !GTEST_OS_WINDOWS_MOBILE\n#endif  // GTEST_HAS_STREAM_REDIRECTION\n\n// Determines whether to support death tests.\n// pops up a dialog window that cannot be suppressed programmatically.\n#if (GTEST_OS_LINUX || GTEST_OS_CYGWIN || GTEST_OS_SOLARIS ||             \\\n     (GTEST_OS_MAC && !GTEST_OS_IOS) ||                                   \\\n     (GTEST_OS_WINDOWS_DESKTOP && _MSC_VER) || GTEST_OS_WINDOWS_MINGW ||  \\\n     GTEST_OS_AIX || GTEST_OS_HPUX || GTEST_OS_OPENBSD || GTEST_OS_QNX || \\\n     GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_FUCHSIA ||           \\\n     GTEST_OS_DRAGONFLY || GTEST_OS_GNU_KFREEBSD || GTEST_OS_HAIKU ||     \\\n     GTEST_OS_GNU_HURD)\n#define GTEST_HAS_DEATH_TEST 1\n#endif\n\n// Determines whether to support type-driven tests.\n\n// Typed tests need <typeinfo> and variadic macros, which GCC, VC++ 8.0,\n// Sun Pro CC, IBM Visual Age, and HP aCC support.\n#if defined(__GNUC__) || defined(_MSC_VER) || defined(__SUNPRO_CC) || \\\n    defined(__IBMCPP__) || defined(__HP_aCC)\n#define GTEST_HAS_TYPED_TEST 1\n#define GTEST_HAS_TYPED_TEST_P 1\n#endif\n\n// Determines whether the system compiler uses UTF-16 for encoding wide strings.\n#define GTEST_WIDE_STRING_USES_UTF16_ \\\n  (GTEST_OS_WINDOWS || GTEST_OS_CYGWIN || GTEST_OS_AIX || GTEST_OS_OS2)\n\n// Determines whether test results can be streamed to a socket.\n#if GTEST_OS_LINUX || GTEST_OS_GNU_KFREEBSD || GTEST_OS_DRAGONFLY || \\\n    GTEST_OS_FREEBSD || GTEST_OS_NETBSD || GTEST_OS_OPENBSD ||       \\\n    GTEST_OS_GNU_HURD\n#define GTEST_CAN_STREAM_RESULTS_ 1\n#endif\n\n// Defines some utility macros.\n\n// The GNU compiler emits a warning if nested \"if\" statements are followed by\n// an \"else\" statement and braces are not used to explicitly disambiguate the\n// \"else\" binding.  This leads to problems with code like:\n//\n//   if (gate)\n//     ASSERT_*(condition) << \"Some message\";\n//\n// The \"switch (0) case 0:\" idiom is used to suppress this.\n#ifdef __INTEL_COMPILER\n#define GTEST_AMBIGUOUS_ELSE_BLOCKER_\n#else\n#define GTEST_AMBIGUOUS_ELSE_BLOCKER_ \\\n  switch (0)                          \\\n  case 0:                             \\\n  default:  // NOLINT\n#endif\n\n// Use this annotation at the end of a struct/class definition to\n// prevent the compiler from optimizing away instances that are never\n// used.  This is useful when all interesting logic happens inside the\n// c'tor and / or d'tor.  Example:\n//\n//   struct Foo {\n//     Foo() { ... }\n//   } GTEST_ATTRIBUTE_UNUSED_;\n//\n// Also use it after a variable or parameter declaration to tell the\n// compiler the variable/parameter does not have to be used.\n#if defined(__GNUC__) && !defined(COMPILER_ICC)\n#define GTEST_ATTRIBUTE_UNUSED_ __attribute__((unused))\n#elif defined(__clang__)\n#if __has_attribute(unused)\n#define GTEST_ATTRIBUTE_UNUSED_ __attribute__((unused))\n#endif\n#endif\n#ifndef GTEST_ATTRIBUTE_UNUSED_\n#define GTEST_ATTRIBUTE_UNUSED_\n#endif\n\n// Use this annotation before a function that takes a printf format string.\n#if (defined(__GNUC__) || defined(__clang__)) && !defined(COMPILER_ICC)\n#if defined(__MINGW_PRINTF_FORMAT)\n// MinGW has two different printf implementations. Ensure the format macro\n// matches the selected implementation. See\n// https://sourceforge.net/p/mingw-w64/wiki2/gnu%20printf/.\n#define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \\\n  __attribute__((                                             \\\n      __format__(__MINGW_PRINTF_FORMAT, string_index, first_to_check)))\n#else\n#define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check) \\\n  __attribute__((__format__(__printf__, string_index, first_to_check)))\n#endif\n#else\n#define GTEST_ATTRIBUTE_PRINTF_(string_index, first_to_check)\n#endif\n\n// Tell the compiler to warn about unused return values for functions declared\n// with this macro.  The macro should be used on function declarations\n// following the argument list:\n//\n//   Sprocket* AllocateSprocket() GTEST_MUST_USE_RESULT_;\n#if defined(__GNUC__) && !defined(COMPILER_ICC)\n#define GTEST_MUST_USE_RESULT_ __attribute__((warn_unused_result))\n#else\n#define GTEST_MUST_USE_RESULT_\n#endif  // __GNUC__ && !COMPILER_ICC\n\n// MS C++ compiler emits warning when a conditional expression is compile time\n// constant. In some contexts this warning is false positive and needs to be\n// suppressed. Use the following two macros in such cases:\n//\n// GTEST_INTENTIONAL_CONST_COND_PUSH_()\n// while (true) {\n// GTEST_INTENTIONAL_CONST_COND_POP_()\n// }\n#define GTEST_INTENTIONAL_CONST_COND_PUSH_() \\\n  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4127)\n#define GTEST_INTENTIONAL_CONST_COND_POP_() GTEST_DISABLE_MSC_WARNINGS_POP_()\n\n// Determine whether the compiler supports Microsoft's Structured Exception\n// Handling.  This is supported by several Windows compilers but generally\n// does not exist on any other system.\n#ifndef GTEST_HAS_SEH\n// The user didn't tell us, so we need to figure it out.\n\n#if defined(_MSC_VER) || defined(__BORLANDC__)\n// These two compilers are known to support SEH.\n#define GTEST_HAS_SEH 1\n#else\n// Assume no SEH.\n#define GTEST_HAS_SEH 0\n#endif\n\n#endif  // GTEST_HAS_SEH\n\n#ifndef GTEST_IS_THREADSAFE\n\n#define GTEST_IS_THREADSAFE                                                 \\\n  (GTEST_HAS_MUTEX_AND_THREAD_LOCAL_ ||                                     \\\n   (GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT) || \\\n   GTEST_HAS_PTHREAD)\n\n#endif  // GTEST_IS_THREADSAFE\n\n#if GTEST_IS_THREADSAFE\n// Some platforms don't support including these threading related headers.\n#include <condition_variable>  // NOLINT\n#include <mutex>               // NOLINT\n#endif                         // GTEST_IS_THREADSAFE\n\n// GTEST_API_ qualifies all symbols that must be exported. The definitions below\n// are guarded by #ifndef to give embedders a chance to define GTEST_API_ in\n// gtest/internal/custom/gtest-port.h\n#ifndef GTEST_API_\n\n#ifdef _MSC_VER\n#if GTEST_LINKED_AS_SHARED_LIBRARY\n#define GTEST_API_ __declspec(dllimport)\n#elif GTEST_CREATE_SHARED_LIBRARY\n#define GTEST_API_ __declspec(dllexport)\n#endif\n#elif __GNUC__ >= 4 || defined(__clang__)\n#define GTEST_API_ __attribute__((visibility(\"default\")))\n#endif  // _MSC_VER\n\n#endif  // GTEST_API_\n\n#ifndef GTEST_API_\n#define GTEST_API_\n#endif  // GTEST_API_\n\n#ifndef GTEST_DEFAULT_DEATH_TEST_STYLE\n#define GTEST_DEFAULT_DEATH_TEST_STYLE \"fast\"\n#endif  // GTEST_DEFAULT_DEATH_TEST_STYLE\n\n#ifdef __GNUC__\n// Ask the compiler to never inline a given function.\n#define GTEST_NO_INLINE_ __attribute__((noinline))\n#else\n#define GTEST_NO_INLINE_\n#endif\n\n#if defined(__clang__)\n// Nested ifs to avoid triggering MSVC warning.\n#if __has_attribute(disable_tail_calls)\n// Ask the compiler not to perform tail call optimization inside\n// the marked function.\n#define GTEST_NO_TAIL_CALL_ __attribute__((disable_tail_calls))\n#endif\n#elif __GNUC__\n#define GTEST_NO_TAIL_CALL_ \\\n  __attribute__((optimize(\"no-optimize-sibling-calls\")))\n#else\n#define GTEST_NO_TAIL_CALL_\n#endif\n\n// _LIBCPP_VERSION is defined by the libc++ library from the LLVM project.\n#if !defined(GTEST_HAS_CXXABI_H_)\n#if defined(__GLIBCXX__) || (defined(_LIBCPP_VERSION) && !defined(_MSC_VER))\n#define GTEST_HAS_CXXABI_H_ 1\n#else\n#define GTEST_HAS_CXXABI_H_ 0\n#endif\n#endif\n\n// A function level attribute to disable checking for use of uninitialized\n// memory when built with MemorySanitizer.\n#if defined(__clang__)\n#if __has_feature(memory_sanitizer)\n#define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ __attribute__((no_sanitize_memory))\n#else\n#define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_\n#endif  // __has_feature(memory_sanitizer)\n#else\n#define GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_\n#endif  // __clang__\n\n// A function level attribute to disable AddressSanitizer instrumentation.\n#if defined(__clang__)\n#if __has_feature(address_sanitizer)\n#define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ \\\n  __attribute__((no_sanitize_address))\n#else\n#define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_\n#endif  // __has_feature(address_sanitizer)\n#else\n#define GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_\n#endif  // __clang__\n\n// A function level attribute to disable HWAddressSanitizer instrumentation.\n#if defined(__clang__)\n#if __has_feature(hwaddress_sanitizer)\n#define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_ \\\n  __attribute__((no_sanitize(\"hwaddress\")))\n#else\n#define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_\n#endif  // __has_feature(hwaddress_sanitizer)\n#else\n#define GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_\n#endif  // __clang__\n\n// A function level attribute to disable ThreadSanitizer instrumentation.\n#if defined(__clang__)\n#if __has_feature(thread_sanitizer)\n#define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ __attribute__((no_sanitize_thread))\n#else\n#define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_\n#endif  // __has_feature(thread_sanitizer)\n#else\n#define GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_\n#endif  // __clang__\n\nnamespace testing {\n\nclass Message;\n\n// Legacy imports for backwards compatibility.\n// New code should use std:: names directly.\nusing std::get;\nusing std::make_tuple;\nusing std::tuple;\nusing std::tuple_element;\nusing std::tuple_size;\n\nnamespace internal {\n\n// A secret type that Google Test users don't know about.  It has no\n// definition on purpose.  Therefore it's impossible to create a\n// Secret object, which is what we want.\nclass Secret;\n\n// A helper for suppressing warnings on constant condition.  It just\n// returns 'condition'.\nGTEST_API_ bool IsTrue(bool condition);\n\n// Defines RE.\n\n#if GTEST_USES_RE2\n\n// This is almost `using RE = ::RE2`, except it is copy-constructible, and it\n// needs to disambiguate the `std::string`, `absl::string_view`, and `const\n// char*` constructors.\nclass GTEST_API_ RE {\n public:\n  RE(absl::string_view regex) : regex_(regex) {}                  // NOLINT\n  RE(const char* regex) : RE(absl::string_view(regex)) {}         // NOLINT\n  RE(const std::string& regex) : RE(absl::string_view(regex)) {}  // NOLINT\n  RE(const RE& other) : RE(other.pattern()) {}\n\n  const std::string& pattern() const { return regex_.pattern(); }\n\n  static bool FullMatch(absl::string_view str, const RE& re) {\n    return RE2::FullMatch(str, re.regex_);\n  }\n  static bool PartialMatch(absl::string_view str, const RE& re) {\n    return RE2::PartialMatch(str, re.regex_);\n  }\n\n private:\n  RE2 regex_;\n};\n\n#elif GTEST_USES_POSIX_RE || GTEST_USES_SIMPLE_RE\n\n// A simple C++ wrapper for <regex.h>.  It uses the POSIX Extended\n// Regular Expression syntax.\nclass GTEST_API_ RE {\n public:\n  // A copy constructor is required by the Standard to initialize object\n  // references from r-values.\n  RE(const RE& other) { Init(other.pattern()); }\n\n  // Constructs an RE from a string.\n  RE(const ::std::string& regex) { Init(regex.c_str()); }  // NOLINT\n\n  RE(const char* regex) { Init(regex); }  // NOLINT\n  ~RE();\n\n  // Returns the string representation of the regex.\n  const char* pattern() const { return pattern_; }\n\n  // FullMatch(str, re) returns true if and only if regular expression re\n  // matches the entire str.\n  // PartialMatch(str, re) returns true if and only if regular expression re\n  // matches a substring of str (including str itself).\n  static bool FullMatch(const ::std::string& str, const RE& re) {\n    return FullMatch(str.c_str(), re);\n  }\n  static bool PartialMatch(const ::std::string& str, const RE& re) {\n    return PartialMatch(str.c_str(), re);\n  }\n\n  static bool FullMatch(const char* str, const RE& re);\n  static bool PartialMatch(const char* str, const RE& re);\n\n private:\n  void Init(const char* regex);\n  const char* pattern_;\n  bool is_valid_;\n\n#if GTEST_USES_POSIX_RE\n\n  regex_t full_regex_;     // For FullMatch().\n  regex_t partial_regex_;  // For PartialMatch().\n\n#else  // GTEST_USES_SIMPLE_RE\n\n  const char* full_pattern_;  // For FullMatch();\n\n#endif\n};\n\n#endif  // ::testing::internal::RE implementation\n\n// Formats a source file path and a line number as they would appear\n// in an error message from the compiler used to compile this code.\nGTEST_API_ ::std::string FormatFileLocation(const char* file, int line);\n\n// Formats a file location for compiler-independent XML output.\n// Although this function is not platform dependent, we put it next to\n// FormatFileLocation in order to contrast the two functions.\nGTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file,\n                                                               int line);\n\n// Defines logging utilities:\n//   GTEST_LOG_(severity) - logs messages at the specified severity level. The\n//                          message itself is streamed into the macro.\n//   LogToStderr()  - directs all log messages to stderr.\n//   FlushInfoLog() - flushes informational log messages.\n\nenum GTestLogSeverity { GTEST_INFO, GTEST_WARNING, GTEST_ERROR, GTEST_FATAL };\n\n// Formats log entry severity, provides a stream object for streaming the\n// log message, and terminates the message with a newline when going out of\n// scope.\nclass GTEST_API_ GTestLog {\n public:\n  GTestLog(GTestLogSeverity severity, const char* file, int line);\n\n  // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.\n  ~GTestLog();\n\n  ::std::ostream& GetStream() { return ::std::cerr; }\n\n private:\n  const GTestLogSeverity severity_;\n\n  GTestLog(const GTestLog&) = delete;\n  GTestLog& operator=(const GTestLog&) = delete;\n};\n\n#if !defined(GTEST_LOG_)\n\n#define GTEST_LOG_(severity)                                           \\\n  ::testing::internal::GTestLog(::testing::internal::GTEST_##severity, \\\n                                __FILE__, __LINE__)                    \\\n      .GetStream()\n\ninline void LogToStderr() {}\ninline void FlushInfoLog() { fflush(nullptr); }\n\n#endif  // !defined(GTEST_LOG_)\n\n#if !defined(GTEST_CHECK_)\n// INTERNAL IMPLEMENTATION - DO NOT USE.\n//\n// GTEST_CHECK_ is an all-mode assert. It aborts the program if the condition\n// is not satisfied.\n//  Synopsis:\n//    GTEST_CHECK_(boolean_condition);\n//     or\n//    GTEST_CHECK_(boolean_condition) << \"Additional message\";\n//\n//    This checks the condition and if the condition is not satisfied\n//    it prints message about the condition violation, including the\n//    condition itself, plus additional message streamed into it, if any,\n//    and then it aborts the program. It aborts the program irrespective of\n//    whether it is built in the debug mode or not.\n#define GTEST_CHECK_(condition)               \\\n  GTEST_AMBIGUOUS_ELSE_BLOCKER_               \\\n  if (::testing::internal::IsTrue(condition)) \\\n    ;                                         \\\n  else                                        \\\n    GTEST_LOG_(FATAL) << \"Condition \" #condition \" failed. \"\n#endif  // !defined(GTEST_CHECK_)\n\n// An all-mode assert to verify that the given POSIX-style function\n// call returns 0 (indicating success).  Known limitation: this\n// doesn't expand to a balanced 'if' statement, so enclose the macro\n// in {} if you need to use it as the only statement in an 'if'\n// branch.\n#define GTEST_CHECK_POSIX_SUCCESS_(posix_call) \\\n  if (const int gtest_error = (posix_call))    \\\n  GTEST_LOG_(FATAL) << #posix_call << \"failed with error \" << gtest_error\n\n// Transforms \"T\" into \"const T&\" according to standard reference collapsing\n// rules (this is only needed as a backport for C++98 compilers that do not\n// support reference collapsing). Specifically, it transforms:\n//\n//   char         ==> const char&\n//   const char   ==> const char&\n//   char&        ==> char&\n//   const char&  ==> const char&\n//\n// Note that the non-const reference will not have \"const\" added. This is\n// standard, and necessary so that \"T\" can always bind to \"const T&\".\ntemplate <typename T>\nstruct ConstRef {\n  typedef const T& type;\n};\ntemplate <typename T>\nstruct ConstRef<T&> {\n  typedef T& type;\n};\n\n// The argument T must depend on some template parameters.\n#define GTEST_REFERENCE_TO_CONST_(T) \\\n  typename ::testing::internal::ConstRef<T>::type\n\n// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.\n//\n// Use ImplicitCast_ as a safe version of static_cast for upcasting in\n// the type hierarchy (e.g. casting a Foo* to a SuperclassOfFoo* or a\n// const Foo*).  When you use ImplicitCast_, the compiler checks that\n// the cast is safe.  Such explicit ImplicitCast_s are necessary in\n// surprisingly many situations where C++ demands an exact type match\n// instead of an argument type convertible to a target type.\n//\n// The syntax for using ImplicitCast_ is the same as for static_cast:\n//\n//   ImplicitCast_<ToType>(expr)\n//\n// ImplicitCast_ would have been part of the C++ standard library,\n// but the proposal was submitted too late.  It will probably make\n// its way into the language in the future.\n//\n// This relatively ugly name is intentional. It prevents clashes with\n// similar functions users may have (e.g., implicit_cast). The internal\n// namespace alone is not enough because the function can be found by ADL.\ntemplate <typename To>\ninline To ImplicitCast_(To x) {\n  return x;\n}\n\n// When you upcast (that is, cast a pointer from type Foo to type\n// SuperclassOfFoo), it's fine to use ImplicitCast_<>, since upcasts\n// always succeed.  When you downcast (that is, cast a pointer from\n// type Foo to type SubclassOfFoo), static_cast<> isn't safe, because\n// how do you know the pointer is really of type SubclassOfFoo?  It\n// could be a bare Foo, or of type DifferentSubclassOfFoo.  Thus,\n// when you downcast, you should use this macro.  In debug mode, we\n// use dynamic_cast<> to double-check the downcast is legal (we die\n// if it's not).  In normal mode, we do the efficient static_cast<>\n// instead.  Thus, it's important to test in debug mode to make sure\n// the cast is legal!\n//    This is the only place in the code we should use dynamic_cast<>.\n// In particular, you SHOULDN'T be using dynamic_cast<> in order to\n// do RTTI (eg code like this:\n//    if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo);\n//    if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo);\n// You should design the code some other way not to need this.\n//\n// This relatively ugly name is intentional. It prevents clashes with\n// similar functions users may have (e.g., down_cast). The internal\n// namespace alone is not enough because the function can be found by ADL.\ntemplate <typename To, typename From>  // use like this: DownCast_<T*>(foo);\ninline To DownCast_(From* f) {         // so we only accept pointers\n  // Ensures that To is a sub-type of From *.  This test is here only\n  // for compile-time type checking, and has no overhead in an\n  // optimized build at run-time, as it will be optimized away\n  // completely.\n  GTEST_INTENTIONAL_CONST_COND_PUSH_()\n  if (false) {\n    GTEST_INTENTIONAL_CONST_COND_POP_()\n    const To to = nullptr;\n    ::testing::internal::ImplicitCast_<From*>(to);\n  }\n\n#if GTEST_HAS_RTTI\n  // RTTI: debug mode only!\n  GTEST_CHECK_(f == nullptr || dynamic_cast<To>(f) != nullptr);\n#endif\n  return static_cast<To>(f);\n}\n\n// Downcasts the pointer of type Base to Derived.\n// Derived must be a subclass of Base. The parameter MUST\n// point to a class of type Derived, not any subclass of it.\n// When RTTI is available, the function performs a runtime\n// check to enforce this.\ntemplate <class Derived, class Base>\nDerived* CheckedDowncastToActualType(Base* base) {\n#if GTEST_HAS_RTTI\n  GTEST_CHECK_(typeid(*base) == typeid(Derived));\n#endif\n\n#if GTEST_HAS_DOWNCAST_\n  return ::down_cast<Derived*>(base);\n#elif GTEST_HAS_RTTI\n  return dynamic_cast<Derived*>(base);  // NOLINT\n#else\n  return static_cast<Derived*>(base);  // Poor man's downcast.\n#endif\n}\n\n#if GTEST_HAS_STREAM_REDIRECTION\n\n// Defines the stderr capturer:\n//   CaptureStdout     - starts capturing stdout.\n//   GetCapturedStdout - stops capturing stdout and returns the captured string.\n//   CaptureStderr     - starts capturing stderr.\n//   GetCapturedStderr - stops capturing stderr and returns the captured string.\n//\nGTEST_API_ void CaptureStdout();\nGTEST_API_ std::string GetCapturedStdout();\nGTEST_API_ void CaptureStderr();\nGTEST_API_ std::string GetCapturedStderr();\n\n#endif  // GTEST_HAS_STREAM_REDIRECTION\n// Returns the size (in bytes) of a file.\nGTEST_API_ size_t GetFileSize(FILE* file);\n\n// Reads the entire content of a file as a string.\nGTEST_API_ std::string ReadEntireFile(FILE* file);\n\n// All command line arguments.\nGTEST_API_ std::vector<std::string> GetArgvs();\n\n#if GTEST_HAS_DEATH_TEST\n\nstd::vector<std::string> GetInjectableArgvs();\n// Deprecated: pass the args vector by value instead.\nvoid SetInjectableArgvs(const std::vector<std::string>* new_argvs);\nvoid SetInjectableArgvs(const std::vector<std::string>& new_argvs);\nvoid ClearInjectableArgvs();\n\n#endif  // GTEST_HAS_DEATH_TEST\n\n// Defines synchronization primitives.\n#if GTEST_IS_THREADSAFE\n\n#if GTEST_OS_WINDOWS\n// Provides leak-safe Windows kernel handle ownership.\n// Used in death tests and in threading support.\nclass GTEST_API_ AutoHandle {\n public:\n  // Assume that Win32 HANDLE type is equivalent to void*. Doing so allows us to\n  // avoid including <windows.h> in this header file. Including <windows.h> is\n  // undesirable because it defines a lot of symbols and macros that tend to\n  // conflict with client code. This assumption is verified by\n  // WindowsTypesTest.HANDLEIsVoidStar.\n  typedef void* Handle;\n  AutoHandle();\n  explicit AutoHandle(Handle handle);\n\n  ~AutoHandle();\n\n  Handle Get() const;\n  void Reset();\n  void Reset(Handle handle);\n\n private:\n  // Returns true if and only if the handle is a valid handle object that can be\n  // closed.\n  bool IsCloseable() const;\n\n  Handle handle_;\n\n  AutoHandle(const AutoHandle&) = delete;\n  AutoHandle& operator=(const AutoHandle&) = delete;\n};\n#endif\n\n#if GTEST_HAS_NOTIFICATION_\n// Notification has already been imported into the namespace.\n// Nothing to do here.\n\n#else\nGTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \\\n/* class A needs to have dll-interface to be used by clients of class B */)\n\n// Allows a controller thread to pause execution of newly created\n// threads until notified.  Instances of this class must be created\n// and destroyed in the controller thread.\n//\n// This class is only for testing Google Test's own constructs. Do not\n// use it in user tests, either directly or indirectly.\n// TODO(b/203539622): Replace unconditionally with absl::Notification.\nclass GTEST_API_ Notification {\n public:\n  Notification() : notified_(false) {}\n  Notification(const Notification&) = delete;\n  Notification& operator=(const Notification&) = delete;\n\n  // Notifies all threads created with this notification to start. Must\n  // be called from the controller thread.\n  void Notify() {\n    std::lock_guard<std::mutex> lock(mu_);\n    notified_ = true;\n    cv_.notify_all();\n  }\n\n  // Blocks until the controller thread notifies. Must be called from a test\n  // thread.\n  void WaitForNotification() {\n    std::unique_lock<std::mutex> lock(mu_);\n    cv_.wait(lock, [this]() { return notified_; });\n  }\n\n private:\n  std::mutex mu_;\n  std::condition_variable cv_;\n  bool notified_;\n};\nGTEST_DISABLE_MSC_WARNINGS_POP_()  // 4251\n#endif  // GTEST_HAS_NOTIFICATION_\n\n// On MinGW, we can have both GTEST_OS_WINDOWS and GTEST_HAS_PTHREAD\n// defined, but we don't want to use MinGW's pthreads implementation, which\n// has conformance problems with some versions of the POSIX standard.\n#if GTEST_HAS_PTHREAD && !GTEST_OS_WINDOWS_MINGW\n\n// As a C-function, ThreadFuncWithCLinkage cannot be templated itself.\n// Consequently, it cannot select a correct instantiation of ThreadWithParam\n// in order to call its Run(). Introducing ThreadWithParamBase as a\n// non-templated base class for ThreadWithParam allows us to bypass this\n// problem.\nclass ThreadWithParamBase {\n public:\n  virtual ~ThreadWithParamBase() {}\n  virtual void Run() = 0;\n};\n\n// pthread_create() accepts a pointer to a function type with the C linkage.\n// According to the Standard (7.5/1), function types with different linkages\n// are different even if they are otherwise identical.  Some compilers (for\n// example, SunStudio) treat them as different types.  Since class methods\n// cannot be defined with C-linkage we need to define a free C-function to\n// pass into pthread_create().\nextern \"C\" inline void* ThreadFuncWithCLinkage(void* thread) {\n  static_cast<ThreadWithParamBase*>(thread)->Run();\n  return nullptr;\n}\n\n// Helper class for testing Google Test's multi-threading constructs.\n// To use it, write:\n//\n//   void ThreadFunc(int param) { /* Do things with param */ }\n//   Notification thread_can_start;\n//   ...\n//   // The thread_can_start parameter is optional; you can supply NULL.\n//   ThreadWithParam<int> thread(&ThreadFunc, 5, &thread_can_start);\n//   thread_can_start.Notify();\n//\n// These classes are only for testing Google Test's own constructs. Do\n// not use them in user tests, either directly or indirectly.\ntemplate <typename T>\nclass ThreadWithParam : public ThreadWithParamBase {\n public:\n  typedef void UserThreadFunc(T);\n\n  ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)\n      : func_(func),\n        param_(param),\n        thread_can_start_(thread_can_start),\n        finished_(false) {\n    ThreadWithParamBase* const base = this;\n    // The thread can be created only after all fields except thread_\n    // have been initialized.\n    GTEST_CHECK_POSIX_SUCCESS_(\n        pthread_create(&thread_, nullptr, &ThreadFuncWithCLinkage, base));\n  }\n  ~ThreadWithParam() override { Join(); }\n\n  void Join() {\n    if (!finished_) {\n      GTEST_CHECK_POSIX_SUCCESS_(pthread_join(thread_, nullptr));\n      finished_ = true;\n    }\n  }\n\n  void Run() override {\n    if (thread_can_start_ != nullptr) thread_can_start_->WaitForNotification();\n    func_(param_);\n  }\n\n private:\n  UserThreadFunc* const func_;  // User-supplied thread function.\n  const T param_;  // User-supplied parameter to the thread function.\n  // When non-NULL, used to block execution until the controller thread\n  // notifies.\n  Notification* const thread_can_start_;\n  bool finished_;  // true if and only if we know that the thread function has\n                   // finished.\n  pthread_t thread_;  // The native thread object.\n\n  ThreadWithParam(const ThreadWithParam&) = delete;\n  ThreadWithParam& operator=(const ThreadWithParam&) = delete;\n};\n#endif  // !GTEST_OS_WINDOWS && GTEST_HAS_PTHREAD ||\n        // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_\n\n#if GTEST_HAS_MUTEX_AND_THREAD_LOCAL_\n// Mutex and ThreadLocal have already been imported into the namespace.\n// Nothing to do here.\n\n#elif GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT\n\n// Mutex implements mutex on Windows platforms.  It is used in conjunction\n// with class MutexLock:\n//\n//   Mutex mutex;\n//   ...\n//   MutexLock lock(&mutex);  // Acquires the mutex and releases it at the\n//                            // end of the current scope.\n//\n// A static Mutex *must* be defined or declared using one of the following\n// macros:\n//   GTEST_DEFINE_STATIC_MUTEX_(g_some_mutex);\n//   GTEST_DECLARE_STATIC_MUTEX_(g_some_mutex);\n//\n// (A non-static Mutex is defined/declared in the usual way).\nclass GTEST_API_ Mutex {\n public:\n  enum MutexType { kStatic = 0, kDynamic = 1 };\n  // We rely on kStaticMutex being 0 as it is to what the linker initializes\n  // type_ in static mutexes.  critical_section_ will be initialized lazily\n  // in ThreadSafeLazyInit().\n  enum StaticConstructorSelector { kStaticMutex = 0 };\n\n  // This constructor intentionally does nothing.  It relies on type_ being\n  // statically initialized to 0 (effectively setting it to kStatic) and on\n  // ThreadSafeLazyInit() to lazily initialize the rest of the members.\n  explicit Mutex(StaticConstructorSelector /*dummy*/) {}\n\n  Mutex();\n  ~Mutex();\n\n  void Lock();\n\n  void Unlock();\n\n  // Does nothing if the current thread holds the mutex. Otherwise, crashes\n  // with high probability.\n  void AssertHeld();\n\n private:\n  // Initializes owner_thread_id_ and critical_section_ in static mutexes.\n  void ThreadSafeLazyInit();\n\n  // Per https://blogs.msdn.microsoft.com/oldnewthing/20040223-00/?p=40503,\n  // we assume that 0 is an invalid value for thread IDs.\n  unsigned int owner_thread_id_;\n\n  // For static mutexes, we rely on these members being initialized to zeros\n  // by the linker.\n  MutexType type_;\n  long critical_section_init_phase_;  // NOLINT\n  GTEST_CRITICAL_SECTION* critical_section_;\n\n  Mutex(const Mutex&) = delete;\n  Mutex& operator=(const Mutex&) = delete;\n};\n\n#define GTEST_DECLARE_STATIC_MUTEX_(mutex) \\\n  extern ::testing::internal::Mutex mutex\n\n#define GTEST_DEFINE_STATIC_MUTEX_(mutex) \\\n  ::testing::internal::Mutex mutex(::testing::internal::Mutex::kStaticMutex)\n\n// We cannot name this class MutexLock because the ctor declaration would\n// conflict with a macro named MutexLock, which is defined on some\n// platforms. That macro is used as a defensive measure to prevent against\n// inadvertent misuses of MutexLock like \"MutexLock(&mu)\" rather than\n// \"MutexLock l(&mu)\".  Hence the typedef trick below.\nclass GTestMutexLock {\n public:\n  explicit GTestMutexLock(Mutex* mutex) : mutex_(mutex) { mutex_->Lock(); }\n\n  ~GTestMutexLock() { mutex_->Unlock(); }\n\n private:\n  Mutex* const mutex_;\n\n  GTestMutexLock(const GTestMutexLock&) = delete;\n  GTestMutexLock& operator=(const GTestMutexLock&) = delete;\n};\n\ntypedef GTestMutexLock MutexLock;\n\n// Base class for ValueHolder<T>.  Allows a caller to hold and delete a value\n// without knowing its type.\nclass ThreadLocalValueHolderBase {\n public:\n  virtual ~ThreadLocalValueHolderBase() {}\n};\n\n// Provides a way for a thread to send notifications to a ThreadLocal\n// regardless of its parameter type.\nclass ThreadLocalBase {\n public:\n  // Creates a new ValueHolder<T> object holding a default value passed to\n  // this ThreadLocal<T>'s constructor and returns it.  It is the caller's\n  // responsibility not to call this when the ThreadLocal<T> instance already\n  // has a value on the current thread.\n  virtual ThreadLocalValueHolderBase* NewValueForCurrentThread() const = 0;\n\n protected:\n  ThreadLocalBase() {}\n  virtual ~ThreadLocalBase() {}\n\n private:\n  ThreadLocalBase(const ThreadLocalBase&) = delete;\n  ThreadLocalBase& operator=(const ThreadLocalBase&) = delete;\n};\n\n// Maps a thread to a set of ThreadLocals that have values instantiated on that\n// thread and notifies them when the thread exits.  A ThreadLocal instance is\n// expected to persist until all threads it has values on have terminated.\nclass GTEST_API_ ThreadLocalRegistry {\n public:\n  // Registers thread_local_instance as having value on the current thread.\n  // Returns a value that can be used to identify the thread from other threads.\n  static ThreadLocalValueHolderBase* GetValueOnCurrentThread(\n      const ThreadLocalBase* thread_local_instance);\n\n  // Invoked when a ThreadLocal instance is destroyed.\n  static void OnThreadLocalDestroyed(\n      const ThreadLocalBase* thread_local_instance);\n};\n\nclass GTEST_API_ ThreadWithParamBase {\n public:\n  void Join();\n\n protected:\n  class Runnable {\n   public:\n    virtual ~Runnable() {}\n    virtual void Run() = 0;\n  };\n\n  ThreadWithParamBase(Runnable* runnable, Notification* thread_can_start);\n  virtual ~ThreadWithParamBase();\n\n private:\n  AutoHandle thread_;\n};\n\n// Helper class for testing Google Test's multi-threading constructs.\ntemplate <typename T>\nclass ThreadWithParam : public ThreadWithParamBase {\n public:\n  typedef void UserThreadFunc(T);\n\n  ThreadWithParam(UserThreadFunc* func, T param, Notification* thread_can_start)\n      : ThreadWithParamBase(new RunnableImpl(func, param), thread_can_start) {}\n  virtual ~ThreadWithParam() {}\n\n private:\n  class RunnableImpl : public Runnable {\n   public:\n    RunnableImpl(UserThreadFunc* func, T param) : func_(func), param_(param) {}\n    virtual ~RunnableImpl() {}\n    virtual void Run() { func_(param_); }\n\n   private:\n    UserThreadFunc* const func_;\n    const T param_;\n\n    RunnableImpl(const RunnableImpl&) = delete;\n    RunnableImpl& operator=(const RunnableImpl&) = delete;\n  };\n\n  ThreadWithParam(const ThreadWithParam&) = delete;\n  ThreadWithParam& operator=(const ThreadWithParam&) = delete;\n};\n\n// Implements thread-local storage on Windows systems.\n//\n//   // Thread 1\n//   ThreadLocal<int> tl(100);  // 100 is the default value for each thread.\n//\n//   // Thread 2\n//   tl.set(150);  // Changes the value for thread 2 only.\n//   EXPECT_EQ(150, tl.get());\n//\n//   // Thread 1\n//   EXPECT_EQ(100, tl.get());  // In thread 1, tl has the original value.\n//   tl.set(200);\n//   EXPECT_EQ(200, tl.get());\n//\n// The template type argument T must have a public copy constructor.\n// In addition, the default ThreadLocal constructor requires T to have\n// a public default constructor.\n//\n// The users of a TheadLocal instance have to make sure that all but one\n// threads (including the main one) using that instance have exited before\n// destroying it. Otherwise, the per-thread objects managed for them by the\n// ThreadLocal instance are not guaranteed to be destroyed on all platforms.\n//\n// Google Test only uses global ThreadLocal objects.  That means they\n// will die after main() has returned.  Therefore, no per-thread\n// object managed by Google Test will be leaked as long as all threads\n// using Google Test have exited when main() returns.\ntemplate <typename T>\nclass ThreadLocal : public ThreadLocalBase {\n public:\n  ThreadLocal() : default_factory_(new DefaultValueHolderFactory()) {}\n  explicit ThreadLocal(const T& value)\n      : default_factory_(new InstanceValueHolderFactory(value)) {}\n\n  ~ThreadLocal() override { ThreadLocalRegistry::OnThreadLocalDestroyed(this); }\n\n  T* pointer() { return GetOrCreateValue(); }\n  const T* pointer() const { return GetOrCreateValue(); }\n  const T& get() const { return *pointer(); }\n  void set(const T& value) { *pointer() = value; }\n\n private:\n  // Holds a value of T.  Can be deleted via its base class without the caller\n  // knowing the type of T.\n  class ValueHolder : public ThreadLocalValueHolderBase {\n   public:\n    ValueHolder() : value_() {}\n    explicit ValueHolder(const T& value) : value_(value) {}\n\n    T* pointer() { return &value_; }\n\n   private:\n    T value_;\n    ValueHolder(const ValueHolder&) = delete;\n    ValueHolder& operator=(const ValueHolder&) = delete;\n  };\n\n  T* GetOrCreateValue() const {\n    return static_cast<ValueHolder*>(\n               ThreadLocalRegistry::GetValueOnCurrentThread(this))\n        ->pointer();\n  }\n\n  ThreadLocalValueHolderBase* NewValueForCurrentThread() const override {\n    return default_factory_->MakeNewHolder();\n  }\n\n  class ValueHolderFactory {\n   public:\n    ValueHolderFactory() {}\n    virtual ~ValueHolderFactory() {}\n    virtual ValueHolder* MakeNewHolder() const = 0;\n\n   private:\n    ValueHolderFactory(const ValueHolderFactory&) = delete;\n    ValueHolderFactory& operator=(const ValueHolderFactory&) = delete;\n  };\n\n  class DefaultValueHolderFactory : public ValueHolderFactory {\n   public:\n    DefaultValueHolderFactory() {}\n    ValueHolder* MakeNewHolder() const override { return new ValueHolder(); }\n\n   private:\n    DefaultValueHolderFactory(const DefaultValueHolderFactory&) = delete;\n    DefaultValueHolderFactory& operator=(const DefaultValueHolderFactory&) =\n        delete;\n  };\n\n  class InstanceValueHolderFactory : public ValueHolderFactory {\n   public:\n    explicit InstanceValueHolderFactory(const T& value) : value_(value) {}\n    ValueHolder* MakeNewHolder() const override {\n      return new ValueHolder(value_);\n    }\n\n   private:\n    const T value_;  // The value for each thread.\n\n    InstanceValueHolderFactory(const InstanceValueHolderFactory&) = delete;\n    InstanceValueHolderFactory& operator=(const InstanceValueHolderFactory&) =\n        delete;\n  };\n\n  std::unique_ptr<ValueHolderFactory> default_factory_;\n\n  ThreadLocal(const ThreadLocal&) = delete;\n  ThreadLocal& operator=(const ThreadLocal&) = delete;\n};\n\n#elif GTEST_HAS_PTHREAD\n\n// MutexBase and Mutex implement mutex on pthreads-based platforms.\nclass MutexBase {\n public:\n  // Acquires this mutex.\n  void Lock() {\n    GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&mutex_));\n    owner_ = pthread_self();\n    has_owner_ = true;\n  }\n\n  // Releases this mutex.\n  void Unlock() {\n    // Since the lock is being released the owner_ field should no longer be\n    // considered valid. We don't protect writing to has_owner_ here, as it's\n    // the caller's responsibility to ensure that the current thread holds the\n    // mutex when this is called.\n    has_owner_ = false;\n    GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&mutex_));\n  }\n\n  // Does nothing if the current thread holds the mutex. Otherwise, crashes\n  // with high probability.\n  void AssertHeld() const {\n    GTEST_CHECK_(has_owner_ && pthread_equal(owner_, pthread_self()))\n        << \"The current thread is not holding the mutex @\" << this;\n  }\n\n  // A static mutex may be used before main() is entered.  It may even\n  // be used before the dynamic initialization stage.  Therefore we\n  // must be able to initialize a static mutex object at link time.\n  // This means MutexBase has to be a POD and its member variables\n  // have to be public.\n public:\n  pthread_mutex_t mutex_;  // The underlying pthread mutex.\n  // has_owner_ indicates whether the owner_ field below contains a valid thread\n  // ID and is therefore safe to inspect (e.g., to use in pthread_equal()). All\n  // accesses to the owner_ field should be protected by a check of this field.\n  // An alternative might be to memset() owner_ to all zeros, but there's no\n  // guarantee that a zero'd pthread_t is necessarily invalid or even different\n  // from pthread_self().\n  bool has_owner_;\n  pthread_t owner_;  // The thread holding the mutex.\n};\n\n// Forward-declares a static mutex.\n#define GTEST_DECLARE_STATIC_MUTEX_(mutex) \\\n  extern ::testing::internal::MutexBase mutex\n\n// Defines and statically (i.e. at link time) initializes a static mutex.\n// The initialization list here does not explicitly initialize each field,\n// instead relying on default initialization for the unspecified fields. In\n// particular, the owner_ field (a pthread_t) is not explicitly initialized.\n// This allows initialization to work whether pthread_t is a scalar or struct.\n// The flag -Wmissing-field-initializers must not be specified for this to work.\n#define GTEST_DEFINE_STATIC_MUTEX_(mutex) \\\n  ::testing::internal::MutexBase mutex = {PTHREAD_MUTEX_INITIALIZER, false, 0}\n\n// The Mutex class can only be used for mutexes created at runtime. It\n// shares its API with MutexBase otherwise.\nclass Mutex : public MutexBase {\n public:\n  Mutex() {\n    GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_init(&mutex_, nullptr));\n    has_owner_ = false;\n  }\n  ~Mutex() { GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&mutex_)); }\n\n private:\n  Mutex(const Mutex&) = delete;\n  Mutex& operator=(const Mutex&) = delete;\n};\n\n// We cannot name this class MutexLock because the ctor declaration would\n// conflict with a macro named MutexLock, which is defined on some\n// platforms. That macro is used as a defensive measure to prevent against\n// inadvertent misuses of MutexLock like \"MutexLock(&mu)\" rather than\n// \"MutexLock l(&mu)\".  Hence the typedef trick below.\nclass GTestMutexLock {\n public:\n  explicit GTestMutexLock(MutexBase* mutex) : mutex_(mutex) { mutex_->Lock(); }\n\n  ~GTestMutexLock() { mutex_->Unlock(); }\n\n private:\n  MutexBase* const mutex_;\n\n  GTestMutexLock(const GTestMutexLock&) = delete;\n  GTestMutexLock& operator=(const GTestMutexLock&) = delete;\n};\n\ntypedef GTestMutexLock MutexLock;\n\n// Helpers for ThreadLocal.\n\n// pthread_key_create() requires DeleteThreadLocalValue() to have\n// C-linkage.  Therefore it cannot be templatized to access\n// ThreadLocal<T>.  Hence the need for class\n// ThreadLocalValueHolderBase.\nclass ThreadLocalValueHolderBase {\n public:\n  virtual ~ThreadLocalValueHolderBase() {}\n};\n\n// Called by pthread to delete thread-local data stored by\n// pthread_setspecific().\nextern \"C\" inline void DeleteThreadLocalValue(void* value_holder) {\n  delete static_cast<ThreadLocalValueHolderBase*>(value_holder);\n}\n\n// Implements thread-local storage on pthreads-based systems.\ntemplate <typename T>\nclass GTEST_API_ ThreadLocal {\n public:\n  ThreadLocal()\n      : key_(CreateKey()), default_factory_(new DefaultValueHolderFactory()) {}\n  explicit ThreadLocal(const T& value)\n      : key_(CreateKey()),\n        default_factory_(new InstanceValueHolderFactory(value)) {}\n\n  ~ThreadLocal() {\n    // Destroys the managed object for the current thread, if any.\n    DeleteThreadLocalValue(pthread_getspecific(key_));\n\n    // Releases resources associated with the key.  This will *not*\n    // delete managed objects for other threads.\n    GTEST_CHECK_POSIX_SUCCESS_(pthread_key_delete(key_));\n  }\n\n  T* pointer() { return GetOrCreateValue(); }\n  const T* pointer() const { return GetOrCreateValue(); }\n  const T& get() const { return *pointer(); }\n  void set(const T& value) { *pointer() = value; }\n\n private:\n  // Holds a value of type T.\n  class ValueHolder : public ThreadLocalValueHolderBase {\n   public:\n    ValueHolder() : value_() {}\n    explicit ValueHolder(const T& value) : value_(value) {}\n\n    T* pointer() { return &value_; }\n\n   private:\n    T value_;\n    ValueHolder(const ValueHolder&) = delete;\n    ValueHolder& operator=(const ValueHolder&) = delete;\n  };\n\n  static pthread_key_t CreateKey() {\n    pthread_key_t key;\n    // When a thread exits, DeleteThreadLocalValue() will be called on\n    // the object managed for that thread.\n    GTEST_CHECK_POSIX_SUCCESS_(\n        pthread_key_create(&key, &DeleteThreadLocalValue));\n    return key;\n  }\n\n  T* GetOrCreateValue() const {\n    ThreadLocalValueHolderBase* const holder =\n        static_cast<ThreadLocalValueHolderBase*>(pthread_getspecific(key_));\n    if (holder != nullptr) {\n      return CheckedDowncastToActualType<ValueHolder>(holder)->pointer();\n    }\n\n    ValueHolder* const new_holder = default_factory_->MakeNewHolder();\n    ThreadLocalValueHolderBase* const holder_base = new_holder;\n    GTEST_CHECK_POSIX_SUCCESS_(pthread_setspecific(key_, holder_base));\n    return new_holder->pointer();\n  }\n\n  class ValueHolderFactory {\n   public:\n    ValueHolderFactory() {}\n    virtual ~ValueHolderFactory() {}\n    virtual ValueHolder* MakeNewHolder() const = 0;\n\n   private:\n    ValueHolderFactory(const ValueHolderFactory&) = delete;\n    ValueHolderFactory& operator=(const ValueHolderFactory&) = delete;\n  };\n\n  class DefaultValueHolderFactory : public ValueHolderFactory {\n   public:\n    DefaultValueHolderFactory() {}\n    ValueHolder* MakeNewHolder() const override { return new ValueHolder(); }\n\n   private:\n    DefaultValueHolderFactory(const DefaultValueHolderFactory&) = delete;\n    DefaultValueHolderFactory& operator=(const DefaultValueHolderFactory&) =\n        delete;\n  };\n\n  class InstanceValueHolderFactory : public ValueHolderFactory {\n   public:\n    explicit InstanceValueHolderFactory(const T& value) : value_(value) {}\n    ValueHolder* MakeNewHolder() const override {\n      return new ValueHolder(value_);\n    }\n\n   private:\n    const T value_;  // The value for each thread.\n\n    InstanceValueHolderFactory(const InstanceValueHolderFactory&) = delete;\n    InstanceValueHolderFactory& operator=(const InstanceValueHolderFactory&) =\n        delete;\n  };\n\n  // A key pthreads uses for looking up per-thread values.\n  const pthread_key_t key_;\n  std::unique_ptr<ValueHolderFactory> default_factory_;\n\n  ThreadLocal(const ThreadLocal&) = delete;\n  ThreadLocal& operator=(const ThreadLocal&) = delete;\n};\n\n#endif  // GTEST_HAS_MUTEX_AND_THREAD_LOCAL_\n\n#else  // GTEST_IS_THREADSAFE\n\n// A dummy implementation of synchronization primitives (mutex, lock,\n// and thread-local variable).  Necessary for compiling Google Test where\n// mutex is not supported - using Google Test in multiple threads is not\n// supported on such platforms.\n\nclass Mutex {\n public:\n  Mutex() {}\n  void Lock() {}\n  void Unlock() {}\n  void AssertHeld() const {}\n};\n\n#define GTEST_DECLARE_STATIC_MUTEX_(mutex) \\\n  extern ::testing::internal::Mutex mutex\n\n#define GTEST_DEFINE_STATIC_MUTEX_(mutex) ::testing::internal::Mutex mutex\n\n// We cannot name this class MutexLock because the ctor declaration would\n// conflict with a macro named MutexLock, which is defined on some\n// platforms. That macro is used as a defensive measure to prevent against\n// inadvertent misuses of MutexLock like \"MutexLock(&mu)\" rather than\n// \"MutexLock l(&mu)\".  Hence the typedef trick below.\nclass GTestMutexLock {\n public:\n  explicit GTestMutexLock(Mutex*) {}  // NOLINT\n};\n\ntypedef GTestMutexLock MutexLock;\n\ntemplate <typename T>\nclass GTEST_API_ ThreadLocal {\n public:\n  ThreadLocal() : value_() {}\n  explicit ThreadLocal(const T& value) : value_(value) {}\n  T* pointer() { return &value_; }\n  const T* pointer() const { return &value_; }\n  const T& get() const { return value_; }\n  void set(const T& value) { value_ = value; }\n\n private:\n  T value_;\n};\n\n#endif  // GTEST_IS_THREADSAFE\n\n// Returns the number of threads running in the process, or 0 to indicate that\n// we cannot detect it.\nGTEST_API_ size_t GetThreadCount();\n\n#if GTEST_OS_WINDOWS\n#define GTEST_PATH_SEP_ \"\\\\\"\n#define GTEST_HAS_ALT_PATH_SEP_ 1\n#else\n#define GTEST_PATH_SEP_ \"/\"\n#define GTEST_HAS_ALT_PATH_SEP_ 0\n#endif  // GTEST_OS_WINDOWS\n\n// Utilities for char.\n\n// isspace(int ch) and friends accept an unsigned char or EOF.  char\n// may be signed, depending on the compiler (or compiler flags).\n// Therefore we need to cast a char to unsigned char before calling\n// isspace(), etc.\n\ninline bool IsAlpha(char ch) {\n  return isalpha(static_cast<unsigned char>(ch)) != 0;\n}\ninline bool IsAlNum(char ch) {\n  return isalnum(static_cast<unsigned char>(ch)) != 0;\n}\ninline bool IsDigit(char ch) {\n  return isdigit(static_cast<unsigned char>(ch)) != 0;\n}\ninline bool IsLower(char ch) {\n  return islower(static_cast<unsigned char>(ch)) != 0;\n}\ninline bool IsSpace(char ch) {\n  return isspace(static_cast<unsigned char>(ch)) != 0;\n}\ninline bool IsUpper(char ch) {\n  return isupper(static_cast<unsigned char>(ch)) != 0;\n}\ninline bool IsXDigit(char ch) {\n  return isxdigit(static_cast<unsigned char>(ch)) != 0;\n}\n#ifdef __cpp_char8_t\ninline bool IsXDigit(char8_t ch) {\n  return isxdigit(static_cast<unsigned char>(ch)) != 0;\n}\n#endif\ninline bool IsXDigit(char16_t ch) {\n  const unsigned char low_byte = static_cast<unsigned char>(ch);\n  return ch == low_byte && isxdigit(low_byte) != 0;\n}\ninline bool IsXDigit(char32_t ch) {\n  const unsigned char low_byte = static_cast<unsigned char>(ch);\n  return ch == low_byte && isxdigit(low_byte) != 0;\n}\ninline bool IsXDigit(wchar_t ch) {\n  const unsigned char low_byte = static_cast<unsigned char>(ch);\n  return ch == low_byte && isxdigit(low_byte) != 0;\n}\n\ninline char ToLower(char ch) {\n  return static_cast<char>(tolower(static_cast<unsigned char>(ch)));\n}\ninline char ToUpper(char ch) {\n  return static_cast<char>(toupper(static_cast<unsigned char>(ch)));\n}\n\ninline std::string StripTrailingSpaces(std::string str) {\n  std::string::iterator it = str.end();\n  while (it != str.begin() && IsSpace(*--it)) it = str.erase(it);\n  return str;\n}\n\n// The testing::internal::posix namespace holds wrappers for common\n// POSIX functions.  These wrappers hide the differences between\n// Windows/MSVC and POSIX systems.  Since some compilers define these\n// standard functions as macros, the wrapper cannot have the same name\n// as the wrapped function.\n\nnamespace posix {\n\n// Functions with a different name on Windows.\n\n#if GTEST_OS_WINDOWS\n\ntypedef struct _stat StatStruct;\n\n#ifdef __BORLANDC__\ninline int DoIsATTY(int fd) { return isatty(fd); }\ninline int StrCaseCmp(const char* s1, const char* s2) {\n  return stricmp(s1, s2);\n}\ninline char* StrDup(const char* src) { return strdup(src); }\n#else  // !__BORLANDC__\n#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_ZOS || GTEST_OS_IOS || \\\n    GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT || defined(ESP_PLATFORM)\ninline int DoIsATTY(int /* fd */) { return 0; }\n#else\ninline int DoIsATTY(int fd) { return _isatty(fd); }\n#endif  // GTEST_OS_WINDOWS_MOBILE\ninline int StrCaseCmp(const char* s1, const char* s2) {\n  return _stricmp(s1, s2);\n}\ninline char* StrDup(const char* src) { return _strdup(src); }\n#endif  // __BORLANDC__\n\n#if GTEST_OS_WINDOWS_MOBILE\ninline int FileNo(FILE* file) { return reinterpret_cast<int>(_fileno(file)); }\n// Stat(), RmDir(), and IsDir() are not needed on Windows CE at this\n// time and thus not defined there.\n#else\ninline int FileNo(FILE* file) { return _fileno(file); }\ninline int Stat(const char* path, StatStruct* buf) { return _stat(path, buf); }\ninline int RmDir(const char* dir) { return _rmdir(dir); }\ninline bool IsDir(const StatStruct& st) { return (_S_IFDIR & st.st_mode) != 0; }\n#endif  // GTEST_OS_WINDOWS_MOBILE\n\n#elif GTEST_OS_ESP8266\ntypedef struct stat StatStruct;\n\ninline int FileNo(FILE* file) { return fileno(file); }\ninline int DoIsATTY(int fd) { return isatty(fd); }\ninline int Stat(const char* path, StatStruct* buf) {\n  // stat function not implemented on ESP8266\n  return 0;\n}\ninline int StrCaseCmp(const char* s1, const char* s2) {\n  return strcasecmp(s1, s2);\n}\ninline char* StrDup(const char* src) { return strdup(src); }\ninline int RmDir(const char* dir) { return rmdir(dir); }\ninline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }\n\n#else\n\ntypedef struct stat StatStruct;\n\ninline int FileNo(FILE* file) { return fileno(file); }\ninline int DoIsATTY(int fd) { return isatty(fd); }\ninline int Stat(const char* path, StatStruct* buf) { return stat(path, buf); }\ninline int StrCaseCmp(const char* s1, const char* s2) {\n  return strcasecmp(s1, s2);\n}\ninline char* StrDup(const char* src) { return strdup(src); }\ninline int RmDir(const char* dir) { return rmdir(dir); }\ninline bool IsDir(const StatStruct& st) { return S_ISDIR(st.st_mode); }\n\n#endif  // GTEST_OS_WINDOWS\n\ninline int IsATTY(int fd) {\n  // DoIsATTY might change errno (for example ENOTTY in case you redirect stdout\n  // to a file on Linux), which is unexpected, so save the previous value, and\n  // restore it after the call.\n  int savedErrno = errno;\n  int isAttyValue = DoIsATTY(fd);\n  errno = savedErrno;\n\n  return isAttyValue;\n}\n\n// Functions deprecated by MSVC 8.0.\n\nGTEST_DISABLE_MSC_DEPRECATED_PUSH_()\n\n// ChDir(), FReopen(), FDOpen(), Read(), Write(), Close(), and\n// StrError() aren't needed on Windows CE at this time and thus not\n// defined there.\n\n#if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \\\n    !GTEST_OS_WINDOWS_RT && !GTEST_OS_ESP8266 && !GTEST_OS_XTENSA\ninline int ChDir(const char* dir) { return chdir(dir); }\n#endif\ninline FILE* FOpen(const char* path, const char* mode) {\n#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW\n  struct wchar_codecvt : public std::codecvt<wchar_t, char, std::mbstate_t> {};\n  std::wstring_convert<wchar_codecvt> converter;\n  std::wstring wide_path = converter.from_bytes(path);\n  std::wstring wide_mode = converter.from_bytes(mode);\n  return _wfopen(wide_path.c_str(), wide_mode.c_str());\n#else   // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW\n  return fopen(path, mode);\n#endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW\n}\n#if !GTEST_OS_WINDOWS_MOBILE\ninline FILE* FReopen(const char* path, const char* mode, FILE* stream) {\n  return freopen(path, mode, stream);\n}\ninline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); }\n#endif\ninline int FClose(FILE* fp) { return fclose(fp); }\n#if !GTEST_OS_WINDOWS_MOBILE\ninline int Read(int fd, void* buf, unsigned int count) {\n  return static_cast<int>(read(fd, buf, count));\n}\ninline int Write(int fd, const void* buf, unsigned int count) {\n  return static_cast<int>(write(fd, buf, count));\n}\ninline int Close(int fd) { return close(fd); }\ninline const char* StrError(int errnum) { return strerror(errnum); }\n#endif\ninline const char* GetEnv(const char* name) {\n#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || \\\n    GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_XTENSA\n  // We are on an embedded platform, which has no environment variables.\n  static_cast<void>(name);  // To prevent 'unused argument' warning.\n  return nullptr;\n#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)\n  // Environment variables which we programmatically clear will be set to the\n  // empty string rather than unset (NULL).  Handle that case.\n  const char* const env = getenv(name);\n  return (env != nullptr && env[0] != '\\0') ? env : nullptr;\n#else\n  return getenv(name);\n#endif\n}\n\nGTEST_DISABLE_MSC_DEPRECATED_POP_()\n\n#if GTEST_OS_WINDOWS_MOBILE\n// Windows CE has no C library. The abort() function is used in\n// several places in Google Test. This implementation provides a reasonable\n// imitation of standard behaviour.\n[[noreturn]] void Abort();\n#else\n[[noreturn]] inline void Abort() { abort(); }\n#endif  // GTEST_OS_WINDOWS_MOBILE\n\n}  // namespace posix\n\n// MSVC \"deprecates\" snprintf and issues warnings wherever it is used.  In\n// order to avoid these warnings, we need to use _snprintf or _snprintf_s on\n// MSVC-based platforms.  We map the GTEST_SNPRINTF_ macro to the appropriate\n// function in order to achieve that.  We use macro definition here because\n// snprintf is a variadic function.\n#if _MSC_VER && !GTEST_OS_WINDOWS_MOBILE\n// MSVC 2005 and above support variadic macros.\n#define GTEST_SNPRINTF_(buffer, size, format, ...) \\\n  _snprintf_s(buffer, size, size, format, __VA_ARGS__)\n#elif defined(_MSC_VER)\n// Windows CE does not define _snprintf_s\n#define GTEST_SNPRINTF_ _snprintf\n#else\n#define GTEST_SNPRINTF_ snprintf\n#endif\n\n// The biggest signed integer type the compiler supports.\n//\n// long long is guaranteed to be at least 64-bits in C++11.\nusing BiggestInt = long long;  // NOLINT\n\n// The maximum number a BiggestInt can represent.\nconstexpr BiggestInt kMaxBiggestInt = (std::numeric_limits<BiggestInt>::max)();\n\n// This template class serves as a compile-time function from size to\n// type.  It maps a size in bytes to a primitive type with that\n// size. e.g.\n//\n//   TypeWithSize<4>::UInt\n//\n// is typedef-ed to be unsigned int (unsigned integer made up of 4\n// bytes).\n//\n// Such functionality should belong to STL, but I cannot find it\n// there.\n//\n// Google Test uses this class in the implementation of floating-point\n// comparison.\n//\n// For now it only handles UInt (unsigned int) as that's all Google Test\n// needs.  Other types can be easily added in the future if need\n// arises.\ntemplate <size_t size>\nclass TypeWithSize {\n public:\n  // This prevents the user from using TypeWithSize<N> with incorrect\n  // values of N.\n  using UInt = void;\n};\n\n// The specialization for size 4.\ntemplate <>\nclass TypeWithSize<4> {\n public:\n  using Int = std::int32_t;\n  using UInt = std::uint32_t;\n};\n\n// The specialization for size 8.\ntemplate <>\nclass TypeWithSize<8> {\n public:\n  using Int = std::int64_t;\n  using UInt = std::uint64_t;\n};\n\n// Integer types of known sizes.\nusing TimeInMillis = int64_t;  // Represents time in milliseconds.\n\n// Utilities for command line flags and environment variables.\n\n// Macro for referencing flags.\n#if !defined(GTEST_FLAG)\n#define GTEST_FLAG_NAME_(name) gtest_##name\n#define GTEST_FLAG(name) FLAGS_gtest_##name\n#endif  // !defined(GTEST_FLAG)\n\n// Pick a command line flags implementation.\n#if GTEST_HAS_ABSL\n\n// Macros for defining flags.\n#define GTEST_DEFINE_bool_(name, default_val, doc) \\\n  ABSL_FLAG(bool, GTEST_FLAG_NAME_(name), default_val, doc)\n#define GTEST_DEFINE_int32_(name, default_val, doc) \\\n  ABSL_FLAG(int32_t, GTEST_FLAG_NAME_(name), default_val, doc)\n#define GTEST_DEFINE_string_(name, default_val, doc) \\\n  ABSL_FLAG(std::string, GTEST_FLAG_NAME_(name), default_val, doc)\n\n// Macros for declaring flags.\n#define GTEST_DECLARE_bool_(name) \\\n  ABSL_DECLARE_FLAG(bool, GTEST_FLAG_NAME_(name))\n#define GTEST_DECLARE_int32_(name) \\\n  ABSL_DECLARE_FLAG(int32_t, GTEST_FLAG_NAME_(name))\n#define GTEST_DECLARE_string_(name) \\\n  ABSL_DECLARE_FLAG(std::string, GTEST_FLAG_NAME_(name))\n\n#define GTEST_FLAG_SAVER_ ::absl::FlagSaver\n\n#define GTEST_FLAG_GET(name) ::absl::GetFlag(GTEST_FLAG(name))\n#define GTEST_FLAG_SET(name, value) \\\n  (void)(::absl::SetFlag(&GTEST_FLAG(name), value))\n#define GTEST_USE_OWN_FLAGFILE_FLAG_ 0\n\n#else  // GTEST_HAS_ABSL\n\n// Macros for defining flags.\n#define GTEST_DEFINE_bool_(name, default_val, doc)  \\\n  namespace testing {                               \\\n  GTEST_API_ bool GTEST_FLAG(name) = (default_val); \\\n  }                                                 \\\n  static_assert(true, \"no-op to require trailing semicolon\")\n#define GTEST_DEFINE_int32_(name, default_val, doc)         \\\n  namespace testing {                                       \\\n  GTEST_API_ std::int32_t GTEST_FLAG(name) = (default_val); \\\n  }                                                         \\\n  static_assert(true, \"no-op to require trailing semicolon\")\n#define GTEST_DEFINE_string_(name, default_val, doc)         \\\n  namespace testing {                                        \\\n  GTEST_API_ ::std::string GTEST_FLAG(name) = (default_val); \\\n  }                                                          \\\n  static_assert(true, \"no-op to require trailing semicolon\")\n\n// Macros for declaring flags.\n#define GTEST_DECLARE_bool_(name)          \\\n  namespace testing {                      \\\n  GTEST_API_ extern bool GTEST_FLAG(name); \\\n  }                                        \\\n  static_assert(true, \"no-op to require trailing semicolon\")\n#define GTEST_DECLARE_int32_(name)                 \\\n  namespace testing {                              \\\n  GTEST_API_ extern std::int32_t GTEST_FLAG(name); \\\n  }                                                \\\n  static_assert(true, \"no-op to require trailing semicolon\")\n#define GTEST_DECLARE_string_(name)                 \\\n  namespace testing {                               \\\n  GTEST_API_ extern ::std::string GTEST_FLAG(name); \\\n  }                                                 \\\n  static_assert(true, \"no-op to require trailing semicolon\")\n\n#define GTEST_FLAG_SAVER_ ::testing::internal::GTestFlagSaver\n\n#define GTEST_FLAG_GET(name) ::testing::GTEST_FLAG(name)\n#define GTEST_FLAG_SET(name, value) (void)(::testing::GTEST_FLAG(name) = value)\n#define GTEST_USE_OWN_FLAGFILE_FLAG_ 1\n\n#endif  // GTEST_HAS_ABSL\n\n// Thread annotations\n#if !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_)\n#define GTEST_EXCLUSIVE_LOCK_REQUIRED_(locks)\n#define GTEST_LOCK_EXCLUDED_(locks)\n#endif  // !defined(GTEST_EXCLUSIVE_LOCK_REQUIRED_)\n\n// Parses 'str' for a 32-bit signed integer.  If successful, writes the result\n// to *value and returns true; otherwise leaves *value unchanged and returns\n// false.\nGTEST_API_ bool ParseInt32(const Message& src_text, const char* str,\n                           int32_t* value);\n\n// Parses a bool/int32_t/string from the environment variable\n// corresponding to the given Google Test flag.\nbool BoolFromGTestEnv(const char* flag, bool default_val);\nGTEST_API_ int32_t Int32FromGTestEnv(const char* flag, int32_t default_val);\nstd::string OutputFlagAlsoCheckEnvVar();\nconst char* StringFromGTestEnv(const char* flag, const char* default_val);\n\n}  // namespace internal\n}  // namespace testing\n\n#if !defined(GTEST_INTERNAL_DEPRECATED)\n\n// Internal Macro to mark an API deprecated, for googletest usage only\n// Usage: class GTEST_INTERNAL_DEPRECATED(message) MyClass or\n// GTEST_INTERNAL_DEPRECATED(message) <return_type> myFunction(); Every usage of\n// a deprecated entity will trigger a warning when compiled with\n// `-Wdeprecated-declarations` option (clang, gcc, any __GNUC__ compiler).\n// For msvc /W3 option will need to be used\n// Note that for 'other' compilers this macro evaluates to nothing to prevent\n// compilations errors.\n#if defined(_MSC_VER)\n#define GTEST_INTERNAL_DEPRECATED(message) __declspec(deprecated(message))\n#elif defined(__GNUC__)\n#define GTEST_INTERNAL_DEPRECATED(message) __attribute__((deprecated(message)))\n#else\n#define GTEST_INTERNAL_DEPRECATED(message)\n#endif\n\n#endif  // !defined(GTEST_INTERNAL_DEPRECATED)\n\n#if GTEST_HAS_ABSL\n// Always use absl::any for UniversalPrinter<> specializations if googletest\n// is built with absl support.\n#define GTEST_INTERNAL_HAS_ANY 1\n#include \"absl/types/any.h\"\nnamespace testing {\nnamespace internal {\nusing Any = ::absl::any;\n}  // namespace internal\n}  // namespace testing\n#else\n#ifdef __has_include\n#if __has_include(<any>) && __cplusplus >= 201703L\n// Otherwise for C++17 and higher use std::any for UniversalPrinter<>\n// specializations.\n#define GTEST_INTERNAL_HAS_ANY 1\n#include <any>\nnamespace testing {\nnamespace internal {\nusing Any = ::std::any;\n}  // namespace internal\n}  // namespace testing\n// The case where absl is configured NOT to alias std::any is not\n// supported.\n#endif  // __has_include(<any>) && __cplusplus >= 201703L\n#endif  // __has_include\n#endif  // GTEST_HAS_ABSL\n\n#if GTEST_HAS_ABSL\n// Always use absl::optional for UniversalPrinter<> specializations if\n// googletest is built with absl support.\n#define GTEST_INTERNAL_HAS_OPTIONAL 1\n#include \"absl/types/optional.h\"\nnamespace testing {\nnamespace internal {\ntemplate <typename T>\nusing Optional = ::absl::optional<T>;\ninline ::absl::nullopt_t Nullopt() { return ::absl::nullopt; }\n}  // namespace internal\n}  // namespace testing\n#else\n#ifdef __has_include\n#if __has_include(<optional>) && __cplusplus >= 201703L\n// Otherwise for C++17 and higher use std::optional for UniversalPrinter<>\n// specializations.\n#define GTEST_INTERNAL_HAS_OPTIONAL 1\n#include <optional>\nnamespace testing {\nnamespace internal {\ntemplate <typename T>\nusing Optional = ::std::optional<T>;\ninline ::std::nullopt_t Nullopt() { return ::std::nullopt; }\n}  // namespace internal\n}  // namespace testing\n// The case where absl is configured NOT to alias std::optional is not\n// supported.\n#endif  // __has_include(<optional>) && __cplusplus >= 201703L\n#endif  // __has_include\n#endif  // GTEST_HAS_ABSL\n\n#if GTEST_HAS_ABSL\n// Always use absl::string_view for Matcher<> specializations if googletest\n// is built with absl support.\n#define GTEST_INTERNAL_HAS_STRING_VIEW 1\n#include \"absl/strings/string_view.h\"\nnamespace testing {\nnamespace internal {\nusing StringView = ::absl::string_view;\n}  // namespace internal\n}  // namespace testing\n#else\n#ifdef __has_include\n#if __has_include(<string_view>) && __cplusplus >= 201703L\n// Otherwise for C++17 and higher use std::string_view for Matcher<>\n// specializations.\n#define GTEST_INTERNAL_HAS_STRING_VIEW 1\n#include <string_view>\nnamespace testing {\nnamespace internal {\nusing StringView = ::std::string_view;\n}  // namespace internal\n}  // namespace testing\n// The case where absl is configured NOT to alias std::string_view is not\n// supported.\n#endif  // __has_include(<string_view>) && __cplusplus >= 201703L\n#endif  // __has_include\n#endif  // GTEST_HAS_ABSL\n\n#if GTEST_HAS_ABSL\n// Always use absl::variant for UniversalPrinter<> specializations if googletest\n// is built with absl support.\n#define GTEST_INTERNAL_HAS_VARIANT 1\n#include \"absl/types/variant.h\"\nnamespace testing {\nnamespace internal {\ntemplate <typename... T>\nusing Variant = ::absl::variant<T...>;\n}  // namespace internal\n}  // namespace testing\n#else\n#ifdef __has_include\n#if __has_include(<variant>) && __cplusplus >= 201703L\n// Otherwise for C++17 and higher use std::variant for UniversalPrinter<>\n// specializations.\n#define GTEST_INTERNAL_HAS_VARIANT 1\n#include <variant>\nnamespace testing {\nnamespace internal {\ntemplate <typename... T>\nusing Variant = ::std::variant<T...>;\n}  // namespace internal\n}  // namespace testing\n// The case where absl is configured NOT to alias std::variant is not supported.\n#endif  // __has_include(<variant>) && __cplusplus >= 201703L\n#endif  // __has_include\n#endif  // GTEST_HAS_ABSL\n\n#endif  // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_PORT_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/include/gtest/internal/gtest-string.h",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// The Google C++ Testing and Mocking Framework (Google Test)\n//\n// This header file declares the String class and functions used internally by\n// Google Test.  They are subject to change without notice. They should not used\n// by code external to Google Test.\n//\n// This header file is #included by gtest-internal.h.\n// It should not be #included by other files.\n\n// IWYU pragma: private, include \"gtest/gtest.h\"\n// IWYU pragma: friend gtest/.*\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_\n#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_\n\n#ifdef __BORLANDC__\n// string.h is not guaranteed to provide strcpy on C++ Builder.\n#include <mem.h>\n#endif\n\n#include <string.h>\n\n#include <cstdint>\n#include <string>\n\n#include \"gtest/internal/gtest-port.h\"\n\nnamespace testing {\nnamespace internal {\n\n// String - an abstract class holding static string utilities.\nclass GTEST_API_ String {\n public:\n  // Static utility methods\n\n  // Clones a 0-terminated C string, allocating memory using new.  The\n  // caller is responsible for deleting the return value using\n  // delete[].  Returns the cloned string, or NULL if the input is\n  // NULL.\n  //\n  // This is different from strdup() in string.h, which allocates\n  // memory using malloc().\n  static const char* CloneCString(const char* c_str);\n\n#if GTEST_OS_WINDOWS_MOBILE\n  // Windows CE does not have the 'ANSI' versions of Win32 APIs. To be\n  // able to pass strings to Win32 APIs on CE we need to convert them\n  // to 'Unicode', UTF-16.\n\n  // Creates a UTF-16 wide string from the given ANSI string, allocating\n  // memory using new. The caller is responsible for deleting the return\n  // value using delete[]. Returns the wide string, or NULL if the\n  // input is NULL.\n  //\n  // The wide string is created using the ANSI codepage (CP_ACP) to\n  // match the behaviour of the ANSI versions of Win32 calls and the\n  // C runtime.\n  static LPCWSTR AnsiToUtf16(const char* c_str);\n\n  // Creates an ANSI string from the given wide string, allocating\n  // memory using new. The caller is responsible for deleting the return\n  // value using delete[]. Returns the ANSI string, or NULL if the\n  // input is NULL.\n  //\n  // The returned string is created using the ANSI codepage (CP_ACP) to\n  // match the behaviour of the ANSI versions of Win32 calls and the\n  // C runtime.\n  static const char* Utf16ToAnsi(LPCWSTR utf16_str);\n#endif\n\n  // Compares two C strings.  Returns true if and only if they have the same\n  // content.\n  //\n  // Unlike strcmp(), this function can handle NULL argument(s).  A\n  // NULL C string is considered different to any non-NULL C string,\n  // including the empty string.\n  static bool CStringEquals(const char* lhs, const char* rhs);\n\n  // Converts a wide C string to a String using the UTF-8 encoding.\n  // NULL will be converted to \"(null)\".  If an error occurred during\n  // the conversion, \"(failed to convert from wide string)\" is\n  // returned.\n  static std::string ShowWideCString(const wchar_t* wide_c_str);\n\n  // Compares two wide C strings.  Returns true if and only if they have the\n  // same content.\n  //\n  // Unlike wcscmp(), this function can handle NULL argument(s).  A\n  // NULL C string is considered different to any non-NULL C string,\n  // including the empty string.\n  static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs);\n\n  // Compares two C strings, ignoring case.  Returns true if and only if\n  // they have the same content.\n  //\n  // Unlike strcasecmp(), this function can handle NULL argument(s).\n  // A NULL C string is considered different to any non-NULL C string,\n  // including the empty string.\n  static bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs);\n\n  // Compares two wide C strings, ignoring case.  Returns true if and only if\n  // they have the same content.\n  //\n  // Unlike wcscasecmp(), this function can handle NULL argument(s).\n  // A NULL C string is considered different to any non-NULL wide C string,\n  // including the empty string.\n  // NB: The implementations on different platforms slightly differ.\n  // On windows, this method uses _wcsicmp which compares according to LC_CTYPE\n  // environment variable. On GNU platform this method uses wcscasecmp\n  // which compares according to LC_CTYPE category of the current locale.\n  // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the\n  // current locale.\n  static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs,\n                                               const wchar_t* rhs);\n\n  // Returns true if and only if the given string ends with the given suffix,\n  // ignoring case. Any string is considered to end with an empty suffix.\n  static bool EndsWithCaseInsensitive(const std::string& str,\n                                      const std::string& suffix);\n\n  // Formats an int value as \"%02d\".\n  static std::string FormatIntWidth2(int value);  // \"%02d\" for width == 2\n\n  // Formats an int value to given width with leading zeros.\n  static std::string FormatIntWidthN(int value, int width);\n\n  // Formats an int value as \"%X\".\n  static std::string FormatHexInt(int value);\n\n  // Formats an int value as \"%X\".\n  static std::string FormatHexUInt32(uint32_t value);\n\n  // Formats a byte as \"%02X\".\n  static std::string FormatByte(unsigned char value);\n\n private:\n  String();  // Not meant to be instantiated.\n};           // class String\n\n// Gets the content of the stringstream's buffer as an std::string.  Each '\\0'\n// character in the buffer is replaced with \"\\\\0\".\nGTEST_API_ std::string StringStreamToString(::std::stringstream* stream);\n\n}  // namespace internal\n}  // namespace testing\n\n#endif  // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/include/gtest/internal/gtest-type-util.h",
    "content": "// Copyright 2008 Google Inc.\n// All Rights Reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Type utilities needed for implementing typed and type-parameterized\n// tests.\n\n// IWYU pragma: private, include \"gtest/gtest.h\"\n// IWYU pragma: friend gtest/.*\n// IWYU pragma: friend gmock/.*\n\n#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_\n#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_\n\n#include \"gtest/internal/gtest-port.h\"\n\n// #ifdef __GNUC__ is too general here.  It is possible to use gcc without using\n// libstdc++ (which is where cxxabi.h comes from).\n#if GTEST_HAS_CXXABI_H_\n#include <cxxabi.h>\n#elif defined(__HP_aCC)\n#include <acxx_demangle.h>\n#endif  // GTEST_HASH_CXXABI_H_\n\nnamespace testing {\nnamespace internal {\n\n// Canonicalizes a given name with respect to the Standard C++ Library.\n// This handles removing the inline namespace within `std` that is\n// used by various standard libraries (e.g., `std::__1`).  Names outside\n// of namespace std are returned unmodified.\ninline std::string CanonicalizeForStdLibVersioning(std::string s) {\n  static const char prefix[] = \"std::__\";\n  if (s.compare(0, strlen(prefix), prefix) == 0) {\n    std::string::size_type end = s.find(\"::\", strlen(prefix));\n    if (end != s.npos) {\n      // Erase everything between the initial `std` and the second `::`.\n      s.erase(strlen(\"std\"), end - strlen(\"std\"));\n    }\n  }\n  return s;\n}\n\n#if GTEST_HAS_RTTI\n// GetTypeName(const std::type_info&) returns a human-readable name of type T.\ninline std::string GetTypeName(const std::type_info& type) {\n  const char* const name = type.name();\n#if GTEST_HAS_CXXABI_H_ || defined(__HP_aCC)\n  int status = 0;\n  // gcc's implementation of typeid(T).name() mangles the type name,\n  // so we have to demangle it.\n#if GTEST_HAS_CXXABI_H_\n  using abi::__cxa_demangle;\n#endif  // GTEST_HAS_CXXABI_H_\n  char* const readable_name = __cxa_demangle(name, nullptr, nullptr, &status);\n  const std::string name_str(status == 0 ? readable_name : name);\n  free(readable_name);\n  return CanonicalizeForStdLibVersioning(name_str);\n#else\n  return name;\n#endif  // GTEST_HAS_CXXABI_H_ || __HP_aCC\n}\n#endif  // GTEST_HAS_RTTI\n\n// GetTypeName<T>() returns a human-readable name of type T if and only if\n// RTTI is enabled, otherwise it returns a dummy type name.\n// NB: This function is also used in Google Mock, so don't move it inside of\n// the typed-test-only section below.\ntemplate <typename T>\nstd::string GetTypeName() {\n#if GTEST_HAS_RTTI\n  return GetTypeName(typeid(T));\n#else\n  return \"<type>\";\n#endif  // GTEST_HAS_RTTI\n}\n\n// A unique type indicating an empty node\nstruct None {};\n\n#define GTEST_TEMPLATE_ \\\n  template <typename T> \\\n  class\n\n// The template \"selector\" struct TemplateSel<Tmpl> is used to\n// represent Tmpl, which must be a class template with one type\n// parameter, as a type.  TemplateSel<Tmpl>::Bind<T>::type is defined\n// as the type Tmpl<T>.  This allows us to actually instantiate the\n// template \"selected\" by TemplateSel<Tmpl>.\n//\n// This trick is necessary for simulating typedef for class templates,\n// which C++ doesn't support directly.\ntemplate <GTEST_TEMPLATE_ Tmpl>\nstruct TemplateSel {\n  template <typename T>\n  struct Bind {\n    typedef Tmpl<T> type;\n  };\n};\n\n#define GTEST_BIND_(TmplSel, T) TmplSel::template Bind<T>::type\n\ntemplate <GTEST_TEMPLATE_ Head_, GTEST_TEMPLATE_... Tail_>\nstruct Templates {\n  using Head = TemplateSel<Head_>;\n  using Tail = Templates<Tail_...>;\n};\n\ntemplate <GTEST_TEMPLATE_ Head_>\nstruct Templates<Head_> {\n  using Head = TemplateSel<Head_>;\n  using Tail = None;\n};\n\n// Tuple-like type lists\ntemplate <typename Head_, typename... Tail_>\nstruct Types {\n  using Head = Head_;\n  using Tail = Types<Tail_...>;\n};\n\ntemplate <typename Head_>\nstruct Types<Head_> {\n  using Head = Head_;\n  using Tail = None;\n};\n\n// Helper metafunctions to tell apart a single type from types\n// generated by ::testing::Types\ntemplate <typename... Ts>\nstruct ProxyTypeList {\n  using type = Types<Ts...>;\n};\n\ntemplate <typename>\nstruct is_proxy_type_list : std::false_type {};\n\ntemplate <typename... Ts>\nstruct is_proxy_type_list<ProxyTypeList<Ts...>> : std::true_type {};\n\n// Generator which conditionally creates type lists.\n// It recognizes if a requested type list should be created\n// and prevents creating a new type list nested within another one.\ntemplate <typename T>\nstruct GenerateTypeList {\n private:\n  using proxy = typename std::conditional<is_proxy_type_list<T>::value, T,\n                                          ProxyTypeList<T>>::type;\n\n public:\n  using type = typename proxy::type;\n};\n\n}  // namespace internal\n\ntemplate <typename... Ts>\nusing Types = internal::ProxyTypeList<Ts...>;\n\n}  // namespace testing\n\n#endif  // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_TYPE_UTIL_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/samples/prime_tables.h",
    "content": "// Copyright 2008 Google Inc.\n// All Rights Reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// This provides interface PrimeTable that determines whether a number is a\n// prime and determines a next prime number. This interface is used\n// in Google Test samples demonstrating use of parameterized tests.\n\n#ifndef GOOGLETEST_SAMPLES_PRIME_TABLES_H_\n#define GOOGLETEST_SAMPLES_PRIME_TABLES_H_\n\n#include <algorithm>\n\n// The prime table interface.\nclass PrimeTable {\n public:\n  virtual ~PrimeTable() {}\n\n  // Returns true if and only if n is a prime number.\n  virtual bool IsPrime(int n) const = 0;\n\n  // Returns the smallest prime number greater than p; or returns -1\n  // if the next prime is beyond the capacity of the table.\n  virtual int GetNextPrime(int p) const = 0;\n};\n\n// Implementation #1 calculates the primes on-the-fly.\nclass OnTheFlyPrimeTable : public PrimeTable {\n public:\n  bool IsPrime(int n) const override {\n    if (n <= 1) return false;\n\n    for (int i = 2; i * i <= n; i++) {\n      // n is divisible by an integer other than 1 and itself.\n      if ((n % i) == 0) return false;\n    }\n\n    return true;\n  }\n\n  int GetNextPrime(int p) const override {\n    if (p < 0) return -1;\n\n    for (int n = p + 1;; n++) {\n      if (IsPrime(n)) return n;\n    }\n  }\n};\n\n// Implementation #2 pre-calculates the primes and stores the result\n// in an array.\nclass PreCalculatedPrimeTable : public PrimeTable {\n public:\n  // 'max' specifies the maximum number the prime table holds.\n  explicit PreCalculatedPrimeTable(int max)\n      : is_prime_size_(max + 1), is_prime_(new bool[max + 1]) {\n    CalculatePrimesUpTo(max);\n  }\n  ~PreCalculatedPrimeTable() override { delete[] is_prime_; }\n\n  bool IsPrime(int n) const override {\n    return 0 <= n && n < is_prime_size_ && is_prime_[n];\n  }\n\n  int GetNextPrime(int p) const override {\n    for (int n = p + 1; n < is_prime_size_; n++) {\n      if (is_prime_[n]) return n;\n    }\n\n    return -1;\n  }\n\n private:\n  void CalculatePrimesUpTo(int max) {\n    ::std::fill(is_prime_, is_prime_ + is_prime_size_, true);\n    is_prime_[0] = is_prime_[1] = false;\n\n    // Checks every candidate for prime number (we know that 2 is the only even\n    // prime).\n    for (int i = 2; i * i <= max; i += i % 2 + 1) {\n      if (!is_prime_[i]) continue;\n\n      // Marks all multiples of i (except i itself) as non-prime.\n      // We are starting here from i-th multiplier, because all smaller\n      // complex numbers were already marked.\n      for (int j = i * i; j <= max; j += i) {\n        is_prime_[j] = false;\n      }\n    }\n  }\n\n  const int is_prime_size_;\n  bool* const is_prime_;\n\n  // Disables compiler warning \"assignment operator could not be generated.\"\n  void operator=(const PreCalculatedPrimeTable& rhs);\n};\n\n#endif  // GOOGLETEST_SAMPLES_PRIME_TABLES_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/samples/sample1.cc",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// A sample program demonstrating using Google C++ testing framework.\n\n#include \"sample1.h\"\n\n// Returns n! (the factorial of n).  For negative n, n! is defined to be 1.\nint Factorial(int n) {\n  int result = 1;\n  for (int i = 1; i <= n; i++) {\n    result *= i;\n  }\n\n  return result;\n}\n\n// Returns true if and only if n is a prime number.\nbool IsPrime(int n) {\n  // Trivial case 1: small numbers\n  if (n <= 1) return false;\n\n  // Trivial case 2: even numbers\n  if (n % 2 == 0) return n == 2;\n\n  // Now, we have that n is odd and n >= 3.\n\n  // Try to divide n by every odd number i, starting from 3\n  for (int i = 3;; i += 2) {\n    // We only have to try i up to the square root of n\n    if (i > n / i) break;\n\n    // Now, we have i <= n/i < n.\n    // If n is divisible by i, n is not prime.\n    if (n % i == 0) return false;\n  }\n\n  // n has no integer factor in the range (1, n), and thus is prime.\n  return true;\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/samples/sample1.h",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// A sample program demonstrating using Google C++ testing framework.\n\n#ifndef GOOGLETEST_SAMPLES_SAMPLE1_H_\n#define GOOGLETEST_SAMPLES_SAMPLE1_H_\n\n// Returns n! (the factorial of n).  For negative n, n! is defined to be 1.\nint Factorial(int n);\n\n// Returns true if and only if n is a prime number.\nbool IsPrime(int n);\n\n#endif  // GOOGLETEST_SAMPLES_SAMPLE1_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/samples/sample10_unittest.cc",
    "content": "// Copyright 2009 Google Inc. All Rights Reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// This sample shows how to use Google Test listener API to implement\n// a primitive leak checker.\n\n#include <stdio.h>\n#include <stdlib.h>\n\n#include \"gtest/gtest.h\"\nusing ::testing::EmptyTestEventListener;\nusing ::testing::InitGoogleTest;\nusing ::testing::Test;\nusing ::testing::TestEventListeners;\nusing ::testing::TestInfo;\nusing ::testing::TestPartResult;\nusing ::testing::UnitTest;\n\nnamespace {\n// We will track memory used by this class.\nclass Water {\n public:\n  // Normal Water declarations go here.\n\n  // operator new and operator delete help us control water allocation.\n  void* operator new(size_t allocation_size) {\n    allocated_++;\n    return malloc(allocation_size);\n  }\n\n  void operator delete(void* block, size_t /* allocation_size */) {\n    allocated_--;\n    free(block);\n  }\n\n  static int allocated() { return allocated_; }\n\n private:\n  static int allocated_;\n};\n\nint Water::allocated_ = 0;\n\n// This event listener monitors how many Water objects are created and\n// destroyed by each test, and reports a failure if a test leaks some Water\n// objects. It does this by comparing the number of live Water objects at\n// the beginning of a test and at the end of a test.\nclass LeakChecker : public EmptyTestEventListener {\n private:\n  // Called before a test starts.\n  void OnTestStart(const TestInfo& /* test_info */) override {\n    initially_allocated_ = Water::allocated();\n  }\n\n  // Called after a test ends.\n  void OnTestEnd(const TestInfo& /* test_info */) override {\n    int difference = Water::allocated() - initially_allocated_;\n\n    // You can generate a failure in any event handler except\n    // OnTestPartResult. Just use an appropriate Google Test assertion to do\n    // it.\n    EXPECT_LE(difference, 0) << \"Leaked \" << difference << \" unit(s) of Water!\";\n  }\n\n  int initially_allocated_;\n};\n\nTEST(ListenersTest, DoesNotLeak) {\n  Water* water = new Water;\n  delete water;\n}\n\n// This should fail when the --check_for_leaks command line flag is\n// specified.\nTEST(ListenersTest, LeaksWater) {\n  Water* water = new Water;\n  EXPECT_TRUE(water != nullptr);\n}\n}  // namespace\n\nint main(int argc, char** argv) {\n  InitGoogleTest(&argc, argv);\n\n  bool check_for_leaks = false;\n  if (argc > 1 && strcmp(argv[1], \"--check_for_leaks\") == 0)\n    check_for_leaks = true;\n  else\n    printf(\"%s\\n\",\n           \"Run this program with --check_for_leaks to enable \"\n           \"custom leak checking in the tests.\");\n\n  // If we are given the --check_for_leaks command line flag, installs the\n  // leak checker.\n  if (check_for_leaks) {\n    TestEventListeners& listeners = UnitTest::GetInstance()->listeners();\n\n    // Adds the leak checker to the end of the test event listener list,\n    // after the default text output printer and the default XML report\n    // generator.\n    //\n    // The order is important - it ensures that failures generated in the\n    // leak checker's OnTestEnd() method are processed by the text and XML\n    // printers *before* their OnTestEnd() methods are called, such that\n    // they are attributed to the right test. Remember that a listener\n    // receives an OnXyzStart event *after* listeners preceding it in the\n    // list received that event, and receives an OnXyzEnd event *before*\n    // listeners preceding it.\n    //\n    // We don't need to worry about deleting the new listener later, as\n    // Google Test will do it.\n    listeners.Append(new LeakChecker);\n  }\n  return RUN_ALL_TESTS();\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/samples/sample1_unittest.cc",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// A sample program demonstrating using Google C++ testing framework.\n\n// This sample shows how to write a simple unit test for a function,\n// using Google C++ testing framework.\n//\n// Writing a unit test using Google C++ testing framework is easy as 1-2-3:\n\n// Step 1. Include necessary header files such that the stuff your\n// test logic needs is declared.\n//\n// Don't forget gtest.h, which declares the testing framework.\n\n#include \"sample1.h\"\n\n#include <limits.h>\n\n#include \"gtest/gtest.h\"\nnamespace {\n\n// Step 2. Use the TEST macro to define your tests.\n//\n// TEST has two parameters: the test case name and the test name.\n// After using the macro, you should define your test logic between a\n// pair of braces.  You can use a bunch of macros to indicate the\n// success or failure of a test.  EXPECT_TRUE and EXPECT_EQ are\n// examples of such macros.  For a complete list, see gtest.h.\n//\n// <TechnicalDetails>\n//\n// In Google Test, tests are grouped into test cases.  This is how we\n// keep test code organized.  You should put logically related tests\n// into the same test case.\n//\n// The test case name and the test name should both be valid C++\n// identifiers.  And you should not use underscore (_) in the names.\n//\n// Google Test guarantees that each test you define is run exactly\n// once, but it makes no guarantee on the order the tests are\n// executed.  Therefore, you should write your tests in such a way\n// that their results don't depend on their order.\n//\n// </TechnicalDetails>\n\n// Tests Factorial().\n\n// Tests factorial of negative numbers.\nTEST(FactorialTest, Negative) {\n  // This test is named \"Negative\", and belongs to the \"FactorialTest\"\n  // test case.\n  EXPECT_EQ(1, Factorial(-5));\n  EXPECT_EQ(1, Factorial(-1));\n  EXPECT_GT(Factorial(-10), 0);\n\n  // <TechnicalDetails>\n  //\n  // EXPECT_EQ(expected, actual) is the same as\n  //\n  //   EXPECT_TRUE((expected) == (actual))\n  //\n  // except that it will print both the expected value and the actual\n  // value when the assertion fails.  This is very helpful for\n  // debugging.  Therefore in this case EXPECT_EQ is preferred.\n  //\n  // On the other hand, EXPECT_TRUE accepts any Boolean expression,\n  // and is thus more general.\n  //\n  // </TechnicalDetails>\n}\n\n// Tests factorial of 0.\nTEST(FactorialTest, Zero) { EXPECT_EQ(1, Factorial(0)); }\n\n// Tests factorial of positive numbers.\nTEST(FactorialTest, Positive) {\n  EXPECT_EQ(1, Factorial(1));\n  EXPECT_EQ(2, Factorial(2));\n  EXPECT_EQ(6, Factorial(3));\n  EXPECT_EQ(40320, Factorial(8));\n}\n\n// Tests IsPrime()\n\n// Tests negative input.\nTEST(IsPrimeTest, Negative) {\n  // This test belongs to the IsPrimeTest test case.\n\n  EXPECT_FALSE(IsPrime(-1));\n  EXPECT_FALSE(IsPrime(-2));\n  EXPECT_FALSE(IsPrime(INT_MIN));\n}\n\n// Tests some trivial cases.\nTEST(IsPrimeTest, Trivial) {\n  EXPECT_FALSE(IsPrime(0));\n  EXPECT_FALSE(IsPrime(1));\n  EXPECT_TRUE(IsPrime(2));\n  EXPECT_TRUE(IsPrime(3));\n}\n\n// Tests positive input.\nTEST(IsPrimeTest, Positive) {\n  EXPECT_FALSE(IsPrime(4));\n  EXPECT_TRUE(IsPrime(5));\n  EXPECT_FALSE(IsPrime(6));\n  EXPECT_TRUE(IsPrime(23));\n}\n}  // namespace\n\n// Step 3. Call RUN_ALL_TESTS() in main().\n//\n// We do this by linking in src/gtest_main.cc file, which consists of\n// a main() function which calls RUN_ALL_TESTS() for us.\n//\n// This runs all the tests you've defined, prints the result, and\n// returns 0 if successful, or 1 otherwise.\n//\n// Did you notice that we didn't register the tests?  The\n// RUN_ALL_TESTS() macro magically knows about all the tests we\n// defined.  Isn't this convenient?\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/samples/sample2.cc",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// A sample program demonstrating using Google C++ testing framework.\n\n#include \"sample2.h\"\n\n#include <string.h>\n\n// Clones a 0-terminated C string, allocating memory using new.\nconst char* MyString::CloneCString(const char* a_c_string) {\n  if (a_c_string == nullptr) return nullptr;\n\n  const size_t len = strlen(a_c_string);\n  char* const clone = new char[len + 1];\n  memcpy(clone, a_c_string, len + 1);\n\n  return clone;\n}\n\n// Sets the 0-terminated C string this MyString object\n// represents.\nvoid MyString::Set(const char* a_c_string) {\n  // Makes sure this works when c_string == c_string_\n  const char* const temp = MyString::CloneCString(a_c_string);\n  delete[] c_string_;\n  c_string_ = temp;\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/samples/sample2.h",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// A sample program demonstrating using Google C++ testing framework.\n\n#ifndef GOOGLETEST_SAMPLES_SAMPLE2_H_\n#define GOOGLETEST_SAMPLES_SAMPLE2_H_\n\n#include <string.h>\n\n// A simple string class.\nclass MyString {\n private:\n  const char* c_string_;\n  const MyString& operator=(const MyString& rhs);\n\n public:\n  // Clones a 0-terminated C string, allocating memory using new.\n  static const char* CloneCString(const char* a_c_string);\n\n  ////////////////////////////////////////////////////////////\n  //\n  // C'tors\n\n  // The default c'tor constructs a NULL string.\n  MyString() : c_string_(nullptr) {}\n\n  // Constructs a MyString by cloning a 0-terminated C string.\n  explicit MyString(const char* a_c_string) : c_string_(nullptr) {\n    Set(a_c_string);\n  }\n\n  // Copy c'tor\n  MyString(const MyString& string) : c_string_(nullptr) {\n    Set(string.c_string_);\n  }\n\n  ////////////////////////////////////////////////////////////\n  //\n  // D'tor.  MyString is intended to be a final class, so the d'tor\n  // doesn't need to be virtual.\n  ~MyString() { delete[] c_string_; }\n\n  // Gets the 0-terminated C string this MyString object represents.\n  const char* c_string() const { return c_string_; }\n\n  size_t Length() const { return c_string_ == nullptr ? 0 : strlen(c_string_); }\n\n  // Sets the 0-terminated C string this MyString object represents.\n  void Set(const char* c_string);\n};\n\n#endif  // GOOGLETEST_SAMPLES_SAMPLE2_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/samples/sample2_unittest.cc",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// A sample program demonstrating using Google C++ testing framework.\n\n// This sample shows how to write a more complex unit test for a class\n// that has multiple member functions.\n//\n// Usually, it's a good idea to have one test for each method in your\n// class.  You don't have to do that exactly, but it helps to keep\n// your tests organized.  You may also throw in additional tests as\n// needed.\n\n#include \"sample2.h\"\n\n#include \"gtest/gtest.h\"\nnamespace {\n// In this example, we test the MyString class (a simple string).\n\n// Tests the default c'tor.\nTEST(MyString, DefaultConstructor) {\n  const MyString s;\n\n  // Asserts that s.c_string() returns NULL.\n  //\n  // <TechnicalDetails>\n  //\n  // If we write NULL instead of\n  //\n  //   static_cast<const char *>(NULL)\n  //\n  // in this assertion, it will generate a warning on gcc 3.4.  The\n  // reason is that EXPECT_EQ needs to know the types of its\n  // arguments in order to print them when it fails.  Since NULL is\n  // #defined as 0, the compiler will use the formatter function for\n  // int to print it.  However, gcc thinks that NULL should be used as\n  // a pointer, not an int, and therefore complains.\n  //\n  // The root of the problem is C++'s lack of distinction between the\n  // integer number 0 and the null pointer constant.  Unfortunately,\n  // we have to live with this fact.\n  //\n  // </TechnicalDetails>\n  EXPECT_STREQ(nullptr, s.c_string());\n\n  EXPECT_EQ(0u, s.Length());\n}\n\nconst char kHelloString[] = \"Hello, world!\";\n\n// Tests the c'tor that accepts a C string.\nTEST(MyString, ConstructorFromCString) {\n  const MyString s(kHelloString);\n  EXPECT_EQ(0, strcmp(s.c_string(), kHelloString));\n  EXPECT_EQ(sizeof(kHelloString) / sizeof(kHelloString[0]) - 1, s.Length());\n}\n\n// Tests the copy c'tor.\nTEST(MyString, CopyConstructor) {\n  const MyString s1(kHelloString);\n  const MyString s2 = s1;\n  EXPECT_EQ(0, strcmp(s2.c_string(), kHelloString));\n}\n\n// Tests the Set method.\nTEST(MyString, Set) {\n  MyString s;\n\n  s.Set(kHelloString);\n  EXPECT_EQ(0, strcmp(s.c_string(), kHelloString));\n\n  // Set should work when the input pointer is the same as the one\n  // already in the MyString object.\n  s.Set(s.c_string());\n  EXPECT_EQ(0, strcmp(s.c_string(), kHelloString));\n\n  // Can we set the MyString to NULL?\n  s.Set(nullptr);\n  EXPECT_STREQ(nullptr, s.c_string());\n}\n}  // namespace\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/samples/sample3-inl.h",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// A sample program demonstrating using Google C++ testing framework.\n\n#ifndef GOOGLETEST_SAMPLES_SAMPLE3_INL_H_\n#define GOOGLETEST_SAMPLES_SAMPLE3_INL_H_\n\n#include <stddef.h>\n\n// Queue is a simple queue implemented as a singled-linked list.\n//\n// The element type must support copy constructor.\ntemplate <typename E>  // E is the element type\nclass Queue;\n\n// QueueNode is a node in a Queue, which consists of an element of\n// type E and a pointer to the next node.\ntemplate <typename E>  // E is the element type\nclass QueueNode {\n  friend class Queue<E>;\n\n public:\n  // Gets the element in this node.\n  const E& element() const { return element_; }\n\n  // Gets the next node in the queue.\n  QueueNode* next() { return next_; }\n  const QueueNode* next() const { return next_; }\n\n private:\n  // Creates a node with a given element value.  The next pointer is\n  // set to NULL.\n  explicit QueueNode(const E& an_element)\n      : element_(an_element), next_(nullptr) {}\n\n  // We disable the default assignment operator and copy c'tor.\n  const QueueNode& operator=(const QueueNode&);\n  QueueNode(const QueueNode&);\n\n  E element_;\n  QueueNode* next_;\n};\n\ntemplate <typename E>  // E is the element type.\nclass Queue {\n public:\n  // Creates an empty queue.\n  Queue() : head_(nullptr), last_(nullptr), size_(0) {}\n\n  // D'tor.  Clears the queue.\n  ~Queue() { Clear(); }\n\n  // Clears the queue.\n  void Clear() {\n    if (size_ > 0) {\n      // 1. Deletes every node.\n      QueueNode<E>* node = head_;\n      QueueNode<E>* next = node->next();\n      for (;;) {\n        delete node;\n        node = next;\n        if (node == nullptr) break;\n        next = node->next();\n      }\n\n      // 2. Resets the member variables.\n      head_ = last_ = nullptr;\n      size_ = 0;\n    }\n  }\n\n  // Gets the number of elements.\n  size_t Size() const { return size_; }\n\n  // Gets the first element of the queue, or NULL if the queue is empty.\n  QueueNode<E>* Head() { return head_; }\n  const QueueNode<E>* Head() const { return head_; }\n\n  // Gets the last element of the queue, or NULL if the queue is empty.\n  QueueNode<E>* Last() { return last_; }\n  const QueueNode<E>* Last() const { return last_; }\n\n  // Adds an element to the end of the queue.  A copy of the element is\n  // created using the copy constructor, and then stored in the queue.\n  // Changes made to the element in the queue doesn't affect the source\n  // object, and vice versa.\n  void Enqueue(const E& element) {\n    QueueNode<E>* new_node = new QueueNode<E>(element);\n\n    if (size_ == 0) {\n      head_ = last_ = new_node;\n      size_ = 1;\n    } else {\n      last_->next_ = new_node;\n      last_ = new_node;\n      size_++;\n    }\n  }\n\n  // Removes the head of the queue and returns it.  Returns NULL if\n  // the queue is empty.\n  E* Dequeue() {\n    if (size_ == 0) {\n      return nullptr;\n    }\n\n    const QueueNode<E>* const old_head = head_;\n    head_ = head_->next_;\n    size_--;\n    if (size_ == 0) {\n      last_ = nullptr;\n    }\n\n    E* element = new E(old_head->element());\n    delete old_head;\n\n    return element;\n  }\n\n  // Applies a function/functor on each element of the queue, and\n  // returns the result in a new queue.  The original queue is not\n  // affected.\n  template <typename F>\n  Queue* Map(F function) const {\n    Queue* new_queue = new Queue();\n    for (const QueueNode<E>* node = head_; node != nullptr;\n         node = node->next_) {\n      new_queue->Enqueue(function(node->element()));\n    }\n\n    return new_queue;\n  }\n\n private:\n  QueueNode<E>* head_;  // The first node of the queue.\n  QueueNode<E>* last_;  // The last node of the queue.\n  size_t size_;         // The number of elements in the queue.\n\n  // We disallow copying a queue.\n  Queue(const Queue&);\n  const Queue& operator=(const Queue&);\n};\n\n#endif  // GOOGLETEST_SAMPLES_SAMPLE3_INL_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/samples/sample3_unittest.cc",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// A sample program demonstrating using Google C++ testing framework.\n\n// In this example, we use a more advanced feature of Google Test called\n// test fixture.\n//\n// A test fixture is a place to hold objects and functions shared by\n// all tests in a test case.  Using a test fixture avoids duplicating\n// the test code necessary to initialize and cleanup those common\n// objects for each test.  It is also useful for defining sub-routines\n// that your tests need to invoke a lot.\n//\n// <TechnicalDetails>\n//\n// The tests share the test fixture in the sense of code sharing, not\n// data sharing.  Each test is given its own fresh copy of the\n// fixture.  You cannot expect the data modified by one test to be\n// passed on to another test, which is a bad idea.\n//\n// The reason for this design is that tests should be independent and\n// repeatable.  In particular, a test should not fail as the result of\n// another test's failure.  If one test depends on info produced by\n// another test, then the two tests should really be one big test.\n//\n// The macros for indicating the success/failure of a test\n// (EXPECT_TRUE, FAIL, etc) need to know what the current test is\n// (when Google Test prints the test result, it tells you which test\n// each failure belongs to).  Technically, these macros invoke a\n// member function of the Test class.  Therefore, you cannot use them\n// in a global function.  That's why you should put test sub-routines\n// in a test fixture.\n//\n// </TechnicalDetails>\n\n#include \"sample3-inl.h\"\n#include \"gtest/gtest.h\"\nnamespace {\n// To use a test fixture, derive a class from testing::Test.\nclass QueueTestSmpl3 : public testing::Test {\n protected:  // You should make the members protected s.t. they can be\n             // accessed from sub-classes.\n  // virtual void SetUp() will be called before each test is run.  You\n  // should define it if you need to initialize the variables.\n  // Otherwise, this can be skipped.\n  void SetUp() override {\n    q1_.Enqueue(1);\n    q2_.Enqueue(2);\n    q2_.Enqueue(3);\n  }\n\n  // virtual void TearDown() will be called after each test is run.\n  // You should define it if there is cleanup work to do.  Otherwise,\n  // you don't have to provide it.\n  //\n  // virtual void TearDown() {\n  // }\n\n  // A helper function that some test uses.\n  static int Double(int n) { return 2 * n; }\n\n  // A helper function for testing Queue::Map().\n  void MapTester(const Queue<int>* q) {\n    // Creates a new queue, where each element is twice as big as the\n    // corresponding one in q.\n    const Queue<int>* const new_q = q->Map(Double);\n\n    // Verifies that the new queue has the same size as q.\n    ASSERT_EQ(q->Size(), new_q->Size());\n\n    // Verifies the relationship between the elements of the two queues.\n    for (const QueueNode<int>*n1 = q->Head(), *n2 = new_q->Head();\n         n1 != nullptr; n1 = n1->next(), n2 = n2->next()) {\n      EXPECT_EQ(2 * n1->element(), n2->element());\n    }\n\n    delete new_q;\n  }\n\n  // Declares the variables your tests want to use.\n  Queue<int> q0_;\n  Queue<int> q1_;\n  Queue<int> q2_;\n};\n\n// When you have a test fixture, you define a test using TEST_F\n// instead of TEST.\n\n// Tests the default c'tor.\nTEST_F(QueueTestSmpl3, DefaultConstructor) {\n  // You can access data in the test fixture here.\n  EXPECT_EQ(0u, q0_.Size());\n}\n\n// Tests Dequeue().\nTEST_F(QueueTestSmpl3, Dequeue) {\n  int* n = q0_.Dequeue();\n  EXPECT_TRUE(n == nullptr);\n\n  n = q1_.Dequeue();\n  ASSERT_TRUE(n != nullptr);\n  EXPECT_EQ(1, *n);\n  EXPECT_EQ(0u, q1_.Size());\n  delete n;\n\n  n = q2_.Dequeue();\n  ASSERT_TRUE(n != nullptr);\n  EXPECT_EQ(2, *n);\n  EXPECT_EQ(1u, q2_.Size());\n  delete n;\n}\n\n// Tests the Queue::Map() function.\nTEST_F(QueueTestSmpl3, Map) {\n  MapTester(&q0_);\n  MapTester(&q1_);\n  MapTester(&q2_);\n}\n}  // namespace\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/samples/sample4.cc",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// A sample program demonstrating using Google C++ testing framework.\n\n#include \"sample4.h\"\n\n#include <stdio.h>\n\n// Returns the current counter value, and increments it.\nint Counter::Increment() { return counter_++; }\n\n// Returns the current counter value, and decrements it.\n// counter can not be less than 0, return 0 in this case\nint Counter::Decrement() {\n  if (counter_ == 0) {\n    return counter_;\n  } else {\n    return counter_--;\n  }\n}\n\n// Prints the current counter value to STDOUT.\nvoid Counter::Print() const { printf(\"%d\", counter_); }\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/samples/sample4.h",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// A sample program demonstrating using Google C++ testing framework.\n#ifndef GOOGLETEST_SAMPLES_SAMPLE4_H_\n#define GOOGLETEST_SAMPLES_SAMPLE4_H_\n\n// A simple monotonic counter.\nclass Counter {\n private:\n  int counter_;\n\n public:\n  // Creates a counter that starts at 0.\n  Counter() : counter_(0) {}\n\n  // Returns the current counter value, and increments it.\n  int Increment();\n\n  // Returns the current counter value, and decrements it.\n  int Decrement();\n\n  // Prints the current counter value to STDOUT.\n  void Print() const;\n};\n\n#endif  // GOOGLETEST_SAMPLES_SAMPLE4_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/samples/sample4_unittest.cc",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"sample4.h\"\n\n#include \"gtest/gtest.h\"\n\nnamespace {\n// Tests the Increment() method.\n\nTEST(Counter, Increment) {\n  Counter c;\n\n  // Test that counter 0 returns 0\n  EXPECT_EQ(0, c.Decrement());\n\n  // EXPECT_EQ() evaluates its arguments exactly once, so they\n  // can have side effects.\n\n  EXPECT_EQ(0, c.Increment());\n  EXPECT_EQ(1, c.Increment());\n  EXPECT_EQ(2, c.Increment());\n\n  EXPECT_EQ(3, c.Decrement());\n}\n\n}  // namespace\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/samples/sample5_unittest.cc",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// This sample teaches how to reuse a test fixture in multiple test\n// cases by deriving sub-fixtures from it.\n//\n// When you define a test fixture, you specify the name of the test\n// case that will use this fixture.  Therefore, a test fixture can\n// be used by only one test case.\n//\n// Sometimes, more than one test cases may want to use the same or\n// slightly different test fixtures.  For example, you may want to\n// make sure that all tests for a GUI library don't leak important\n// system resources like fonts and brushes.  In Google Test, you do\n// this by putting the shared logic in a super (as in \"super class\")\n// test fixture, and then have each test case use a fixture derived\n// from this super fixture.\n\n#include <limits.h>\n#include <time.h>\n\n#include \"sample1.h\"\n#include \"sample3-inl.h\"\n#include \"gtest/gtest.h\"\nnamespace {\n// In this sample, we want to ensure that every test finishes within\n// ~5 seconds.  If a test takes longer to run, we consider it a\n// failure.\n//\n// We put the code for timing a test in a test fixture called\n// \"QuickTest\".  QuickTest is intended to be the super fixture that\n// other fixtures derive from, therefore there is no test case with\n// the name \"QuickTest\".  This is OK.\n//\n// Later, we will derive multiple test fixtures from QuickTest.\nclass QuickTest : public testing::Test {\n protected:\n  // Remember that SetUp() is run immediately before a test starts.\n  // This is a good place to record the start time.\n  void SetUp() override { start_time_ = time(nullptr); }\n\n  // TearDown() is invoked immediately after a test finishes.  Here we\n  // check if the test was too slow.\n  void TearDown() override {\n    // Gets the time when the test finishes\n    const time_t end_time = time(nullptr);\n\n    // Asserts that the test took no more than ~5 seconds.  Did you\n    // know that you can use assertions in SetUp() and TearDown() as\n    // well?\n    EXPECT_TRUE(end_time - start_time_ <= 5) << \"The test took too long.\";\n  }\n\n  // The UTC time (in seconds) when the test starts\n  time_t start_time_;\n};\n\n// We derive a fixture named IntegerFunctionTest from the QuickTest\n// fixture.  All tests using this fixture will be automatically\n// required to be quick.\nclass IntegerFunctionTest : public QuickTest {\n  // We don't need any more logic than already in the QuickTest fixture.\n  // Therefore the body is empty.\n};\n\n// Now we can write tests in the IntegerFunctionTest test case.\n\n// Tests Factorial()\nTEST_F(IntegerFunctionTest, Factorial) {\n  // Tests factorial of negative numbers.\n  EXPECT_EQ(1, Factorial(-5));\n  EXPECT_EQ(1, Factorial(-1));\n  EXPECT_GT(Factorial(-10), 0);\n\n  // Tests factorial of 0.\n  EXPECT_EQ(1, Factorial(0));\n\n  // Tests factorial of positive numbers.\n  EXPECT_EQ(1, Factorial(1));\n  EXPECT_EQ(2, Factorial(2));\n  EXPECT_EQ(6, Factorial(3));\n  EXPECT_EQ(40320, Factorial(8));\n}\n\n// Tests IsPrime()\nTEST_F(IntegerFunctionTest, IsPrime) {\n  // Tests negative input.\n  EXPECT_FALSE(IsPrime(-1));\n  EXPECT_FALSE(IsPrime(-2));\n  EXPECT_FALSE(IsPrime(INT_MIN));\n\n  // Tests some trivial cases.\n  EXPECT_FALSE(IsPrime(0));\n  EXPECT_FALSE(IsPrime(1));\n  EXPECT_TRUE(IsPrime(2));\n  EXPECT_TRUE(IsPrime(3));\n\n  // Tests positive input.\n  EXPECT_FALSE(IsPrime(4));\n  EXPECT_TRUE(IsPrime(5));\n  EXPECT_FALSE(IsPrime(6));\n  EXPECT_TRUE(IsPrime(23));\n}\n\n// The next test case (named \"QueueTest\") also needs to be quick, so\n// we derive another fixture from QuickTest.\n//\n// The QueueTest test fixture has some logic and shared objects in\n// addition to what's in QuickTest already.  We define the additional\n// stuff inside the body of the test fixture, as usual.\nclass QueueTest : public QuickTest {\n protected:\n  void SetUp() override {\n    // First, we need to set up the super fixture (QuickTest).\n    QuickTest::SetUp();\n\n    // Second, some additional setup for this fixture.\n    q1_.Enqueue(1);\n    q2_.Enqueue(2);\n    q2_.Enqueue(3);\n  }\n\n  // By default, TearDown() inherits the behavior of\n  // QuickTest::TearDown().  As we have no additional cleaning work\n  // for QueueTest, we omit it here.\n  //\n  // virtual void TearDown() {\n  //   QuickTest::TearDown();\n  // }\n\n  Queue<int> q0_;\n  Queue<int> q1_;\n  Queue<int> q2_;\n};\n\n// Now, let's write tests using the QueueTest fixture.\n\n// Tests the default constructor.\nTEST_F(QueueTest, DefaultConstructor) { EXPECT_EQ(0u, q0_.Size()); }\n\n// Tests Dequeue().\nTEST_F(QueueTest, Dequeue) {\n  int* n = q0_.Dequeue();\n  EXPECT_TRUE(n == nullptr);\n\n  n = q1_.Dequeue();\n  EXPECT_TRUE(n != nullptr);\n  EXPECT_EQ(1, *n);\n  EXPECT_EQ(0u, q1_.Size());\n  delete n;\n\n  n = q2_.Dequeue();\n  EXPECT_TRUE(n != nullptr);\n  EXPECT_EQ(2, *n);\n  EXPECT_EQ(1u, q2_.Size());\n  delete n;\n}\n}  // namespace\n// If necessary, you can derive further test fixtures from a derived\n// fixture itself.  For example, you can derive another fixture from\n// QueueTest.  Google Test imposes no limit on how deep the hierarchy\n// can be.  In practice, however, you probably don't want it to be too\n// deep as to be confusing.\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/samples/sample6_unittest.cc",
    "content": "// Copyright 2008 Google Inc.\n// All Rights Reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// This sample shows how to test common properties of multiple\n// implementations of the same interface (aka interface tests).\n\n// The interface and its implementations are in this header.\n#include \"prime_tables.h\"\n#include \"gtest/gtest.h\"\nnamespace {\n// First, we define some factory functions for creating instances of\n// the implementations.  You may be able to skip this step if all your\n// implementations can be constructed the same way.\n\ntemplate <class T>\nPrimeTable* CreatePrimeTable();\n\ntemplate <>\nPrimeTable* CreatePrimeTable<OnTheFlyPrimeTable>() {\n  return new OnTheFlyPrimeTable;\n}\n\ntemplate <>\nPrimeTable* CreatePrimeTable<PreCalculatedPrimeTable>() {\n  return new PreCalculatedPrimeTable(10000);\n}\n\n// Then we define a test fixture class template.\ntemplate <class T>\nclass PrimeTableTest : public testing::Test {\n protected:\n  // The ctor calls the factory function to create a prime table\n  // implemented by T.\n  PrimeTableTest() : table_(CreatePrimeTable<T>()) {}\n\n  ~PrimeTableTest() override { delete table_; }\n\n  // Note that we test an implementation via the base interface\n  // instead of the actual implementation class.  This is important\n  // for keeping the tests close to the real world scenario, where the\n  // implementation is invoked via the base interface.  It avoids\n  // got-yas where the implementation class has a method that shadows\n  // a method with the same name (but slightly different argument\n  // types) in the base interface, for example.\n  PrimeTable* const table_;\n};\n\nusing testing::Types;\n\n// Google Test offers two ways for reusing tests for different types.\n// The first is called \"typed tests\".  You should use it if you\n// already know *all* the types you are gonna exercise when you write\n// the tests.\n\n// To write a typed test case, first use\n//\n//   TYPED_TEST_SUITE(TestCaseName, TypeList);\n//\n// to declare it and specify the type parameters.  As with TEST_F,\n// TestCaseName must match the test fixture name.\n\n// The list of types we want to test.\ntypedef Types<OnTheFlyPrimeTable, PreCalculatedPrimeTable> Implementations;\n\nTYPED_TEST_SUITE(PrimeTableTest, Implementations);\n\n// Then use TYPED_TEST(TestCaseName, TestName) to define a typed test,\n// similar to TEST_F.\nTYPED_TEST(PrimeTableTest, ReturnsFalseForNonPrimes) {\n  // Inside the test body, you can refer to the type parameter by\n  // TypeParam, and refer to the fixture class by TestFixture.  We\n  // don't need them in this example.\n\n  // Since we are in the template world, C++ requires explicitly\n  // writing 'this->' when referring to members of the fixture class.\n  // This is something you have to learn to live with.\n  EXPECT_FALSE(this->table_->IsPrime(-5));\n  EXPECT_FALSE(this->table_->IsPrime(0));\n  EXPECT_FALSE(this->table_->IsPrime(1));\n  EXPECT_FALSE(this->table_->IsPrime(4));\n  EXPECT_FALSE(this->table_->IsPrime(6));\n  EXPECT_FALSE(this->table_->IsPrime(100));\n}\n\nTYPED_TEST(PrimeTableTest, ReturnsTrueForPrimes) {\n  EXPECT_TRUE(this->table_->IsPrime(2));\n  EXPECT_TRUE(this->table_->IsPrime(3));\n  EXPECT_TRUE(this->table_->IsPrime(5));\n  EXPECT_TRUE(this->table_->IsPrime(7));\n  EXPECT_TRUE(this->table_->IsPrime(11));\n  EXPECT_TRUE(this->table_->IsPrime(131));\n}\n\nTYPED_TEST(PrimeTableTest, CanGetNextPrime) {\n  EXPECT_EQ(2, this->table_->GetNextPrime(0));\n  EXPECT_EQ(3, this->table_->GetNextPrime(2));\n  EXPECT_EQ(5, this->table_->GetNextPrime(3));\n  EXPECT_EQ(7, this->table_->GetNextPrime(5));\n  EXPECT_EQ(11, this->table_->GetNextPrime(7));\n  EXPECT_EQ(131, this->table_->GetNextPrime(128));\n}\n\n// That's it!  Google Test will repeat each TYPED_TEST for each type\n// in the type list specified in TYPED_TEST_SUITE.  Sit back and be\n// happy that you don't have to define them multiple times.\n\nusing testing::Types;\n\n// Sometimes, however, you don't yet know all the types that you want\n// to test when you write the tests.  For example, if you are the\n// author of an interface and expect other people to implement it, you\n// might want to write a set of tests to make sure each implementation\n// conforms to some basic requirements, but you don't know what\n// implementations will be written in the future.\n//\n// How can you write the tests without committing to the type\n// parameters?  That's what \"type-parameterized tests\" can do for you.\n// It is a bit more involved than typed tests, but in return you get a\n// test pattern that can be reused in many contexts, which is a big\n// win.  Here's how you do it:\n\n// First, define a test fixture class template.  Here we just reuse\n// the PrimeTableTest fixture defined earlier:\n\ntemplate <class T>\nclass PrimeTableTest2 : public PrimeTableTest<T> {};\n\n// Then, declare the test case.  The argument is the name of the test\n// fixture, and also the name of the test case (as usual).  The _P\n// suffix is for \"parameterized\" or \"pattern\".\nTYPED_TEST_SUITE_P(PrimeTableTest2);\n\n// Next, use TYPED_TEST_P(TestCaseName, TestName) to define a test,\n// similar to what you do with TEST_F.\nTYPED_TEST_P(PrimeTableTest2, ReturnsFalseForNonPrimes) {\n  EXPECT_FALSE(this->table_->IsPrime(-5));\n  EXPECT_FALSE(this->table_->IsPrime(0));\n  EXPECT_FALSE(this->table_->IsPrime(1));\n  EXPECT_FALSE(this->table_->IsPrime(4));\n  EXPECT_FALSE(this->table_->IsPrime(6));\n  EXPECT_FALSE(this->table_->IsPrime(100));\n}\n\nTYPED_TEST_P(PrimeTableTest2, ReturnsTrueForPrimes) {\n  EXPECT_TRUE(this->table_->IsPrime(2));\n  EXPECT_TRUE(this->table_->IsPrime(3));\n  EXPECT_TRUE(this->table_->IsPrime(5));\n  EXPECT_TRUE(this->table_->IsPrime(7));\n  EXPECT_TRUE(this->table_->IsPrime(11));\n  EXPECT_TRUE(this->table_->IsPrime(131));\n}\n\nTYPED_TEST_P(PrimeTableTest2, CanGetNextPrime) {\n  EXPECT_EQ(2, this->table_->GetNextPrime(0));\n  EXPECT_EQ(3, this->table_->GetNextPrime(2));\n  EXPECT_EQ(5, this->table_->GetNextPrime(3));\n  EXPECT_EQ(7, this->table_->GetNextPrime(5));\n  EXPECT_EQ(11, this->table_->GetNextPrime(7));\n  EXPECT_EQ(131, this->table_->GetNextPrime(128));\n}\n\n// Type-parameterized tests involve one extra step: you have to\n// enumerate the tests you defined:\nREGISTER_TYPED_TEST_SUITE_P(\n    PrimeTableTest2,  // The first argument is the test case name.\n    // The rest of the arguments are the test names.\n    ReturnsFalseForNonPrimes, ReturnsTrueForPrimes, CanGetNextPrime);\n\n// At this point the test pattern is done.  However, you don't have\n// any real test yet as you haven't said which types you want to run\n// the tests with.\n\n// To turn the abstract test pattern into real tests, you instantiate\n// it with a list of types.  Usually the test pattern will be defined\n// in a .h file, and anyone can #include and instantiate it.  You can\n// even instantiate it more than once in the same program.  To tell\n// different instances apart, you give each of them a name, which will\n// become part of the test case name and can be used in test filters.\n\n// The list of types we want to test.  Note that it doesn't have to be\n// defined at the time we write the TYPED_TEST_P()s.\ntypedef Types<OnTheFlyPrimeTable, PreCalculatedPrimeTable>\n    PrimeTableImplementations;\nINSTANTIATE_TYPED_TEST_SUITE_P(OnTheFlyAndPreCalculated,    // Instance name\n                               PrimeTableTest2,             // Test case name\n                               PrimeTableImplementations);  // Type list\n\n}  // namespace\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/samples/sample7_unittest.cc",
    "content": "// Copyright 2008 Google Inc.\n// All Rights Reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// This sample shows how to test common properties of multiple\n// implementations of an interface (aka interface tests) using\n// value-parameterized tests. Each test in the test case has\n// a parameter that is an interface pointer to an implementation\n// tested.\n\n// The interface and its implementations are in this header.\n#include \"prime_tables.h\"\n#include \"gtest/gtest.h\"\nnamespace {\n\nusing ::testing::TestWithParam;\nusing ::testing::Values;\n\n// As a general rule, to prevent a test from affecting the tests that come\n// after it, you should create and destroy the tested objects for each test\n// instead of reusing them.  In this sample we will define a simple factory\n// function for PrimeTable objects.  We will instantiate objects in test's\n// SetUp() method and delete them in TearDown() method.\ntypedef PrimeTable* CreatePrimeTableFunc();\n\nPrimeTable* CreateOnTheFlyPrimeTable() { return new OnTheFlyPrimeTable(); }\n\ntemplate <size_t max_precalculated>\nPrimeTable* CreatePreCalculatedPrimeTable() {\n  return new PreCalculatedPrimeTable(max_precalculated);\n}\n\n// Inside the test body, fixture constructor, SetUp(), and TearDown() you\n// can refer to the test parameter by GetParam().  In this case, the test\n// parameter is a factory function which we call in fixture's SetUp() to\n// create and store an instance of PrimeTable.\nclass PrimeTableTestSmpl7 : public TestWithParam<CreatePrimeTableFunc*> {\n public:\n  ~PrimeTableTestSmpl7() override { delete table_; }\n  void SetUp() override { table_ = (*GetParam())(); }\n  void TearDown() override {\n    delete table_;\n    table_ = nullptr;\n  }\n\n protected:\n  PrimeTable* table_;\n};\n\nTEST_P(PrimeTableTestSmpl7, ReturnsFalseForNonPrimes) {\n  EXPECT_FALSE(table_->IsPrime(-5));\n  EXPECT_FALSE(table_->IsPrime(0));\n  EXPECT_FALSE(table_->IsPrime(1));\n  EXPECT_FALSE(table_->IsPrime(4));\n  EXPECT_FALSE(table_->IsPrime(6));\n  EXPECT_FALSE(table_->IsPrime(100));\n}\n\nTEST_P(PrimeTableTestSmpl7, ReturnsTrueForPrimes) {\n  EXPECT_TRUE(table_->IsPrime(2));\n  EXPECT_TRUE(table_->IsPrime(3));\n  EXPECT_TRUE(table_->IsPrime(5));\n  EXPECT_TRUE(table_->IsPrime(7));\n  EXPECT_TRUE(table_->IsPrime(11));\n  EXPECT_TRUE(table_->IsPrime(131));\n}\n\nTEST_P(PrimeTableTestSmpl7, CanGetNextPrime) {\n  EXPECT_EQ(2, table_->GetNextPrime(0));\n  EXPECT_EQ(3, table_->GetNextPrime(2));\n  EXPECT_EQ(5, table_->GetNextPrime(3));\n  EXPECT_EQ(7, table_->GetNextPrime(5));\n  EXPECT_EQ(11, table_->GetNextPrime(7));\n  EXPECT_EQ(131, table_->GetNextPrime(128));\n}\n\n// In order to run value-parameterized tests, you need to instantiate them,\n// or bind them to a list of values which will be used as test parameters.\n// You can instantiate them in a different translation module, or even\n// instantiate them several times.\n//\n// Here, we instantiate our tests with a list of two PrimeTable object\n// factory functions:\nINSTANTIATE_TEST_SUITE_P(OnTheFlyAndPreCalculated, PrimeTableTestSmpl7,\n                         Values(&CreateOnTheFlyPrimeTable,\n                                &CreatePreCalculatedPrimeTable<1000>));\n\n}  // namespace\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/samples/sample8_unittest.cc",
    "content": "// Copyright 2008 Google Inc.\n// All Rights Reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// This sample shows how to test code relying on some global flag variables.\n// Combine() helps with generating all possible combinations of such flags,\n// and each test is given one combination as a parameter.\n\n// Use class definitions to test from this header.\n#include \"prime_tables.h\"\n#include \"gtest/gtest.h\"\nnamespace {\n\n// Suppose we want to introduce a new, improved implementation of PrimeTable\n// which combines speed of PrecalcPrimeTable and versatility of\n// OnTheFlyPrimeTable (see prime_tables.h). Inside it instantiates both\n// PrecalcPrimeTable and OnTheFlyPrimeTable and uses the one that is more\n// appropriate under the circumstances. But in low memory conditions, it can be\n// told to instantiate without PrecalcPrimeTable instance at all and use only\n// OnTheFlyPrimeTable.\nclass HybridPrimeTable : public PrimeTable {\n public:\n  HybridPrimeTable(bool force_on_the_fly, int max_precalculated)\n      : on_the_fly_impl_(new OnTheFlyPrimeTable),\n        precalc_impl_(force_on_the_fly\n                          ? nullptr\n                          : new PreCalculatedPrimeTable(max_precalculated)),\n        max_precalculated_(max_precalculated) {}\n  ~HybridPrimeTable() override {\n    delete on_the_fly_impl_;\n    delete precalc_impl_;\n  }\n\n  bool IsPrime(int n) const override {\n    if (precalc_impl_ != nullptr && n < max_precalculated_)\n      return precalc_impl_->IsPrime(n);\n    else\n      return on_the_fly_impl_->IsPrime(n);\n  }\n\n  int GetNextPrime(int p) const override {\n    int next_prime = -1;\n    if (precalc_impl_ != nullptr && p < max_precalculated_)\n      next_prime = precalc_impl_->GetNextPrime(p);\n\n    return next_prime != -1 ? next_prime : on_the_fly_impl_->GetNextPrime(p);\n  }\n\n private:\n  OnTheFlyPrimeTable* on_the_fly_impl_;\n  PreCalculatedPrimeTable* precalc_impl_;\n  int max_precalculated_;\n};\n\nusing ::testing::Bool;\nusing ::testing::Combine;\nusing ::testing::TestWithParam;\nusing ::testing::Values;\n\n// To test all code paths for HybridPrimeTable we must test it with numbers\n// both within and outside PreCalculatedPrimeTable's capacity and also with\n// PreCalculatedPrimeTable disabled. We do this by defining fixture which will\n// accept different combinations of parameters for instantiating a\n// HybridPrimeTable instance.\nclass PrimeTableTest : public TestWithParam< ::std::tuple<bool, int> > {\n protected:\n  void SetUp() override {\n    bool force_on_the_fly;\n    int max_precalculated;\n    std::tie(force_on_the_fly, max_precalculated) = GetParam();\n    table_ = new HybridPrimeTable(force_on_the_fly, max_precalculated);\n  }\n  void TearDown() override {\n    delete table_;\n    table_ = nullptr;\n  }\n  HybridPrimeTable* table_;\n};\n\nTEST_P(PrimeTableTest, ReturnsFalseForNonPrimes) {\n  // Inside the test body, you can refer to the test parameter by GetParam().\n  // In this case, the test parameter is a PrimeTable interface pointer which\n  // we can use directly.\n  // Please note that you can also save it in the fixture's SetUp() method\n  // or constructor and use saved copy in the tests.\n\n  EXPECT_FALSE(table_->IsPrime(-5));\n  EXPECT_FALSE(table_->IsPrime(0));\n  EXPECT_FALSE(table_->IsPrime(1));\n  EXPECT_FALSE(table_->IsPrime(4));\n  EXPECT_FALSE(table_->IsPrime(6));\n  EXPECT_FALSE(table_->IsPrime(100));\n}\n\nTEST_P(PrimeTableTest, ReturnsTrueForPrimes) {\n  EXPECT_TRUE(table_->IsPrime(2));\n  EXPECT_TRUE(table_->IsPrime(3));\n  EXPECT_TRUE(table_->IsPrime(5));\n  EXPECT_TRUE(table_->IsPrime(7));\n  EXPECT_TRUE(table_->IsPrime(11));\n  EXPECT_TRUE(table_->IsPrime(131));\n}\n\nTEST_P(PrimeTableTest, CanGetNextPrime) {\n  EXPECT_EQ(2, table_->GetNextPrime(0));\n  EXPECT_EQ(3, table_->GetNextPrime(2));\n  EXPECT_EQ(5, table_->GetNextPrime(3));\n  EXPECT_EQ(7, table_->GetNextPrime(5));\n  EXPECT_EQ(11, table_->GetNextPrime(7));\n  EXPECT_EQ(131, table_->GetNextPrime(128));\n}\n\n// In order to run value-parameterized tests, you need to instantiate them,\n// or bind them to a list of values which will be used as test parameters.\n// You can instantiate them in a different translation module, or even\n// instantiate them several times.\n//\n// Here, we instantiate our tests with a list of parameters. We must combine\n// all variations of the boolean flag suppressing PrecalcPrimeTable and some\n// meaningful values for tests. We choose a small value (1), and a value that\n// will put some of the tested numbers beyond the capability of the\n// PrecalcPrimeTable instance and some inside it (10). Combine will produce all\n// possible combinations.\nINSTANTIATE_TEST_SUITE_P(MeaningfulTestParameters, PrimeTableTest,\n                         Combine(Bool(), Values(1, 10)));\n\n}  // namespace\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/samples/sample9_unittest.cc",
    "content": "// Copyright 2009 Google Inc. All Rights Reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// This sample shows how to use Google Test listener API to implement\n// an alternative console output and how to use the UnitTest reflection API\n// to enumerate test suites and tests and to inspect their results.\n\n#include <stdio.h>\n\n#include \"gtest/gtest.h\"\n\nusing ::testing::EmptyTestEventListener;\nusing ::testing::InitGoogleTest;\nusing ::testing::Test;\nusing ::testing::TestEventListeners;\nusing ::testing::TestInfo;\nusing ::testing::TestPartResult;\nusing ::testing::TestSuite;\nusing ::testing::UnitTest;\nnamespace {\n// Provides alternative output mode which produces minimal amount of\n// information about tests.\nclass TersePrinter : public EmptyTestEventListener {\n private:\n  // Called before any test activity starts.\n  void OnTestProgramStart(const UnitTest& /* unit_test */) override {}\n\n  // Called after all test activities have ended.\n  void OnTestProgramEnd(const UnitTest& unit_test) override {\n    fprintf(stdout, \"TEST %s\\n\", unit_test.Passed() ? \"PASSED\" : \"FAILED\");\n    fflush(stdout);\n  }\n\n  // Called before a test starts.\n  void OnTestStart(const TestInfo& test_info) override {\n    fprintf(stdout, \"*** Test %s.%s starting.\\n\", test_info.test_suite_name(),\n            test_info.name());\n    fflush(stdout);\n  }\n\n  // Called after a failed assertion or a SUCCEED() invocation.\n  void OnTestPartResult(const TestPartResult& test_part_result) override {\n    fprintf(stdout, \"%s in %s:%d\\n%s\\n\",\n            test_part_result.failed() ? \"*** Failure\" : \"Success\",\n            test_part_result.file_name(), test_part_result.line_number(),\n            test_part_result.summary());\n    fflush(stdout);\n  }\n\n  // Called after a test ends.\n  void OnTestEnd(const TestInfo& test_info) override {\n    fprintf(stdout, \"*** Test %s.%s ending.\\n\", test_info.test_suite_name(),\n            test_info.name());\n    fflush(stdout);\n  }\n};  // class TersePrinter\n\nTEST(CustomOutputTest, PrintsMessage) {\n  printf(\"Printing something from the test body...\\n\");\n}\n\nTEST(CustomOutputTest, Succeeds) {\n  SUCCEED() << \"SUCCEED() has been invoked from here\";\n}\n\nTEST(CustomOutputTest, Fails) {\n  EXPECT_EQ(1, 2)\n      << \"This test fails in order to demonstrate alternative failure messages\";\n}\n}  // namespace\n\nint main(int argc, char** argv) {\n  InitGoogleTest(&argc, argv);\n\n  bool terse_output = false;\n  if (argc > 1 && strcmp(argv[1], \"--terse_output\") == 0)\n    terse_output = true;\n  else\n    printf(\"%s\\n\",\n           \"Run this program with --terse_output to change the way \"\n           \"it prints its output.\");\n\n  UnitTest& unit_test = *UnitTest::GetInstance();\n\n  // If we are given the --terse_output command line flag, suppresses the\n  // standard output and attaches own result printer.\n  if (terse_output) {\n    TestEventListeners& listeners = unit_test.listeners();\n\n    // Removes the default console output listener from the list so it will\n    // not receive events from Google Test and won't print any output. Since\n    // this operation transfers ownership of the listener to the caller we\n    // have to delete it as well.\n    delete listeners.Release(listeners.default_result_printer());\n\n    // Adds the custom output listener to the list. It will now receive\n    // events from Google Test and print the alternative output. We don't\n    // have to worry about deleting it since Google Test assumes ownership\n    // over it after adding it to the list.\n    listeners.Append(new TersePrinter);\n  }\n  int ret_val = RUN_ALL_TESTS();\n\n  // This is an example of using the UnitTest reflection API to inspect test\n  // results. Here we discount failures from the tests we expected to fail.\n  int unexpectedly_failed_tests = 0;\n  for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {\n    const testing::TestSuite& test_suite = *unit_test.GetTestSuite(i);\n    for (int j = 0; j < test_suite.total_test_count(); ++j) {\n      const TestInfo& test_info = *test_suite.GetTestInfo(j);\n      // Counts failed tests that were not meant to fail (those without\n      // 'Fails' in the name).\n      if (test_info.result()->Failed() &&\n          strcmp(test_info.name(), \"Fails\") != 0) {\n        unexpectedly_failed_tests++;\n      }\n    }\n  }\n\n  // Test that were meant to fail should not affect the test program outcome.\n  if (unexpectedly_failed_tests == 0) ret_val = 0;\n\n  return ret_val;\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/src/gtest-all.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// Google C++ Testing and Mocking Framework (Google Test)\n//\n// Sometimes it's desirable to build Google Test by compiling a single file.\n// This file serves this purpose.\n\n// This line ensures that gtest.h can be compiled on its own, even\n// when it's fused.\n#include \"gtest/gtest.h\"\n\n// The following lines pull in the real gtest *.cc files.\n#include \"src/gtest-assertion-result.cc\"\n#include \"src/gtest-death-test.cc\"\n#include \"src/gtest-filepath.cc\"\n#include \"src/gtest-matchers.cc\"\n#include \"src/gtest-port.cc\"\n#include \"src/gtest-printers.cc\"\n#include \"src/gtest-test-part.cc\"\n#include \"src/gtest-typed-test.cc\"\n#include \"src/gtest.cc\"\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/src/gtest-assertion-result.cc",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// The Google C++ Testing and Mocking Framework (Google Test)\n//\n// This file defines the AssertionResult type.\n\n#include \"gtest/gtest-assertion-result.h\"\n\n#include <string>\n#include <utility>\n\n#include \"gtest/gtest-message.h\"\n\nnamespace testing {\n\n// AssertionResult constructors.\n// Used in EXPECT_TRUE/FALSE(assertion_result).\nAssertionResult::AssertionResult(const AssertionResult& other)\n    : success_(other.success_),\n      message_(other.message_.get() != nullptr\n                   ? new ::std::string(*other.message_)\n                   : static_cast< ::std::string*>(nullptr)) {}\n\n// Swaps two AssertionResults.\nvoid AssertionResult::swap(AssertionResult& other) {\n  using std::swap;\n  swap(success_, other.success_);\n  swap(message_, other.message_);\n}\n\n// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.\nAssertionResult AssertionResult::operator!() const {\n  AssertionResult negation(!success_);\n  if (message_.get() != nullptr) negation << *message_;\n  return negation;\n}\n\n// Makes a successful assertion result.\nAssertionResult AssertionSuccess() { return AssertionResult(true); }\n\n// Makes a failed assertion result.\nAssertionResult AssertionFailure() { return AssertionResult(false); }\n\n// Makes a failed assertion result with the given failure message.\n// Deprecated; use AssertionFailure() << message.\nAssertionResult AssertionFailure(const Message& message) {\n  return AssertionFailure() << message;\n}\n\n}  // namespace testing\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/src/gtest-death-test.cc",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// This file implements death tests.\n\n#include \"gtest/gtest-death-test.h\"\n\n#include <functional>\n#include <utility>\n\n#include \"gtest/internal/custom/gtest.h\"\n#include \"gtest/internal/gtest-port.h\"\n\n#if GTEST_HAS_DEATH_TEST\n\n#if GTEST_OS_MAC\n#include <crt_externs.h>\n#endif  // GTEST_OS_MAC\n\n#include <errno.h>\n#include <fcntl.h>\n#include <limits.h>\n\n#if GTEST_OS_LINUX\n#include <signal.h>\n#endif  // GTEST_OS_LINUX\n\n#include <stdarg.h>\n\n#if GTEST_OS_WINDOWS\n#include <windows.h>\n#else\n#include <sys/mman.h>\n#include <sys/wait.h>\n#endif  // GTEST_OS_WINDOWS\n\n#if GTEST_OS_QNX\n#include <spawn.h>\n#endif  // GTEST_OS_QNX\n\n#if GTEST_OS_FUCHSIA\n#include <lib/fdio/fd.h>\n#include <lib/fdio/io.h>\n#include <lib/fdio/spawn.h>\n#include <lib/zx/channel.h>\n#include <lib/zx/port.h>\n#include <lib/zx/process.h>\n#include <lib/zx/socket.h>\n#include <zircon/processargs.h>\n#include <zircon/syscalls.h>\n#include <zircon/syscalls/policy.h>\n#include <zircon/syscalls/port.h>\n#endif  // GTEST_OS_FUCHSIA\n\n#endif  // GTEST_HAS_DEATH_TEST\n\n#include \"gtest/gtest-message.h\"\n#include \"gtest/internal/gtest-string.h\"\n#include \"src/gtest-internal-inl.h\"\n\nnamespace testing {\n\n// Constants.\n\n// The default death test style.\n//\n// This is defined in internal/gtest-port.h as \"fast\", but can be overridden by\n// a definition in internal/custom/gtest-port.h. The recommended value, which is\n// used internally at Google, is \"threadsafe\".\nstatic const char kDefaultDeathTestStyle[] = GTEST_DEFAULT_DEATH_TEST_STYLE;\n\n}  // namespace testing\n\nGTEST_DEFINE_string_(\n    death_test_style,\n    testing::internal::StringFromGTestEnv(\"death_test_style\",\n                                          testing::kDefaultDeathTestStyle),\n    \"Indicates how to run a death test in a forked child process: \"\n    \"\\\"threadsafe\\\" (child process re-executes the test binary \"\n    \"from the beginning, running only the specific death test) or \"\n    \"\\\"fast\\\" (child process runs the death test immediately \"\n    \"after forking).\");\n\nGTEST_DEFINE_bool_(\n    death_test_use_fork,\n    testing::internal::BoolFromGTestEnv(\"death_test_use_fork\", false),\n    \"Instructs to use fork()/_exit() instead of clone() in death tests. \"\n    \"Ignored and always uses fork() on POSIX systems where clone() is not \"\n    \"implemented. Useful when running under valgrind or similar tools if \"\n    \"those do not support clone(). Valgrind 3.3.1 will just fail if \"\n    \"it sees an unsupported combination of clone() flags. \"\n    \"It is not recommended to use this flag w/o valgrind though it will \"\n    \"work in 99% of the cases. Once valgrind is fixed, this flag will \"\n    \"most likely be removed.\");\n\nGTEST_DEFINE_string_(\n    internal_run_death_test, \"\",\n    \"Indicates the file, line number, temporal index of \"\n    \"the single death test to run, and a file descriptor to \"\n    \"which a success code may be sent, all separated by \"\n    \"the '|' characters.  This flag is specified if and only if the \"\n    \"current process is a sub-process launched for running a thread-safe \"\n    \"death test.  FOR INTERNAL USE ONLY.\");\n\nnamespace testing {\n\n#if GTEST_HAS_DEATH_TEST\n\nnamespace internal {\n\n// Valid only for fast death tests. Indicates the code is running in the\n// child process of a fast style death test.\n#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA\nstatic bool g_in_fast_death_test_child = false;\n#endif\n\n// Returns a Boolean value indicating whether the caller is currently\n// executing in the context of the death test child process.  Tools such as\n// Valgrind heap checkers may need this to modify their behavior in death\n// tests.  IMPORTANT: This is an internal utility.  Using it may break the\n// implementation of death tests.  User code MUST NOT use it.\nbool InDeathTestChild() {\n#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA\n\n  // On Windows and Fuchsia, death tests are thread-safe regardless of the value\n  // of the death_test_style flag.\n  return !GTEST_FLAG_GET(internal_run_death_test).empty();\n\n#else\n\n  if (GTEST_FLAG_GET(death_test_style) == \"threadsafe\")\n    return !GTEST_FLAG_GET(internal_run_death_test).empty();\n  else\n    return g_in_fast_death_test_child;\n#endif\n}\n\n}  // namespace internal\n\n// ExitedWithCode constructor.\nExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {}\n\n// ExitedWithCode function-call operator.\nbool ExitedWithCode::operator()(int exit_status) const {\n#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA\n\n  return exit_status == exit_code_;\n\n#else\n\n  return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;\n\n#endif  // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA\n}\n\n#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA\n// KilledBySignal constructor.\nKilledBySignal::KilledBySignal(int signum) : signum_(signum) {}\n\n// KilledBySignal function-call operator.\nbool KilledBySignal::operator()(int exit_status) const {\n#if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)\n  {\n    bool result;\n    if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {\n      return result;\n    }\n  }\n#endif  // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)\n  return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;\n}\n#endif  // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA\n\nnamespace internal {\n\n// Utilities needed for death tests.\n\n// Generates a textual description of a given exit code, in the format\n// specified by wait(2).\nstatic std::string ExitSummary(int exit_code) {\n  Message m;\n\n#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA\n\n  m << \"Exited with exit status \" << exit_code;\n\n#else\n\n  if (WIFEXITED(exit_code)) {\n    m << \"Exited with exit status \" << WEXITSTATUS(exit_code);\n  } else if (WIFSIGNALED(exit_code)) {\n    m << \"Terminated by signal \" << WTERMSIG(exit_code);\n  }\n#ifdef WCOREDUMP\n  if (WCOREDUMP(exit_code)) {\n    m << \" (core dumped)\";\n  }\n#endif\n#endif  // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA\n\n  return m.GetString();\n}\n\n// Returns true if exit_status describes a process that was terminated\n// by a signal, or exited normally with a nonzero exit code.\nbool ExitedUnsuccessfully(int exit_status) {\n  return !ExitedWithCode(0)(exit_status);\n}\n\n#if !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA\n// Generates a textual failure message when a death test finds more than\n// one thread running, or cannot determine the number of threads, prior\n// to executing the given statement.  It is the responsibility of the\n// caller not to pass a thread_count of 1.\nstatic std::string DeathTestThreadWarning(size_t thread_count) {\n  Message msg;\n  msg << \"Death tests use fork(), which is unsafe particularly\"\n      << \" in a threaded context. For this test, \" << GTEST_NAME_ << \" \";\n  if (thread_count == 0) {\n    msg << \"couldn't detect the number of threads.\";\n  } else {\n    msg << \"detected \" << thread_count << \" threads.\";\n  }\n  msg << \" See \"\n         \"https://github.com/google/googletest/blob/master/docs/\"\n         \"advanced.md#death-tests-and-threads\"\n      << \" for more explanation and suggested solutions, especially if\"\n      << \" this is the last message you see before your test times out.\";\n  return msg.GetString();\n}\n#endif  // !GTEST_OS_WINDOWS && !GTEST_OS_FUCHSIA\n\n// Flag characters for reporting a death test that did not die.\nstatic const char kDeathTestLived = 'L';\nstatic const char kDeathTestReturned = 'R';\nstatic const char kDeathTestThrew = 'T';\nstatic const char kDeathTestInternalError = 'I';\n\n#if GTEST_OS_FUCHSIA\n\n// File descriptor used for the pipe in the child process.\nstatic const int kFuchsiaReadPipeFd = 3;\n\n#endif\n\n// An enumeration describing all of the possible ways that a death test can\n// conclude.  DIED means that the process died while executing the test\n// code; LIVED means that process lived beyond the end of the test code;\n// RETURNED means that the test statement attempted to execute a return\n// statement, which is not allowed; THREW means that the test statement\n// returned control by throwing an exception.  IN_PROGRESS means the test\n// has not yet concluded.\nenum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };\n\n// Routine for aborting the program which is safe to call from an\n// exec-style death test child process, in which case the error\n// message is propagated back to the parent process.  Otherwise, the\n// message is simply printed to stderr.  In either case, the program\n// then exits with status 1.\nstatic void DeathTestAbort(const std::string& message) {\n  // On a POSIX system, this function may be called from a threadsafe-style\n  // death test child process, which operates on a very small stack.  Use\n  // the heap for any additional non-minuscule memory requirements.\n  const InternalRunDeathTestFlag* const flag =\n      GetUnitTestImpl()->internal_run_death_test_flag();\n  if (flag != nullptr) {\n    FILE* parent = posix::FDOpen(flag->write_fd(), \"w\");\n    fputc(kDeathTestInternalError, parent);\n    fprintf(parent, \"%s\", message.c_str());\n    fflush(parent);\n    _exit(1);\n  } else {\n    fprintf(stderr, \"%s\", message.c_str());\n    fflush(stderr);\n    posix::Abort();\n  }\n}\n\n// A replacement for CHECK that calls DeathTestAbort if the assertion\n// fails.\n#define GTEST_DEATH_TEST_CHECK_(expression)                              \\\n  do {                                                                   \\\n    if (!::testing::internal::IsTrue(expression)) {                      \\\n      DeathTestAbort(::std::string(\"CHECK failed: File \") + __FILE__ +   \\\n                     \", line \" +                                         \\\n                     ::testing::internal::StreamableToString(__LINE__) + \\\n                     \": \" + #expression);                                \\\n    }                                                                    \\\n  } while (::testing::internal::AlwaysFalse())\n\n// This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for\n// evaluating any system call that fulfills two conditions: it must return\n// -1 on failure, and set errno to EINTR when it is interrupted and\n// should be tried again.  The macro expands to a loop that repeatedly\n// evaluates the expression as long as it evaluates to -1 and sets\n// errno to EINTR.  If the expression evaluates to -1 but errno is\n// something other than EINTR, DeathTestAbort is called.\n#define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression)                      \\\n  do {                                                                   \\\n    int gtest_retval;                                                    \\\n    do {                                                                 \\\n      gtest_retval = (expression);                                       \\\n    } while (gtest_retval == -1 && errno == EINTR);                      \\\n    if (gtest_retval == -1) {                                            \\\n      DeathTestAbort(::std::string(\"CHECK failed: File \") + __FILE__ +   \\\n                     \", line \" +                                         \\\n                     ::testing::internal::StreamableToString(__LINE__) + \\\n                     \": \" + #expression + \" != -1\");                     \\\n    }                                                                    \\\n  } while (::testing::internal::AlwaysFalse())\n\n// Returns the message describing the last system error in errno.\nstd::string GetLastErrnoDescription() {\n  return errno == 0 ? \"\" : posix::StrError(errno);\n}\n\n// This is called from a death test parent process to read a failure\n// message from the death test child process and log it with the FATAL\n// severity. On Windows, the message is read from a pipe handle. On other\n// platforms, it is read from a file descriptor.\nstatic void FailFromInternalError(int fd) {\n  Message error;\n  char buffer[256];\n  int num_read;\n\n  do {\n    while ((num_read = posix::Read(fd, buffer, 255)) > 0) {\n      buffer[num_read] = '\\0';\n      error << buffer;\n    }\n  } while (num_read == -1 && errno == EINTR);\n\n  if (num_read == 0) {\n    GTEST_LOG_(FATAL) << error.GetString();\n  } else {\n    const int last_error = errno;\n    GTEST_LOG_(FATAL) << \"Error while reading death test internal: \"\n                      << GetLastErrnoDescription() << \" [\" << last_error << \"]\";\n  }\n}\n\n// Death test constructor.  Increments the running death test count\n// for the current test.\nDeathTest::DeathTest() {\n  TestInfo* const info = GetUnitTestImpl()->current_test_info();\n  if (info == nullptr) {\n    DeathTestAbort(\n        \"Cannot run a death test outside of a TEST or \"\n        \"TEST_F construct\");\n  }\n}\n\n// Creates and returns a death test by dispatching to the current\n// death test factory.\nbool DeathTest::Create(const char* statement,\n                       Matcher<const std::string&> matcher, const char* file,\n                       int line, DeathTest** test) {\n  return GetUnitTestImpl()->death_test_factory()->Create(\n      statement, std::move(matcher), file, line, test);\n}\n\nconst char* DeathTest::LastMessage() {\n  return last_death_test_message_.c_str();\n}\n\nvoid DeathTest::set_last_death_test_message(const std::string& message) {\n  last_death_test_message_ = message;\n}\n\nstd::string DeathTest::last_death_test_message_;\n\n// Provides cross platform implementation for some death functionality.\nclass DeathTestImpl : public DeathTest {\n protected:\n  DeathTestImpl(const char* a_statement, Matcher<const std::string&> matcher)\n      : statement_(a_statement),\n        matcher_(std::move(matcher)),\n        spawned_(false),\n        status_(-1),\n        outcome_(IN_PROGRESS),\n        read_fd_(-1),\n        write_fd_(-1) {}\n\n  // read_fd_ is expected to be closed and cleared by a derived class.\n  ~DeathTestImpl() override { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }\n\n  void Abort(AbortReason reason) override;\n  bool Passed(bool status_ok) override;\n\n  const char* statement() const { return statement_; }\n  bool spawned() const { return spawned_; }\n  void set_spawned(bool is_spawned) { spawned_ = is_spawned; }\n  int status() const { return status_; }\n  void set_status(int a_status) { status_ = a_status; }\n  DeathTestOutcome outcome() const { return outcome_; }\n  void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }\n  int read_fd() const { return read_fd_; }\n  void set_read_fd(int fd) { read_fd_ = fd; }\n  int write_fd() const { return write_fd_; }\n  void set_write_fd(int fd) { write_fd_ = fd; }\n\n  // Called in the parent process only. Reads the result code of the death\n  // test child process via a pipe, interprets it to set the outcome_\n  // member, and closes read_fd_.  Outputs diagnostics and terminates in\n  // case of unexpected codes.\n  void ReadAndInterpretStatusByte();\n\n  // Returns stderr output from the child process.\n  virtual std::string GetErrorLogs();\n\n private:\n  // The textual content of the code this object is testing.  This class\n  // doesn't own this string and should not attempt to delete it.\n  const char* const statement_;\n  // A matcher that's expected to match the stderr output by the child process.\n  Matcher<const std::string&> matcher_;\n  // True if the death test child process has been successfully spawned.\n  bool spawned_;\n  // The exit status of the child process.\n  int status_;\n  // How the death test concluded.\n  DeathTestOutcome outcome_;\n  // Descriptor to the read end of the pipe to the child process.  It is\n  // always -1 in the child process.  The child keeps its write end of the\n  // pipe in write_fd_.\n  int read_fd_;\n  // Descriptor to the child's write end of the pipe to the parent process.\n  // It is always -1 in the parent process.  The parent keeps its end of the\n  // pipe in read_fd_.\n  int write_fd_;\n};\n\n// Called in the parent process only. Reads the result code of the death\n// test child process via a pipe, interprets it to set the outcome_\n// member, and closes read_fd_.  Outputs diagnostics and terminates in\n// case of unexpected codes.\nvoid DeathTestImpl::ReadAndInterpretStatusByte() {\n  char flag;\n  int bytes_read;\n\n  // The read() here blocks until data is available (signifying the\n  // failure of the death test) or until the pipe is closed (signifying\n  // its success), so it's okay to call this in the parent before\n  // the child process has exited.\n  do {\n    bytes_read = posix::Read(read_fd(), &flag, 1);\n  } while (bytes_read == -1 && errno == EINTR);\n\n  if (bytes_read == 0) {\n    set_outcome(DIED);\n  } else if (bytes_read == 1) {\n    switch (flag) {\n      case kDeathTestReturned:\n        set_outcome(RETURNED);\n        break;\n      case kDeathTestThrew:\n        set_outcome(THREW);\n        break;\n      case kDeathTestLived:\n        set_outcome(LIVED);\n        break;\n      case kDeathTestInternalError:\n        FailFromInternalError(read_fd());  // Does not return.\n        break;\n      default:\n        GTEST_LOG_(FATAL) << \"Death test child process reported \"\n                          << \"unexpected status byte (\"\n                          << static_cast<unsigned int>(flag) << \")\";\n    }\n  } else {\n    GTEST_LOG_(FATAL) << \"Read from death test child process failed: \"\n                      << GetLastErrnoDescription();\n  }\n  GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));\n  set_read_fd(-1);\n}\n\nstd::string DeathTestImpl::GetErrorLogs() { return GetCapturedStderr(); }\n\n// Signals that the death test code which should have exited, didn't.\n// Should be called only in a death test child process.\n// Writes a status byte to the child's status file descriptor, then\n// calls _exit(1).\nvoid DeathTestImpl::Abort(AbortReason reason) {\n  // The parent process considers the death test to be a failure if\n  // it finds any data in our pipe.  So, here we write a single flag byte\n  // to the pipe, then exit.\n  const char status_ch = reason == TEST_DID_NOT_DIE       ? kDeathTestLived\n                         : reason == TEST_THREW_EXCEPTION ? kDeathTestThrew\n                                                          : kDeathTestReturned;\n\n  GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));\n  // We are leaking the descriptor here because on some platforms (i.e.,\n  // when built as Windows DLL), destructors of global objects will still\n  // run after calling _exit(). On such systems, write_fd_ will be\n  // indirectly closed from the destructor of UnitTestImpl, causing double\n  // close if it is also closed here. On debug configurations, double close\n  // may assert. As there are no in-process buffers to flush here, we are\n  // relying on the OS to close the descriptor after the process terminates\n  // when the destructors are not run.\n  _exit(1);  // Exits w/o any normal exit hooks (we were supposed to crash)\n}\n\n// Returns an indented copy of stderr output for a death test.\n// This makes distinguishing death test output lines from regular log lines\n// much easier.\nstatic ::std::string FormatDeathTestOutput(const ::std::string& output) {\n  ::std::string ret;\n  for (size_t at = 0;;) {\n    const size_t line_end = output.find('\\n', at);\n    ret += \"[  DEATH   ] \";\n    if (line_end == ::std::string::npos) {\n      ret += output.substr(at);\n      break;\n    }\n    ret += output.substr(at, line_end + 1 - at);\n    at = line_end + 1;\n  }\n  return ret;\n}\n\n// Assesses the success or failure of a death test, using both private\n// members which have previously been set, and one argument:\n//\n// Private data members:\n//   outcome:  An enumeration describing how the death test\n//             concluded: DIED, LIVED, THREW, or RETURNED.  The death test\n//             fails in the latter three cases.\n//   status:   The exit status of the child process. On *nix, it is in the\n//             in the format specified by wait(2). On Windows, this is the\n//             value supplied to the ExitProcess() API or a numeric code\n//             of the exception that terminated the program.\n//   matcher_: A matcher that's expected to match the stderr output by the child\n//             process.\n//\n// Argument:\n//   status_ok: true if exit_status is acceptable in the context of\n//              this particular death test, which fails if it is false\n//\n// Returns true if and only if all of the above conditions are met.  Otherwise,\n// the first failing condition, in the order given above, is the one that is\n// reported. Also sets the last death test message string.\nbool DeathTestImpl::Passed(bool status_ok) {\n  if (!spawned()) return false;\n\n  const std::string error_message = GetErrorLogs();\n\n  bool success = false;\n  Message buffer;\n\n  buffer << \"Death test: \" << statement() << \"\\n\";\n  switch (outcome()) {\n    case LIVED:\n      buffer << \"    Result: failed to die.\\n\"\n             << \" Error msg:\\n\"\n             << FormatDeathTestOutput(error_message);\n      break;\n    case THREW:\n      buffer << \"    Result: threw an exception.\\n\"\n             << \" Error msg:\\n\"\n             << FormatDeathTestOutput(error_message);\n      break;\n    case RETURNED:\n      buffer << \"    Result: illegal return in test statement.\\n\"\n             << \" Error msg:\\n\"\n             << FormatDeathTestOutput(error_message);\n      break;\n    case DIED:\n      if (status_ok) {\n        if (matcher_.Matches(error_message)) {\n          success = true;\n        } else {\n          std::ostringstream stream;\n          matcher_.DescribeTo(&stream);\n          buffer << \"    Result: died but not with expected error.\\n\"\n                 << \"  Expected: \" << stream.str() << \"\\n\"\n                 << \"Actual msg:\\n\"\n                 << FormatDeathTestOutput(error_message);\n        }\n      } else {\n        buffer << \"    Result: died but not with expected exit code:\\n\"\n               << \"            \" << ExitSummary(status()) << \"\\n\"\n               << \"Actual msg:\\n\"\n               << FormatDeathTestOutput(error_message);\n      }\n      break;\n    case IN_PROGRESS:\n    default:\n      GTEST_LOG_(FATAL)\n          << \"DeathTest::Passed somehow called before conclusion of test\";\n  }\n\n  DeathTest::set_last_death_test_message(buffer.GetString());\n  return success;\n}\n\n#if GTEST_OS_WINDOWS\n// WindowsDeathTest implements death tests on Windows. Due to the\n// specifics of starting new processes on Windows, death tests there are\n// always threadsafe, and Google Test considers the\n// --gtest_death_test_style=fast setting to be equivalent to\n// --gtest_death_test_style=threadsafe there.\n//\n// A few implementation notes:  Like the Linux version, the Windows\n// implementation uses pipes for child-to-parent communication. But due to\n// the specifics of pipes on Windows, some extra steps are required:\n//\n// 1. The parent creates a communication pipe and stores handles to both\n//    ends of it.\n// 2. The parent starts the child and provides it with the information\n//    necessary to acquire the handle to the write end of the pipe.\n// 3. The child acquires the write end of the pipe and signals the parent\n//    using a Windows event.\n// 4. Now the parent can release the write end of the pipe on its side. If\n//    this is done before step 3, the object's reference count goes down to\n//    0 and it is destroyed, preventing the child from acquiring it. The\n//    parent now has to release it, or read operations on the read end of\n//    the pipe will not return when the child terminates.\n// 5. The parent reads child's output through the pipe (outcome code and\n//    any possible error messages) from the pipe, and its stderr and then\n//    determines whether to fail the test.\n//\n// Note: to distinguish Win32 API calls from the local method and function\n// calls, the former are explicitly resolved in the global namespace.\n//\nclass WindowsDeathTest : public DeathTestImpl {\n public:\n  WindowsDeathTest(const char* a_statement, Matcher<const std::string&> matcher,\n                   const char* file, int line)\n      : DeathTestImpl(a_statement, std::move(matcher)),\n        file_(file),\n        line_(line) {}\n\n  // All of these virtual functions are inherited from DeathTest.\n  virtual int Wait();\n  virtual TestRole AssumeRole();\n\n private:\n  // The name of the file in which the death test is located.\n  const char* const file_;\n  // The line number on which the death test is located.\n  const int line_;\n  // Handle to the write end of the pipe to the child process.\n  AutoHandle write_handle_;\n  // Child process handle.\n  AutoHandle child_handle_;\n  // Event the child process uses to signal the parent that it has\n  // acquired the handle to the write end of the pipe. After seeing this\n  // event the parent can release its own handles to make sure its\n  // ReadFile() calls return when the child terminates.\n  AutoHandle event_handle_;\n};\n\n// Waits for the child in a death test to exit, returning its exit\n// status, or 0 if no child process exists.  As a side effect, sets the\n// outcome data member.\nint WindowsDeathTest::Wait() {\n  if (!spawned()) return 0;\n\n  // Wait until the child either signals that it has acquired the write end\n  // of the pipe or it dies.\n  const HANDLE wait_handles[2] = {child_handle_.Get(), event_handle_.Get()};\n  switch (::WaitForMultipleObjects(2, wait_handles,\n                                   FALSE,  // Waits for any of the handles.\n                                   INFINITE)) {\n    case WAIT_OBJECT_0:\n    case WAIT_OBJECT_0 + 1:\n      break;\n    default:\n      GTEST_DEATH_TEST_CHECK_(false);  // Should not get here.\n  }\n\n  // The child has acquired the write end of the pipe or exited.\n  // We release the handle on our side and continue.\n  write_handle_.Reset();\n  event_handle_.Reset();\n\n  ReadAndInterpretStatusByte();\n\n  // Waits for the child process to exit if it haven't already. This\n  // returns immediately if the child has already exited, regardless of\n  // whether previous calls to WaitForMultipleObjects synchronized on this\n  // handle or not.\n  GTEST_DEATH_TEST_CHECK_(WAIT_OBJECT_0 ==\n                          ::WaitForSingleObject(child_handle_.Get(), INFINITE));\n  DWORD status_code;\n  GTEST_DEATH_TEST_CHECK_(\n      ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);\n  child_handle_.Reset();\n  set_status(static_cast<int>(status_code));\n  return status();\n}\n\n// The AssumeRole process for a Windows death test.  It creates a child\n// process with the same executable as the current process to run the\n// death test.  The child process is given the --gtest_filter and\n// --gtest_internal_run_death_test flags such that it knows to run the\n// current death test only.\nDeathTest::TestRole WindowsDeathTest::AssumeRole() {\n  const UnitTestImpl* const impl = GetUnitTestImpl();\n  const InternalRunDeathTestFlag* const flag =\n      impl->internal_run_death_test_flag();\n  const TestInfo* const info = impl->current_test_info();\n  const int death_test_index = info->result()->death_test_count();\n\n  if (flag != nullptr) {\n    // ParseInternalRunDeathTestFlag() has performed all the necessary\n    // processing.\n    set_write_fd(flag->write_fd());\n    return EXECUTE_TEST;\n  }\n\n  // WindowsDeathTest uses an anonymous pipe to communicate results of\n  // a death test.\n  SECURITY_ATTRIBUTES handles_are_inheritable = {sizeof(SECURITY_ATTRIBUTES),\n                                                 nullptr, TRUE};\n  HANDLE read_handle, write_handle;\n  GTEST_DEATH_TEST_CHECK_(::CreatePipe(&read_handle, &write_handle,\n                                       &handles_are_inheritable,\n                                       0)  // Default buffer size.\n                          != FALSE);\n  set_read_fd(\n      ::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle), O_RDONLY));\n  write_handle_.Reset(write_handle);\n  event_handle_.Reset(::CreateEvent(\n      &handles_are_inheritable,\n      TRUE,       // The event will automatically reset to non-signaled state.\n      FALSE,      // The initial state is non-signalled.\n      nullptr));  // The even is unnamed.\n  GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != nullptr);\n  const std::string filter_flag = std::string(\"--\") + GTEST_FLAG_PREFIX_ +\n                                  \"filter=\" + info->test_suite_name() + \".\" +\n                                  info->name();\n  const std::string internal_flag =\n      std::string(\"--\") + GTEST_FLAG_PREFIX_ +\n      \"internal_run_death_test=\" + file_ + \"|\" + StreamableToString(line_) +\n      \"|\" + StreamableToString(death_test_index) + \"|\" +\n      StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +\n      // size_t has the same width as pointers on both 32-bit and 64-bit\n      // Windows platforms.\n      // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.\n      \"|\" + StreamableToString(reinterpret_cast<size_t>(write_handle)) + \"|\" +\n      StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));\n\n  char executable_path[_MAX_PATH + 1];  // NOLINT\n  GTEST_DEATH_TEST_CHECK_(_MAX_PATH + 1 != ::GetModuleFileNameA(nullptr,\n                                                                executable_path,\n                                                                _MAX_PATH));\n\n  std::string command_line = std::string(::GetCommandLineA()) + \" \" +\n                             filter_flag + \" \\\"\" + internal_flag + \"\\\"\";\n\n  DeathTest::set_last_death_test_message(\"\");\n\n  CaptureStderr();\n  // Flush the log buffers since the log streams are shared with the child.\n  FlushInfoLog();\n\n  // The child process will share the standard handles with the parent.\n  STARTUPINFOA startup_info;\n  memset(&startup_info, 0, sizeof(STARTUPINFO));\n  startup_info.dwFlags = STARTF_USESTDHANDLES;\n  startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);\n  startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);\n  startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);\n\n  PROCESS_INFORMATION process_info;\n  GTEST_DEATH_TEST_CHECK_(\n      ::CreateProcessA(\n          executable_path, const_cast<char*>(command_line.c_str()),\n          nullptr,  // Returned process handle is not inheritable.\n          nullptr,  // Returned thread handle is not inheritable.\n          TRUE,  // Child inherits all inheritable handles (for write_handle_).\n          0x0,   // Default creation flags.\n          nullptr,  // Inherit the parent's environment.\n          UnitTest::GetInstance()->original_working_dir(), &startup_info,\n          &process_info) != FALSE);\n  child_handle_.Reset(process_info.hProcess);\n  ::CloseHandle(process_info.hThread);\n  set_spawned(true);\n  return OVERSEE_TEST;\n}\n\n#elif GTEST_OS_FUCHSIA\n\nclass FuchsiaDeathTest : public DeathTestImpl {\n public:\n  FuchsiaDeathTest(const char* a_statement, Matcher<const std::string&> matcher,\n                   const char* file, int line)\n      : DeathTestImpl(a_statement, std::move(matcher)),\n        file_(file),\n        line_(line) {}\n\n  // All of these virtual functions are inherited from DeathTest.\n  int Wait() override;\n  TestRole AssumeRole() override;\n  std::string GetErrorLogs() override;\n\n private:\n  // The name of the file in which the death test is located.\n  const char* const file_;\n  // The line number on which the death test is located.\n  const int line_;\n  // The stderr data captured by the child process.\n  std::string captured_stderr_;\n\n  zx::process child_process_;\n  zx::channel exception_channel_;\n  zx::socket stderr_socket_;\n};\n\n// Utility class for accumulating command-line arguments.\nclass Arguments {\n public:\n  Arguments() { args_.push_back(nullptr); }\n\n  ~Arguments() {\n    for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();\n         ++i) {\n      free(*i);\n    }\n  }\n  void AddArgument(const char* argument) {\n    args_.insert(args_.end() - 1, posix::StrDup(argument));\n  }\n\n  template <typename Str>\n  void AddArguments(const ::std::vector<Str>& arguments) {\n    for (typename ::std::vector<Str>::const_iterator i = arguments.begin();\n         i != arguments.end(); ++i) {\n      args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));\n    }\n  }\n  char* const* Argv() { return &args_[0]; }\n\n  int size() { return static_cast<int>(args_.size()) - 1; }\n\n private:\n  std::vector<char*> args_;\n};\n\n// Waits for the child in a death test to exit, returning its exit\n// status, or 0 if no child process exists.  As a side effect, sets the\n// outcome data member.\nint FuchsiaDeathTest::Wait() {\n  const int kProcessKey = 0;\n  const int kSocketKey = 1;\n  const int kExceptionKey = 2;\n\n  if (!spawned()) return 0;\n\n  // Create a port to wait for socket/task/exception events.\n  zx_status_t status_zx;\n  zx::port port;\n  status_zx = zx::port::create(0, &port);\n  GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);\n\n  // Register to wait for the child process to terminate.\n  status_zx =\n      child_process_.wait_async(port, kProcessKey, ZX_PROCESS_TERMINATED, 0);\n  GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);\n\n  // Register to wait for the socket to be readable or closed.\n  status_zx = stderr_socket_.wait_async(\n      port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, 0);\n  GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);\n\n  // Register to wait for an exception.\n  status_zx = exception_channel_.wait_async(port, kExceptionKey,\n                                            ZX_CHANNEL_READABLE, 0);\n  GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);\n\n  bool process_terminated = false;\n  bool socket_closed = false;\n  do {\n    zx_port_packet_t packet = {};\n    status_zx = port.wait(zx::time::infinite(), &packet);\n    GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);\n\n    if (packet.key == kExceptionKey) {\n      // Process encountered an exception. Kill it directly rather than\n      // letting other handlers process the event. We will get a kProcessKey\n      // event when the process actually terminates.\n      status_zx = child_process_.kill();\n      GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);\n    } else if (packet.key == kProcessKey) {\n      // Process terminated.\n      GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));\n      GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_PROCESS_TERMINATED);\n      process_terminated = true;\n    } else if (packet.key == kSocketKey) {\n      GTEST_DEATH_TEST_CHECK_(ZX_PKT_IS_SIGNAL_ONE(packet.type));\n      if (packet.signal.observed & ZX_SOCKET_READABLE) {\n        // Read data from the socket.\n        constexpr size_t kBufferSize = 1024;\n        do {\n          size_t old_length = captured_stderr_.length();\n          size_t bytes_read = 0;\n          captured_stderr_.resize(old_length + kBufferSize);\n          status_zx =\n              stderr_socket_.read(0, &captured_stderr_.front() + old_length,\n                                  kBufferSize, &bytes_read);\n          captured_stderr_.resize(old_length + bytes_read);\n        } while (status_zx == ZX_OK);\n        if (status_zx == ZX_ERR_PEER_CLOSED) {\n          socket_closed = true;\n        } else {\n          GTEST_DEATH_TEST_CHECK_(status_zx == ZX_ERR_SHOULD_WAIT);\n          status_zx = stderr_socket_.wait_async(\n              port, kSocketKey, ZX_SOCKET_READABLE | ZX_SOCKET_PEER_CLOSED, 0);\n          GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);\n        }\n      } else {\n        GTEST_DEATH_TEST_CHECK_(packet.signal.observed & ZX_SOCKET_PEER_CLOSED);\n        socket_closed = true;\n      }\n    }\n  } while (!process_terminated && !socket_closed);\n\n  ReadAndInterpretStatusByte();\n\n  zx_info_process_t buffer;\n  status_zx = child_process_.get_info(ZX_INFO_PROCESS, &buffer, sizeof(buffer),\n                                      nullptr, nullptr);\n  GTEST_DEATH_TEST_CHECK_(status_zx == ZX_OK);\n\n  GTEST_DEATH_TEST_CHECK_(buffer.flags & ZX_INFO_PROCESS_FLAG_EXITED);\n  set_status(static_cast<int>(buffer.return_code));\n  return status();\n}\n\n// The AssumeRole process for a Fuchsia death test.  It creates a child\n// process with the same executable as the current process to run the\n// death test.  The child process is given the --gtest_filter and\n// --gtest_internal_run_death_test flags such that it knows to run the\n// current death test only.\nDeathTest::TestRole FuchsiaDeathTest::AssumeRole() {\n  const UnitTestImpl* const impl = GetUnitTestImpl();\n  const InternalRunDeathTestFlag* const flag =\n      impl->internal_run_death_test_flag();\n  const TestInfo* const info = impl->current_test_info();\n  const int death_test_index = info->result()->death_test_count();\n\n  if (flag != nullptr) {\n    // ParseInternalRunDeathTestFlag() has performed all the necessary\n    // processing.\n    set_write_fd(kFuchsiaReadPipeFd);\n    return EXECUTE_TEST;\n  }\n\n  // Flush the log buffers since the log streams are shared with the child.\n  FlushInfoLog();\n\n  // Build the child process command line.\n  const std::string filter_flag = std::string(\"--\") + GTEST_FLAG_PREFIX_ +\n                                  \"filter=\" + info->test_suite_name() + \".\" +\n                                  info->name();\n  const std::string internal_flag = std::string(\"--\") + GTEST_FLAG_PREFIX_ +\n                                    kInternalRunDeathTestFlag + \"=\" + file_ +\n                                    \"|\" + StreamableToString(line_) + \"|\" +\n                                    StreamableToString(death_test_index);\n  Arguments args;\n  args.AddArguments(GetInjectableArgvs());\n  args.AddArgument(filter_flag.c_str());\n  args.AddArgument(internal_flag.c_str());\n\n  // Build the pipe for communication with the child.\n  zx_status_t status;\n  zx_handle_t child_pipe_handle;\n  int child_pipe_fd;\n  status = fdio_pipe_half(&child_pipe_fd, &child_pipe_handle);\n  GTEST_DEATH_TEST_CHECK_(status == ZX_OK);\n  set_read_fd(child_pipe_fd);\n\n  // Set the pipe handle for the child.\n  fdio_spawn_action_t spawn_actions[2] = {};\n  fdio_spawn_action_t* add_handle_action = &spawn_actions[0];\n  add_handle_action->action = FDIO_SPAWN_ACTION_ADD_HANDLE;\n  add_handle_action->h.id = PA_HND(PA_FD, kFuchsiaReadPipeFd);\n  add_handle_action->h.handle = child_pipe_handle;\n\n  // Create a socket pair will be used to receive the child process' stderr.\n  zx::socket stderr_producer_socket;\n  status = zx::socket::create(0, &stderr_producer_socket, &stderr_socket_);\n  GTEST_DEATH_TEST_CHECK_(status >= 0);\n  int stderr_producer_fd = -1;\n  status =\n      fdio_fd_create(stderr_producer_socket.release(), &stderr_producer_fd);\n  GTEST_DEATH_TEST_CHECK_(status >= 0);\n\n  // Make the stderr socket nonblocking.\n  GTEST_DEATH_TEST_CHECK_(fcntl(stderr_producer_fd, F_SETFL, 0) == 0);\n\n  fdio_spawn_action_t* add_stderr_action = &spawn_actions[1];\n  add_stderr_action->action = FDIO_SPAWN_ACTION_CLONE_FD;\n  add_stderr_action->fd.local_fd = stderr_producer_fd;\n  add_stderr_action->fd.target_fd = STDERR_FILENO;\n\n  // Create a child job.\n  zx_handle_t child_job = ZX_HANDLE_INVALID;\n  status = zx_job_create(zx_job_default(), 0, &child_job);\n  GTEST_DEATH_TEST_CHECK_(status == ZX_OK);\n  zx_policy_basic_t policy;\n  policy.condition = ZX_POL_NEW_ANY;\n  policy.policy = ZX_POL_ACTION_ALLOW;\n  status = zx_job_set_policy(child_job, ZX_JOB_POL_RELATIVE, ZX_JOB_POL_BASIC,\n                             &policy, 1);\n  GTEST_DEATH_TEST_CHECK_(status == ZX_OK);\n\n  // Create an exception channel attached to the |child_job|, to allow\n  // us to suppress the system default exception handler from firing.\n  status = zx_task_create_exception_channel(\n      child_job, 0, exception_channel_.reset_and_get_address());\n  GTEST_DEATH_TEST_CHECK_(status == ZX_OK);\n\n  // Spawn the child process.\n  status = fdio_spawn_etc(child_job, FDIO_SPAWN_CLONE_ALL, args.Argv()[0],\n                          args.Argv(), nullptr, 2, spawn_actions,\n                          child_process_.reset_and_get_address(), nullptr);\n  GTEST_DEATH_TEST_CHECK_(status == ZX_OK);\n\n  set_spawned(true);\n  return OVERSEE_TEST;\n}\n\nstd::string FuchsiaDeathTest::GetErrorLogs() { return captured_stderr_; }\n\n#else  // We are neither on Windows, nor on Fuchsia.\n\n// ForkingDeathTest provides implementations for most of the abstract\n// methods of the DeathTest interface.  Only the AssumeRole method is\n// left undefined.\nclass ForkingDeathTest : public DeathTestImpl {\n public:\n  ForkingDeathTest(const char* statement, Matcher<const std::string&> matcher);\n\n  // All of these virtual functions are inherited from DeathTest.\n  int Wait() override;\n\n protected:\n  void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }\n\n private:\n  // PID of child process during death test; 0 in the child process itself.\n  pid_t child_pid_;\n};\n\n// Constructs a ForkingDeathTest.\nForkingDeathTest::ForkingDeathTest(const char* a_statement,\n                                   Matcher<const std::string&> matcher)\n    : DeathTestImpl(a_statement, std::move(matcher)), child_pid_(-1) {}\n\n// Waits for the child in a death test to exit, returning its exit\n// status, or 0 if no child process exists.  As a side effect, sets the\n// outcome data member.\nint ForkingDeathTest::Wait() {\n  if (!spawned()) return 0;\n\n  ReadAndInterpretStatusByte();\n\n  int status_value;\n  GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));\n  set_status(status_value);\n  return status_value;\n}\n\n// A concrete death test class that forks, then immediately runs the test\n// in the child process.\nclass NoExecDeathTest : public ForkingDeathTest {\n public:\n  NoExecDeathTest(const char* a_statement, Matcher<const std::string&> matcher)\n      : ForkingDeathTest(a_statement, std::move(matcher)) {}\n  TestRole AssumeRole() override;\n};\n\n// The AssumeRole process for a fork-and-run death test.  It implements a\n// straightforward fork, with a simple pipe to transmit the status byte.\nDeathTest::TestRole NoExecDeathTest::AssumeRole() {\n  const size_t thread_count = GetThreadCount();\n  if (thread_count != 1) {\n    GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);\n  }\n\n  int pipe_fd[2];\n  GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);\n\n  DeathTest::set_last_death_test_message(\"\");\n  CaptureStderr();\n  // When we fork the process below, the log file buffers are copied, but the\n  // file descriptors are shared.  We flush all log files here so that closing\n  // the file descriptors in the child process doesn't throw off the\n  // synchronization between descriptors and buffers in the parent process.\n  // This is as close to the fork as possible to avoid a race condition in case\n  // there are multiple threads running before the death test, and another\n  // thread writes to the log file.\n  FlushInfoLog();\n\n  const pid_t child_pid = fork();\n  GTEST_DEATH_TEST_CHECK_(child_pid != -1);\n  set_child_pid(child_pid);\n  if (child_pid == 0) {\n    GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));\n    set_write_fd(pipe_fd[1]);\n    // Redirects all logging to stderr in the child process to prevent\n    // concurrent writes to the log files.  We capture stderr in the parent\n    // process and append the child process' output to a log.\n    LogToStderr();\n    // Event forwarding to the listeners of event listener API mush be shut\n    // down in death test subprocesses.\n    GetUnitTestImpl()->listeners()->SuppressEventForwarding();\n    g_in_fast_death_test_child = true;\n    return EXECUTE_TEST;\n  } else {\n    GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));\n    set_read_fd(pipe_fd[0]);\n    set_spawned(true);\n    return OVERSEE_TEST;\n  }\n}\n\n// A concrete death test class that forks and re-executes the main\n// program from the beginning, with command-line flags set that cause\n// only this specific death test to be run.\nclass ExecDeathTest : public ForkingDeathTest {\n public:\n  ExecDeathTest(const char* a_statement, Matcher<const std::string&> matcher,\n                const char* file, int line)\n      : ForkingDeathTest(a_statement, std::move(matcher)),\n        file_(file),\n        line_(line) {}\n  TestRole AssumeRole() override;\n\n private:\n  static ::std::vector<std::string> GetArgvsForDeathTestChildProcess() {\n    ::std::vector<std::string> args = GetInjectableArgvs();\n#if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)\n    ::std::vector<std::string> extra_args =\n        GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();\n    args.insert(args.end(), extra_args.begin(), extra_args.end());\n#endif  // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)\n    return args;\n  }\n  // The name of the file in which the death test is located.\n  const char* const file_;\n  // The line number on which the death test is located.\n  const int line_;\n};\n\n// Utility class for accumulating command-line arguments.\nclass Arguments {\n public:\n  Arguments() { args_.push_back(nullptr); }\n\n  ~Arguments() {\n    for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();\n         ++i) {\n      free(*i);\n    }\n  }\n  void AddArgument(const char* argument) {\n    args_.insert(args_.end() - 1, posix::StrDup(argument));\n  }\n\n  template <typename Str>\n  void AddArguments(const ::std::vector<Str>& arguments) {\n    for (typename ::std::vector<Str>::const_iterator i = arguments.begin();\n         i != arguments.end(); ++i) {\n      args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));\n    }\n  }\n  char* const* Argv() { return &args_[0]; }\n\n private:\n  std::vector<char*> args_;\n};\n\n// A struct that encompasses the arguments to the child process of a\n// threadsafe-style death test process.\nstruct ExecDeathTestArgs {\n  char* const* argv;  // Command-line arguments for the child's call to exec\n  int close_fd;       // File descriptor to close; the read end of a pipe\n};\n\n#if GTEST_OS_QNX\nextern \"C\" char** environ;\n#else   // GTEST_OS_QNX\n// The main function for a threadsafe-style death test child process.\n// This function is called in a clone()-ed process and thus must avoid\n// any potentially unsafe operations like malloc or libc functions.\nstatic int ExecDeathTestChildMain(void* child_arg) {\n  ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);\n  GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));\n\n  // We need to execute the test program in the same environment where\n  // it was originally invoked.  Therefore we change to the original\n  // working directory first.\n  const char* const original_dir =\n      UnitTest::GetInstance()->original_working_dir();\n  // We can safely call chdir() as it's a direct system call.\n  if (chdir(original_dir) != 0) {\n    DeathTestAbort(std::string(\"chdir(\\\"\") + original_dir +\n                   \"\\\") failed: \" + GetLastErrnoDescription());\n    return EXIT_FAILURE;\n  }\n\n  // We can safely call execv() as it's almost a direct system call. We\n  // cannot use execvp() as it's a libc function and thus potentially\n  // unsafe.  Since execv() doesn't search the PATH, the user must\n  // invoke the test program via a valid path that contains at least\n  // one path separator.\n  execv(args->argv[0], args->argv);\n  DeathTestAbort(std::string(\"execv(\") + args->argv[0] + \", ...) in \" +\n                 original_dir + \" failed: \" + GetLastErrnoDescription());\n  return EXIT_FAILURE;\n}\n#endif  // GTEST_OS_QNX\n\n#if GTEST_HAS_CLONE\n// Two utility routines that together determine the direction the stack\n// grows.\n// This could be accomplished more elegantly by a single recursive\n// function, but we want to guard against the unlikely possibility of\n// a smart compiler optimizing the recursion away.\n//\n// GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining\n// StackLowerThanAddress into StackGrowsDown, which then doesn't give\n// correct answer.\nstatic void StackLowerThanAddress(const void* ptr,\n                                  bool* result) GTEST_NO_INLINE_;\n// Make sure sanitizers do not tamper with the stack here.\n// Ideally, we want to use `__builtin_frame_address` instead of a local variable\n// address with sanitizer disabled, but it does not work when the\n// compiler optimizes the stack frame out, which happens on PowerPC targets.\n// HWAddressSanitizer add a random tag to the MSB of the local variable address,\n// making comparison result unpredictable.\nGTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_\nGTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_\nstatic void StackLowerThanAddress(const void* ptr, bool* result) {\n  int dummy = 0;\n  *result = std::less<const void*>()(&dummy, ptr);\n}\n\n// Make sure AddressSanitizer does not tamper with the stack here.\nGTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_\nGTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_\nstatic bool StackGrowsDown() {\n  int dummy = 0;\n  bool result;\n  StackLowerThanAddress(&dummy, &result);\n  return result;\n}\n#endif  // GTEST_HAS_CLONE\n\n// Spawns a child process with the same executable as the current process in\n// a thread-safe manner and instructs it to run the death test.  The\n// implementation uses fork(2) + exec.  On systems where clone(2) is\n// available, it is used instead, being slightly more thread-safe.  On QNX,\n// fork supports only single-threaded environments, so this function uses\n// spawn(2) there instead.  The function dies with an error message if\n// anything goes wrong.\nstatic pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {\n  ExecDeathTestArgs args = {argv, close_fd};\n  pid_t child_pid = -1;\n\n#if GTEST_OS_QNX\n  // Obtains the current directory and sets it to be closed in the child\n  // process.\n  const int cwd_fd = open(\".\", O_RDONLY);\n  GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);\n  GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));\n  // We need to execute the test program in the same environment where\n  // it was originally invoked.  Therefore we change to the original\n  // working directory first.\n  const char* const original_dir =\n      UnitTest::GetInstance()->original_working_dir();\n  // We can safely call chdir() as it's a direct system call.\n  if (chdir(original_dir) != 0) {\n    DeathTestAbort(std::string(\"chdir(\\\"\") + original_dir +\n                   \"\\\") failed: \" + GetLastErrnoDescription());\n    return EXIT_FAILURE;\n  }\n\n  int fd_flags;\n  // Set close_fd to be closed after spawn.\n  GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));\n  GTEST_DEATH_TEST_CHECK_SYSCALL_(\n      fcntl(close_fd, F_SETFD, fd_flags | FD_CLOEXEC));\n  struct inheritance inherit = {0};\n  // spawn is a system call.\n  child_pid = spawn(args.argv[0], 0, nullptr, &inherit, args.argv, environ);\n  // Restores the current working directory.\n  GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);\n  GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));\n\n#else  // GTEST_OS_QNX\n#if GTEST_OS_LINUX\n  // When a SIGPROF signal is received while fork() or clone() are executing,\n  // the process may hang. To avoid this, we ignore SIGPROF here and re-enable\n  // it after the call to fork()/clone() is complete.\n  struct sigaction saved_sigprof_action;\n  struct sigaction ignore_sigprof_action;\n  memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));\n  sigemptyset(&ignore_sigprof_action.sa_mask);\n  ignore_sigprof_action.sa_handler = SIG_IGN;\n  GTEST_DEATH_TEST_CHECK_SYSCALL_(\n      sigaction(SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));\n#endif  // GTEST_OS_LINUX\n\n#if GTEST_HAS_CLONE\n  const bool use_fork = GTEST_FLAG_GET(death_test_use_fork);\n\n  if (!use_fork) {\n    static const bool stack_grows_down = StackGrowsDown();\n    const auto stack_size = static_cast<size_t>(getpagesize() * 2);\n    // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.\n    void* const stack = mmap(nullptr, stack_size, PROT_READ | PROT_WRITE,\n                             MAP_ANON | MAP_PRIVATE, -1, 0);\n    GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);\n\n    // Maximum stack alignment in bytes:  For a downward-growing stack, this\n    // amount is subtracted from size of the stack space to get an address\n    // that is within the stack space and is aligned on all systems we care\n    // about.  As far as I know there is no ABI with stack alignment greater\n    // than 64.  We assume stack and stack_size already have alignment of\n    // kMaxStackAlignment.\n    const size_t kMaxStackAlignment = 64;\n    void* const stack_top =\n        static_cast<char*>(stack) +\n        (stack_grows_down ? stack_size - kMaxStackAlignment : 0);\n    GTEST_DEATH_TEST_CHECK_(\n        static_cast<size_t>(stack_size) > kMaxStackAlignment &&\n        reinterpret_cast<uintptr_t>(stack_top) % kMaxStackAlignment == 0);\n\n    child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);\n\n    GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);\n  }\n#else\n  const bool use_fork = true;\n#endif  // GTEST_HAS_CLONE\n\n  if (use_fork && (child_pid = fork()) == 0) {\n    ExecDeathTestChildMain(&args);\n    _exit(0);\n  }\n#endif  // GTEST_OS_QNX\n#if GTEST_OS_LINUX\n  GTEST_DEATH_TEST_CHECK_SYSCALL_(\n      sigaction(SIGPROF, &saved_sigprof_action, nullptr));\n#endif  // GTEST_OS_LINUX\n\n  GTEST_DEATH_TEST_CHECK_(child_pid != -1);\n  return child_pid;\n}\n\n// The AssumeRole process for a fork-and-exec death test.  It re-executes the\n// main program from the beginning, setting the --gtest_filter\n// and --gtest_internal_run_death_test flags to cause only the current\n// death test to be re-run.\nDeathTest::TestRole ExecDeathTest::AssumeRole() {\n  const UnitTestImpl* const impl = GetUnitTestImpl();\n  const InternalRunDeathTestFlag* const flag =\n      impl->internal_run_death_test_flag();\n  const TestInfo* const info = impl->current_test_info();\n  const int death_test_index = info->result()->death_test_count();\n\n  if (flag != nullptr) {\n    set_write_fd(flag->write_fd());\n    return EXECUTE_TEST;\n  }\n\n  int pipe_fd[2];\n  GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);\n  // Clear the close-on-exec flag on the write end of the pipe, lest\n  // it be closed when the child process does an exec:\n  GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);\n\n  const std::string filter_flag = std::string(\"--\") + GTEST_FLAG_PREFIX_ +\n                                  \"filter=\" + info->test_suite_name() + \".\" +\n                                  info->name();\n  const std::string internal_flag = std::string(\"--\") + GTEST_FLAG_PREFIX_ +\n                                    \"internal_run_death_test=\" + file_ + \"|\" +\n                                    StreamableToString(line_) + \"|\" +\n                                    StreamableToString(death_test_index) + \"|\" +\n                                    StreamableToString(pipe_fd[1]);\n  Arguments args;\n  args.AddArguments(GetArgvsForDeathTestChildProcess());\n  args.AddArgument(filter_flag.c_str());\n  args.AddArgument(internal_flag.c_str());\n\n  DeathTest::set_last_death_test_message(\"\");\n\n  CaptureStderr();\n  // See the comment in NoExecDeathTest::AssumeRole for why the next line\n  // is necessary.\n  FlushInfoLog();\n\n  const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);\n  GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));\n  set_child_pid(child_pid);\n  set_read_fd(pipe_fd[0]);\n  set_spawned(true);\n  return OVERSEE_TEST;\n}\n\n#endif  // !GTEST_OS_WINDOWS\n\n// Creates a concrete DeathTest-derived class that depends on the\n// --gtest_death_test_style flag, and sets the pointer pointed to\n// by the \"test\" argument to its address.  If the test should be\n// skipped, sets that pointer to NULL.  Returns true, unless the\n// flag is set to an invalid value.\nbool DefaultDeathTestFactory::Create(const char* statement,\n                                     Matcher<const std::string&> matcher,\n                                     const char* file, int line,\n                                     DeathTest** test) {\n  UnitTestImpl* const impl = GetUnitTestImpl();\n  const InternalRunDeathTestFlag* const flag =\n      impl->internal_run_death_test_flag();\n  const int death_test_index =\n      impl->current_test_info()->increment_death_test_count();\n\n  if (flag != nullptr) {\n    if (death_test_index > flag->index()) {\n      DeathTest::set_last_death_test_message(\n          \"Death test count (\" + StreamableToString(death_test_index) +\n          \") somehow exceeded expected maximum (\" +\n          StreamableToString(flag->index()) + \")\");\n      return false;\n    }\n\n    if (!(flag->file() == file && flag->line() == line &&\n          flag->index() == death_test_index)) {\n      *test = nullptr;\n      return true;\n    }\n  }\n\n#if GTEST_OS_WINDOWS\n\n  if (GTEST_FLAG_GET(death_test_style) == \"threadsafe\" ||\n      GTEST_FLAG_GET(death_test_style) == \"fast\") {\n    *test = new WindowsDeathTest(statement, std::move(matcher), file, line);\n  }\n\n#elif GTEST_OS_FUCHSIA\n\n  if (GTEST_FLAG_GET(death_test_style) == \"threadsafe\" ||\n      GTEST_FLAG_GET(death_test_style) == \"fast\") {\n    *test = new FuchsiaDeathTest(statement, std::move(matcher), file, line);\n  }\n\n#else\n\n  if (GTEST_FLAG_GET(death_test_style) == \"threadsafe\") {\n    *test = new ExecDeathTest(statement, std::move(matcher), file, line);\n  } else if (GTEST_FLAG_GET(death_test_style) == \"fast\") {\n    *test = new NoExecDeathTest(statement, std::move(matcher));\n  }\n\n#endif  // GTEST_OS_WINDOWS\n\n  else {  // NOLINT - this is more readable than unbalanced brackets inside #if.\n    DeathTest::set_last_death_test_message(\"Unknown death test style \\\"\" +\n                                           GTEST_FLAG_GET(death_test_style) +\n                                           \"\\\" encountered\");\n    return false;\n  }\n\n  return true;\n}\n\n#if GTEST_OS_WINDOWS\n// Recreates the pipe and event handles from the provided parameters,\n// signals the event, and returns a file descriptor wrapped around the pipe\n// handle. This function is called in the child process only.\nstatic int GetStatusFileDescriptor(unsigned int parent_process_id,\n                                   size_t write_handle_as_size_t,\n                                   size_t event_handle_as_size_t) {\n  AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,\n                                                 FALSE,  // Non-inheritable.\n                                                 parent_process_id));\n  if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {\n    DeathTestAbort(\"Unable to open parent process \" +\n                   StreamableToString(parent_process_id));\n  }\n\n  GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));\n\n  const HANDLE write_handle = reinterpret_cast<HANDLE>(write_handle_as_size_t);\n  HANDLE dup_write_handle;\n\n  // The newly initialized handle is accessible only in the parent\n  // process. To obtain one accessible within the child, we need to use\n  // DuplicateHandle.\n  if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,\n                         ::GetCurrentProcess(), &dup_write_handle,\n                         0x0,    // Requested privileges ignored since\n                                 // DUPLICATE_SAME_ACCESS is used.\n                         FALSE,  // Request non-inheritable handler.\n                         DUPLICATE_SAME_ACCESS)) {\n    DeathTestAbort(\"Unable to duplicate the pipe handle \" +\n                   StreamableToString(write_handle_as_size_t) +\n                   \" from the parent process \" +\n                   StreamableToString(parent_process_id));\n  }\n\n  const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);\n  HANDLE dup_event_handle;\n\n  if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,\n                         ::GetCurrentProcess(), &dup_event_handle, 0x0, FALSE,\n                         DUPLICATE_SAME_ACCESS)) {\n    DeathTestAbort(\"Unable to duplicate the event handle \" +\n                   StreamableToString(event_handle_as_size_t) +\n                   \" from the parent process \" +\n                   StreamableToString(parent_process_id));\n  }\n\n  const int write_fd =\n      ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);\n  if (write_fd == -1) {\n    DeathTestAbort(\"Unable to convert pipe handle \" +\n                   StreamableToString(write_handle_as_size_t) +\n                   \" to a file descriptor\");\n  }\n\n  // Signals the parent that the write end of the pipe has been acquired\n  // so the parent can release its own write end.\n  ::SetEvent(dup_event_handle);\n\n  return write_fd;\n}\n#endif  // GTEST_OS_WINDOWS\n\n// Returns a newly created InternalRunDeathTestFlag object with fields\n// initialized from the GTEST_FLAG(internal_run_death_test) flag if\n// the flag is specified; otherwise returns NULL.\nInternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {\n  if (GTEST_FLAG_GET(internal_run_death_test) == \"\") return nullptr;\n\n  // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we\n  // can use it here.\n  int line = -1;\n  int index = -1;\n  ::std::vector< ::std::string> fields;\n  SplitString(GTEST_FLAG_GET(internal_run_death_test), '|', &fields);\n  int write_fd = -1;\n\n#if GTEST_OS_WINDOWS\n\n  unsigned int parent_process_id = 0;\n  size_t write_handle_as_size_t = 0;\n  size_t event_handle_as_size_t = 0;\n\n  if (fields.size() != 6 || !ParseNaturalNumber(fields[1], &line) ||\n      !ParseNaturalNumber(fields[2], &index) ||\n      !ParseNaturalNumber(fields[3], &parent_process_id) ||\n      !ParseNaturalNumber(fields[4], &write_handle_as_size_t) ||\n      !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {\n    DeathTestAbort(\"Bad --gtest_internal_run_death_test flag: \" +\n                   GTEST_FLAG_GET(internal_run_death_test));\n  }\n  write_fd = GetStatusFileDescriptor(parent_process_id, write_handle_as_size_t,\n                                     event_handle_as_size_t);\n\n#elif GTEST_OS_FUCHSIA\n\n  if (fields.size() != 3 || !ParseNaturalNumber(fields[1], &line) ||\n      !ParseNaturalNumber(fields[2], &index)) {\n    DeathTestAbort(\"Bad --gtest_internal_run_death_test flag: \" +\n                   GTEST_FLAG_GET(internal_run_death_test));\n  }\n\n#else\n\n  if (fields.size() != 4 || !ParseNaturalNumber(fields[1], &line) ||\n      !ParseNaturalNumber(fields[2], &index) ||\n      !ParseNaturalNumber(fields[3], &write_fd)) {\n    DeathTestAbort(\"Bad --gtest_internal_run_death_test flag: \" +\n                   GTEST_FLAG_GET(internal_run_death_test));\n  }\n\n#endif  // GTEST_OS_WINDOWS\n\n  return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);\n}\n\n}  // namespace internal\n\n#endif  // GTEST_HAS_DEATH_TEST\n\n}  // namespace testing\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/src/gtest-filepath.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"gtest/internal/gtest-filepath.h\"\n\n#include <stdlib.h>\n\n#include \"gtest/gtest-message.h\"\n#include \"gtest/internal/gtest-port.h\"\n\n#if GTEST_OS_WINDOWS_MOBILE\n#include <windows.h>\n#elif GTEST_OS_WINDOWS\n#include <direct.h>\n#include <io.h>\n#else\n#include <limits.h>\n\n#include <climits>  // Some Linux distributions define PATH_MAX here.\n#endif              // GTEST_OS_WINDOWS_MOBILE\n\n#include \"gtest/internal/gtest-string.h\"\n\n#if GTEST_OS_WINDOWS\n#define GTEST_PATH_MAX_ _MAX_PATH\n#elif defined(PATH_MAX)\n#define GTEST_PATH_MAX_ PATH_MAX\n#elif defined(_XOPEN_PATH_MAX)\n#define GTEST_PATH_MAX_ _XOPEN_PATH_MAX\n#else\n#define GTEST_PATH_MAX_ _POSIX_PATH_MAX\n#endif  // GTEST_OS_WINDOWS\n\nnamespace testing {\nnamespace internal {\n\n#if GTEST_OS_WINDOWS\n// On Windows, '\\\\' is the standard path separator, but many tools and the\n// Windows API also accept '/' as an alternate path separator. Unless otherwise\n// noted, a file path can contain either kind of path separators, or a mixture\n// of them.\nconst char kPathSeparator = '\\\\';\nconst char kAlternatePathSeparator = '/';\nconst char kAlternatePathSeparatorString[] = \"/\";\n#if GTEST_OS_WINDOWS_MOBILE\n// Windows CE doesn't have a current directory. You should not use\n// the current directory in tests on Windows CE, but this at least\n// provides a reasonable fallback.\nconst char kCurrentDirectoryString[] = \"\\\\\";\n// Windows CE doesn't define INVALID_FILE_ATTRIBUTES\nconst DWORD kInvalidFileAttributes = 0xffffffff;\n#else\nconst char kCurrentDirectoryString[] = \".\\\\\";\n#endif  // GTEST_OS_WINDOWS_MOBILE\n#else\nconst char kPathSeparator = '/';\nconst char kCurrentDirectoryString[] = \"./\";\n#endif  // GTEST_OS_WINDOWS\n\n// Returns whether the given character is a valid path separator.\nstatic bool IsPathSeparator(char c) {\n#if GTEST_HAS_ALT_PATH_SEP_\n  return (c == kPathSeparator) || (c == kAlternatePathSeparator);\n#else\n  return c == kPathSeparator;\n#endif\n}\n\n// Returns the current working directory, or \"\" if unsuccessful.\nFilePath FilePath::GetCurrentDir() {\n#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE ||         \\\n    GTEST_OS_WINDOWS_RT || GTEST_OS_ESP8266 || GTEST_OS_ESP32 || \\\n    GTEST_OS_XTENSA\n  // These platforms do not have a current directory, so we just return\n  // something reasonable.\n  return FilePath(kCurrentDirectoryString);\n#elif GTEST_OS_WINDOWS\n  char cwd[GTEST_PATH_MAX_ + 1] = {'\\0'};\n  return FilePath(_getcwd(cwd, sizeof(cwd)) == nullptr ? \"\" : cwd);\n#else\n  char cwd[GTEST_PATH_MAX_ + 1] = {'\\0'};\n  char* result = getcwd(cwd, sizeof(cwd));\n#if GTEST_OS_NACL\n  // getcwd will likely fail in NaCl due to the sandbox, so return something\n  // reasonable. The user may have provided a shim implementation for getcwd,\n  // however, so fallback only when failure is detected.\n  return FilePath(result == nullptr ? kCurrentDirectoryString : cwd);\n#endif  // GTEST_OS_NACL\n  return FilePath(result == nullptr ? \"\" : cwd);\n#endif  // GTEST_OS_WINDOWS_MOBILE\n}\n\n// Returns a copy of the FilePath with the case-insensitive extension removed.\n// Example: FilePath(\"dir/file.exe\").RemoveExtension(\"EXE\") returns\n// FilePath(\"dir/file\"). If a case-insensitive extension is not\n// found, returns a copy of the original FilePath.\nFilePath FilePath::RemoveExtension(const char* extension) const {\n  const std::string dot_extension = std::string(\".\") + extension;\n  if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {\n    return FilePath(\n        pathname_.substr(0, pathname_.length() - dot_extension.length()));\n  }\n  return *this;\n}\n\n// Returns a pointer to the last occurrence of a valid path separator in\n// the FilePath. On Windows, for example, both '/' and '\\' are valid path\n// separators. Returns NULL if no path separator was found.\nconst char* FilePath::FindLastPathSeparator() const {\n  const char* const last_sep = strrchr(c_str(), kPathSeparator);\n#if GTEST_HAS_ALT_PATH_SEP_\n  const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);\n  // Comparing two pointers of which only one is NULL is undefined.\n  if (last_alt_sep != nullptr &&\n      (last_sep == nullptr || last_alt_sep > last_sep)) {\n    return last_alt_sep;\n  }\n#endif\n  return last_sep;\n}\n\n// Returns a copy of the FilePath with the directory part removed.\n// Example: FilePath(\"path/to/file\").RemoveDirectoryName() returns\n// FilePath(\"file\"). If there is no directory part (\"just_a_file\"), it returns\n// the FilePath unmodified. If there is no file part (\"just_a_dir/\") it\n// returns an empty FilePath (\"\").\n// On Windows platform, '\\' is the path separator, otherwise it is '/'.\nFilePath FilePath::RemoveDirectoryName() const {\n  const char* const last_sep = FindLastPathSeparator();\n  return last_sep ? FilePath(last_sep + 1) : *this;\n}\n\n// RemoveFileName returns the directory path with the filename removed.\n// Example: FilePath(\"path/to/file\").RemoveFileName() returns \"path/to/\".\n// If the FilePath is \"a_file\" or \"/a_file\", RemoveFileName returns\n// FilePath(\"./\") or, on Windows, FilePath(\".\\\\\"). If the filepath does\n// not have a file, like \"just/a/dir/\", it returns the FilePath unmodified.\n// On Windows platform, '\\' is the path separator, otherwise it is '/'.\nFilePath FilePath::RemoveFileName() const {\n  const char* const last_sep = FindLastPathSeparator();\n  std::string dir;\n  if (last_sep) {\n    dir = std::string(c_str(), static_cast<size_t>(last_sep + 1 - c_str()));\n  } else {\n    dir = kCurrentDirectoryString;\n  }\n  return FilePath(dir);\n}\n\n// Helper functions for naming files in a directory for xml output.\n\n// Given directory = \"dir\", base_name = \"test\", number = 0,\n// extension = \"xml\", returns \"dir/test.xml\". If number is greater\n// than zero (e.g., 12), returns \"dir/test_12.xml\".\n// On Windows platform, uses \\ as the separator rather than /.\nFilePath FilePath::MakeFileName(const FilePath& directory,\n                                const FilePath& base_name, int number,\n                                const char* extension) {\n  std::string file;\n  if (number == 0) {\n    file = base_name.string() + \".\" + extension;\n  } else {\n    file =\n        base_name.string() + \"_\" + StreamableToString(number) + \".\" + extension;\n  }\n  return ConcatPaths(directory, FilePath(file));\n}\n\n// Given directory = \"dir\", relative_path = \"test.xml\", returns \"dir/test.xml\".\n// On Windows, uses \\ as the separator rather than /.\nFilePath FilePath::ConcatPaths(const FilePath& directory,\n                               const FilePath& relative_path) {\n  if (directory.IsEmpty()) return relative_path;\n  const FilePath dir(directory.RemoveTrailingPathSeparator());\n  return FilePath(dir.string() + kPathSeparator + relative_path.string());\n}\n\n// Returns true if pathname describes something findable in the file-system,\n// either a file, directory, or whatever.\nbool FilePath::FileOrDirectoryExists() const {\n#if GTEST_OS_WINDOWS_MOBILE\n  LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());\n  const DWORD attributes = GetFileAttributes(unicode);\n  delete[] unicode;\n  return attributes != kInvalidFileAttributes;\n#else\n  posix::StatStruct file_stat{};\n  return posix::Stat(pathname_.c_str(), &file_stat) == 0;\n#endif  // GTEST_OS_WINDOWS_MOBILE\n}\n\n// Returns true if pathname describes a directory in the file-system\n// that exists.\nbool FilePath::DirectoryExists() const {\n  bool result = false;\n#if GTEST_OS_WINDOWS\n  // Don't strip off trailing separator if path is a root directory on\n  // Windows (like \"C:\\\\\").\n  const FilePath& path(IsRootDirectory() ? *this\n                                         : RemoveTrailingPathSeparator());\n#else\n  const FilePath& path(*this);\n#endif\n\n#if GTEST_OS_WINDOWS_MOBILE\n  LPCWSTR unicode = String::AnsiToUtf16(path.c_str());\n  const DWORD attributes = GetFileAttributes(unicode);\n  delete[] unicode;\n  if ((attributes != kInvalidFileAttributes) &&\n      (attributes & FILE_ATTRIBUTE_DIRECTORY)) {\n    result = true;\n  }\n#else\n  posix::StatStruct file_stat{};\n  result =\n      posix::Stat(path.c_str(), &file_stat) == 0 && posix::IsDir(file_stat);\n#endif  // GTEST_OS_WINDOWS_MOBILE\n\n  return result;\n}\n\n// Returns true if pathname describes a root directory. (Windows has one\n// root directory per disk drive.)\nbool FilePath::IsRootDirectory() const {\n#if GTEST_OS_WINDOWS\n  return pathname_.length() == 3 && IsAbsolutePath();\n#else\n  return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);\n#endif\n}\n\n// Returns true if pathname describes an absolute path.\nbool FilePath::IsAbsolutePath() const {\n  const char* const name = pathname_.c_str();\n#if GTEST_OS_WINDOWS\n  return pathname_.length() >= 3 &&\n         ((name[0] >= 'a' && name[0] <= 'z') ||\n          (name[0] >= 'A' && name[0] <= 'Z')) &&\n         name[1] == ':' && IsPathSeparator(name[2]);\n#else\n  return IsPathSeparator(name[0]);\n#endif\n}\n\n// Returns a pathname for a file that does not currently exist. The pathname\n// will be directory/base_name.extension or\n// directory/base_name_<number>.extension if directory/base_name.extension\n// already exists. The number will be incremented until a pathname is found\n// that does not already exist.\n// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.\n// There could be a race condition if two or more processes are calling this\n// function at the same time -- they could both pick the same filename.\nFilePath FilePath::GenerateUniqueFileName(const FilePath& directory,\n                                          const FilePath& base_name,\n                                          const char* extension) {\n  FilePath full_pathname;\n  int number = 0;\n  do {\n    full_pathname.Set(MakeFileName(directory, base_name, number++, extension));\n  } while (full_pathname.FileOrDirectoryExists());\n  return full_pathname;\n}\n\n// Returns true if FilePath ends with a path separator, which indicates that\n// it is intended to represent a directory. Returns false otherwise.\n// This does NOT check that a directory (or file) actually exists.\nbool FilePath::IsDirectory() const {\n  return !pathname_.empty() &&\n         IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);\n}\n\n// Create directories so that path exists. Returns true if successful or if\n// the directories already exist; returns false if unable to create directories\n// for any reason.\nbool FilePath::CreateDirectoriesRecursively() const {\n  if (!this->IsDirectory()) {\n    return false;\n  }\n\n  if (pathname_.length() == 0 || this->DirectoryExists()) {\n    return true;\n  }\n\n  const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());\n  return parent.CreateDirectoriesRecursively() && this->CreateFolder();\n}\n\n// Create the directory so that path exists. Returns true if successful or\n// if the directory already exists; returns false if unable to create the\n// directory for any reason, including if the parent directory does not\n// exist. Not named \"CreateDirectory\" because that's a macro on Windows.\nbool FilePath::CreateFolder() const {\n#if GTEST_OS_WINDOWS_MOBILE\n  FilePath removed_sep(this->RemoveTrailingPathSeparator());\n  LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());\n  int result = CreateDirectory(unicode, nullptr) ? 0 : -1;\n  delete[] unicode;\n#elif GTEST_OS_WINDOWS\n  int result = _mkdir(pathname_.c_str());\n#elif GTEST_OS_ESP8266 || GTEST_OS_XTENSA\n  // do nothing\n  int result = 0;\n#else\n  int result = mkdir(pathname_.c_str(), 0777);\n#endif  // GTEST_OS_WINDOWS_MOBILE\n\n  if (result == -1) {\n    return this->DirectoryExists();  // An error is OK if the directory exists.\n  }\n  return true;  // No error.\n}\n\n// If input name has a trailing separator character, remove it and return the\n// name, otherwise return the name string unmodified.\n// On Windows platform, uses \\ as the separator, other platforms use /.\nFilePath FilePath::RemoveTrailingPathSeparator() const {\n  return IsDirectory() ? FilePath(pathname_.substr(0, pathname_.length() - 1))\n                       : *this;\n}\n\n// Removes any redundant separators that might be in the pathname.\n// For example, \"bar///foo\" becomes \"bar/foo\". Does not eliminate other\n// redundancies that might be in a pathname involving \".\" or \"..\".\nvoid FilePath::Normalize() {\n  auto out = pathname_.begin();\n\n  for (const char character : pathname_) {\n    if (!IsPathSeparator(character)) {\n      *(out++) = character;\n    } else if (out == pathname_.begin() || *std::prev(out) != kPathSeparator) {\n      *(out++) = kPathSeparator;\n    } else {\n      continue;\n    }\n  }\n\n  pathname_.erase(out, pathname_.end());\n}\n\n}  // namespace internal\n}  // namespace testing\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/src/gtest-internal-inl.h",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Utility functions and classes used by the Google C++ testing framework.//\n// This file contains purely Google Test's internal implementation.  Please\n// DO NOT #INCLUDE IT IN A USER PROGRAM.\n\n#ifndef GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_\n#define GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_\n\n#ifndef _WIN32_WCE\n#include <errno.h>\n#endif  // !_WIN32_WCE\n#include <stddef.h>\n#include <stdlib.h>  // For strtoll/_strtoul64/malloc/free.\n#include <string.h>  // For memmove.\n\n#include <algorithm>\n#include <cstdint>\n#include <memory>\n#include <string>\n#include <vector>\n\n#include \"gtest/internal/gtest-port.h\"\n\n#if GTEST_CAN_STREAM_RESULTS_\n#include <arpa/inet.h>  // NOLINT\n#include <netdb.h>      // NOLINT\n#endif\n\n#if GTEST_OS_WINDOWS\n#include <windows.h>  // NOLINT\n#endif                // GTEST_OS_WINDOWS\n\n#include \"gtest/gtest-spi.h\"\n#include \"gtest/gtest.h\"\n\nGTEST_DISABLE_MSC_WARNINGS_PUSH_(4251 \\\n/* class A needs to have dll-interface to be used by clients of class B */)\n\n// Declares the flags.\n//\n// We don't want the users to modify this flag in the code, but want\n// Google Test's own unit tests to be able to access it. Therefore we\n// declare it here as opposed to in gtest.h.\nGTEST_DECLARE_bool_(death_test_use_fork);\n\nnamespace testing {\nnamespace internal {\n\n// The value of GetTestTypeId() as seen from within the Google Test\n// library.  This is solely for testing GetTestTypeId().\nGTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;\n\n// A valid random seed must be in [1, kMaxRandomSeed].\nconst int kMaxRandomSeed = 99999;\n\n// g_help_flag is true if and only if the --help flag or an equivalent form\n// is specified on the command line.\nGTEST_API_ extern bool g_help_flag;\n\n// Returns the current time in milliseconds.\nGTEST_API_ TimeInMillis GetTimeInMillis();\n\n// Returns true if and only if Google Test should use colors in the output.\nGTEST_API_ bool ShouldUseColor(bool stdout_is_tty);\n\n// Formats the given time in milliseconds as seconds.\nGTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);\n\n// Converts the given time in milliseconds to a date string in the ISO 8601\n// format, without the timezone information.  N.B.: due to the use the\n// non-reentrant localtime() function, this function is not thread safe.  Do\n// not use it in any code that can be called from multiple threads.\nGTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);\n\n// Parses a string for an Int32 flag, in the form of \"--flag=value\".\n//\n// On success, stores the value of the flag in *value, and returns\n// true.  On failure, returns false without changing *value.\nGTEST_API_ bool ParseFlag(const char* str, const char* flag, int32_t* value);\n\n// Returns a random seed in range [1, kMaxRandomSeed] based on the\n// given --gtest_random_seed flag value.\ninline int GetRandomSeedFromFlag(int32_t random_seed_flag) {\n  const unsigned int raw_seed =\n      (random_seed_flag == 0) ? static_cast<unsigned int>(GetTimeInMillis())\n                              : static_cast<unsigned int>(random_seed_flag);\n\n  // Normalizes the actual seed to range [1, kMaxRandomSeed] such that\n  // it's easy to type.\n  const int normalized_seed =\n      static_cast<int>((raw_seed - 1U) %\n                       static_cast<unsigned int>(kMaxRandomSeed)) +\n      1;\n  return normalized_seed;\n}\n\n// Returns the first valid random seed after 'seed'.  The behavior is\n// undefined if 'seed' is invalid.  The seed after kMaxRandomSeed is\n// considered to be 1.\ninline int GetNextRandomSeed(int seed) {\n  GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)\n      << \"Invalid random seed \" << seed << \" - must be in [1, \"\n      << kMaxRandomSeed << \"].\";\n  const int next_seed = seed + 1;\n  return (next_seed > kMaxRandomSeed) ? 1 : next_seed;\n}\n\n// This class saves the values of all Google Test flags in its c'tor, and\n// restores them in its d'tor.\nclass GTestFlagSaver {\n public:\n  // The c'tor.\n  GTestFlagSaver() {\n    also_run_disabled_tests_ = GTEST_FLAG_GET(also_run_disabled_tests);\n    break_on_failure_ = GTEST_FLAG_GET(break_on_failure);\n    catch_exceptions_ = GTEST_FLAG_GET(catch_exceptions);\n    color_ = GTEST_FLAG_GET(color);\n    death_test_style_ = GTEST_FLAG_GET(death_test_style);\n    death_test_use_fork_ = GTEST_FLAG_GET(death_test_use_fork);\n    fail_fast_ = GTEST_FLAG_GET(fail_fast);\n    filter_ = GTEST_FLAG_GET(filter);\n    internal_run_death_test_ = GTEST_FLAG_GET(internal_run_death_test);\n    list_tests_ = GTEST_FLAG_GET(list_tests);\n    output_ = GTEST_FLAG_GET(output);\n    brief_ = GTEST_FLAG_GET(brief);\n    print_time_ = GTEST_FLAG_GET(print_time);\n    print_utf8_ = GTEST_FLAG_GET(print_utf8);\n    random_seed_ = GTEST_FLAG_GET(random_seed);\n    repeat_ = GTEST_FLAG_GET(repeat);\n    recreate_environments_when_repeating_ =\n        GTEST_FLAG_GET(recreate_environments_when_repeating);\n    shuffle_ = GTEST_FLAG_GET(shuffle);\n    stack_trace_depth_ = GTEST_FLAG_GET(stack_trace_depth);\n    stream_result_to_ = GTEST_FLAG_GET(stream_result_to);\n    throw_on_failure_ = GTEST_FLAG_GET(throw_on_failure);\n  }\n\n  // The d'tor is not virtual.  DO NOT INHERIT FROM THIS CLASS.\n  ~GTestFlagSaver() {\n    GTEST_FLAG_SET(also_run_disabled_tests, also_run_disabled_tests_);\n    GTEST_FLAG_SET(break_on_failure, break_on_failure_);\n    GTEST_FLAG_SET(catch_exceptions, catch_exceptions_);\n    GTEST_FLAG_SET(color, color_);\n    GTEST_FLAG_SET(death_test_style, death_test_style_);\n    GTEST_FLAG_SET(death_test_use_fork, death_test_use_fork_);\n    GTEST_FLAG_SET(filter, filter_);\n    GTEST_FLAG_SET(fail_fast, fail_fast_);\n    GTEST_FLAG_SET(internal_run_death_test, internal_run_death_test_);\n    GTEST_FLAG_SET(list_tests, list_tests_);\n    GTEST_FLAG_SET(output, output_);\n    GTEST_FLAG_SET(brief, brief_);\n    GTEST_FLAG_SET(print_time, print_time_);\n    GTEST_FLAG_SET(print_utf8, print_utf8_);\n    GTEST_FLAG_SET(random_seed, random_seed_);\n    GTEST_FLAG_SET(repeat, repeat_);\n    GTEST_FLAG_SET(recreate_environments_when_repeating,\n                   recreate_environments_when_repeating_);\n    GTEST_FLAG_SET(shuffle, shuffle_);\n    GTEST_FLAG_SET(stack_trace_depth, stack_trace_depth_);\n    GTEST_FLAG_SET(stream_result_to, stream_result_to_);\n    GTEST_FLAG_SET(throw_on_failure, throw_on_failure_);\n  }\n\n private:\n  // Fields for saving the original values of flags.\n  bool also_run_disabled_tests_;\n  bool break_on_failure_;\n  bool catch_exceptions_;\n  std::string color_;\n  std::string death_test_style_;\n  bool death_test_use_fork_;\n  bool fail_fast_;\n  std::string filter_;\n  std::string internal_run_death_test_;\n  bool list_tests_;\n  std::string output_;\n  bool brief_;\n  bool print_time_;\n  bool print_utf8_;\n  int32_t random_seed_;\n  int32_t repeat_;\n  bool recreate_environments_when_repeating_;\n  bool shuffle_;\n  int32_t stack_trace_depth_;\n  std::string stream_result_to_;\n  bool throw_on_failure_;\n} GTEST_ATTRIBUTE_UNUSED_;\n\n// Converts a Unicode code point to a narrow string in UTF-8 encoding.\n// code_point parameter is of type UInt32 because wchar_t may not be\n// wide enough to contain a code point.\n// If the code_point is not a valid Unicode code point\n// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted\n// to \"(Invalid Unicode 0xXXXXXXXX)\".\nGTEST_API_ std::string CodePointToUtf8(uint32_t code_point);\n\n// Converts a wide string to a narrow string in UTF-8 encoding.\n// The wide string is assumed to have the following encoding:\n//   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)\n//   UTF-32 if sizeof(wchar_t) == 4 (on Linux)\n// Parameter str points to a null-terminated wide string.\n// Parameter num_chars may additionally limit the number\n// of wchar_t characters processed. -1 is used when the entire string\n// should be processed.\n// If the string contains code points that are not valid Unicode code points\n// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output\n// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding\n// and contains invalid UTF-16 surrogate pairs, values in those pairs\n// will be encoded as individual Unicode characters from Basic Normal Plane.\nGTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);\n\n// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file\n// if the variable is present. If a file already exists at this location, this\n// function will write over it. If the variable is present, but the file cannot\n// be created, prints an error and exits.\nvoid WriteToShardStatusFileIfNeeded();\n\n// Checks whether sharding is enabled by examining the relevant\n// environment variable values. If the variables are present,\n// but inconsistent (e.g., shard_index >= total_shards), prints\n// an error and exits. If in_subprocess_for_death_test, sharding is\n// disabled because it must only be applied to the original test\n// process. Otherwise, we could filter out death tests we intended to execute.\nGTEST_API_ bool ShouldShard(const char* total_shards_str,\n                            const char* shard_index_str,\n                            bool in_subprocess_for_death_test);\n\n// Parses the environment variable var as a 32-bit integer. If it is unset,\n// returns default_val. If it is not a 32-bit integer, prints an error and\n// and aborts.\nGTEST_API_ int32_t Int32FromEnvOrDie(const char* env_var, int32_t default_val);\n\n// Given the total number of shards, the shard index, and the test id,\n// returns true if and only if the test should be run on this shard. The test id\n// is some arbitrary but unique non-negative integer assigned to each test\n// method. Assumes that 0 <= shard_index < total_shards.\nGTEST_API_ bool ShouldRunTestOnShard(int total_shards, int shard_index,\n                                     int test_id);\n\n// STL container utilities.\n\n// Returns the number of elements in the given container that satisfy\n// the given predicate.\ntemplate <class Container, typename Predicate>\ninline int CountIf(const Container& c, Predicate predicate) {\n  // Implemented as an explicit loop since std::count_if() in libCstd on\n  // Solaris has a non-standard signature.\n  int count = 0;\n  for (auto it = c.begin(); it != c.end(); ++it) {\n    if (predicate(*it)) ++count;\n  }\n  return count;\n}\n\n// Applies a function/functor to each element in the container.\ntemplate <class Container, typename Functor>\nvoid ForEach(const Container& c, Functor functor) {\n  std::for_each(c.begin(), c.end(), functor);\n}\n\n// Returns the i-th element of the vector, or default_value if i is not\n// in range [0, v.size()).\ntemplate <typename E>\ninline E GetElementOr(const std::vector<E>& v, int i, E default_value) {\n  return (i < 0 || i >= static_cast<int>(v.size())) ? default_value\n                                                    : v[static_cast<size_t>(i)];\n}\n\n// Performs an in-place shuffle of a range of the vector's elements.\n// 'begin' and 'end' are element indices as an STL-style range;\n// i.e. [begin, end) are shuffled, where 'end' == size() means to\n// shuffle to the end of the vector.\ntemplate <typename E>\nvoid ShuffleRange(internal::Random* random, int begin, int end,\n                  std::vector<E>* v) {\n  const int size = static_cast<int>(v->size());\n  GTEST_CHECK_(0 <= begin && begin <= size)\n      << \"Invalid shuffle range start \" << begin << \": must be in range [0, \"\n      << size << \"].\";\n  GTEST_CHECK_(begin <= end && end <= size)\n      << \"Invalid shuffle range finish \" << end << \": must be in range [\"\n      << begin << \", \" << size << \"].\";\n\n  // Fisher-Yates shuffle, from\n  // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle\n  for (int range_width = end - begin; range_width >= 2; range_width--) {\n    const int last_in_range = begin + range_width - 1;\n    const int selected =\n        begin +\n        static_cast<int>(random->Generate(static_cast<uint32_t>(range_width)));\n    std::swap((*v)[static_cast<size_t>(selected)],\n              (*v)[static_cast<size_t>(last_in_range)]);\n  }\n}\n\n// Performs an in-place shuffle of the vector's elements.\ntemplate <typename E>\ninline void Shuffle(internal::Random* random, std::vector<E>* v) {\n  ShuffleRange(random, 0, static_cast<int>(v->size()), v);\n}\n\n// A function for deleting an object.  Handy for being used as a\n// functor.\ntemplate <typename T>\nstatic void Delete(T* x) {\n  delete x;\n}\n\n// A predicate that checks the key of a TestProperty against a known key.\n//\n// TestPropertyKeyIs is copyable.\nclass TestPropertyKeyIs {\n public:\n  // Constructor.\n  //\n  // TestPropertyKeyIs has NO default constructor.\n  explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}\n\n  // Returns true if and only if the test name of test property matches on key_.\n  bool operator()(const TestProperty& test_property) const {\n    return test_property.key() == key_;\n  }\n\n private:\n  std::string key_;\n};\n\n// Class UnitTestOptions.\n//\n// This class contains functions for processing options the user\n// specifies when running the tests.  It has only static members.\n//\n// In most cases, the user can specify an option using either an\n// environment variable or a command line flag.  E.g. you can set the\n// test filter using either GTEST_FILTER or --gtest_filter.  If both\n// the variable and the flag are present, the latter overrides the\n// former.\nclass GTEST_API_ UnitTestOptions {\n public:\n  // Functions for processing the gtest_output flag.\n\n  // Returns the output format, or \"\" for normal printed output.\n  static std::string GetOutputFormat();\n\n  // Returns the absolute path of the requested output file, or the\n  // default (test_detail.xml in the original working directory) if\n  // none was explicitly specified.\n  static std::string GetAbsolutePathToOutputFile();\n\n  // Functions for processing the gtest_filter flag.\n\n  // Returns true if and only if the user-specified filter matches the test\n  // suite name and the test name.\n  static bool FilterMatchesTest(const std::string& test_suite_name,\n                                const std::string& test_name);\n\n#if GTEST_OS_WINDOWS\n  // Function for supporting the gtest_catch_exception flag.\n\n  // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the\n  // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.\n  // This function is useful as an __except condition.\n  static int GTestShouldProcessSEH(DWORD exception_code);\n#endif  // GTEST_OS_WINDOWS\n\n  // Returns true if \"name\" matches the ':' separated list of glob-style\n  // filters in \"filter\".\n  static bool MatchesFilter(const std::string& name, const char* filter);\n};\n\n// Returns the current application's name, removing directory path if that\n// is present.  Used by UnitTestOptions::GetOutputFile.\nGTEST_API_ FilePath GetCurrentExecutableName();\n\n// The role interface for getting the OS stack trace as a string.\nclass OsStackTraceGetterInterface {\n public:\n  OsStackTraceGetterInterface() {}\n  virtual ~OsStackTraceGetterInterface() {}\n\n  // Returns the current OS stack trace as an std::string.  Parameters:\n  //\n  //   max_depth  - the maximum number of stack frames to be included\n  //                in the trace.\n  //   skip_count - the number of top frames to be skipped; doesn't count\n  //                against max_depth.\n  virtual std::string CurrentStackTrace(int max_depth, int skip_count) = 0;\n\n  // UponLeavingGTest() should be called immediately before Google Test calls\n  // user code. It saves some information about the current stack that\n  // CurrentStackTrace() will use to find and hide Google Test stack frames.\n  virtual void UponLeavingGTest() = 0;\n\n  // This string is inserted in place of stack frames that are part of\n  // Google Test's implementation.\n  static const char* const kElidedFramesMarker;\n\n private:\n  OsStackTraceGetterInterface(const OsStackTraceGetterInterface&) = delete;\n  OsStackTraceGetterInterface& operator=(const OsStackTraceGetterInterface&) =\n      delete;\n};\n\n// A working implementation of the OsStackTraceGetterInterface interface.\nclass OsStackTraceGetter : public OsStackTraceGetterInterface {\n public:\n  OsStackTraceGetter() {}\n\n  std::string CurrentStackTrace(int max_depth, int skip_count) override;\n  void UponLeavingGTest() override;\n\n private:\n#if GTEST_HAS_ABSL\n  Mutex mutex_;  // Protects all internal state.\n\n  // We save the stack frame below the frame that calls user code.\n  // We do this because the address of the frame immediately below\n  // the user code changes between the call to UponLeavingGTest()\n  // and any calls to the stack trace code from within the user code.\n  void* caller_frame_ = nullptr;\n#endif  // GTEST_HAS_ABSL\n\n  OsStackTraceGetter(const OsStackTraceGetter&) = delete;\n  OsStackTraceGetter& operator=(const OsStackTraceGetter&) = delete;\n};\n\n// Information about a Google Test trace point.\nstruct TraceInfo {\n  const char* file;\n  int line;\n  std::string message;\n};\n\n// This is the default global test part result reporter used in UnitTestImpl.\n// This class should only be used by UnitTestImpl.\nclass DefaultGlobalTestPartResultReporter\n    : public TestPartResultReporterInterface {\n public:\n  explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);\n  // Implements the TestPartResultReporterInterface. Reports the test part\n  // result in the current test.\n  void ReportTestPartResult(const TestPartResult& result) override;\n\n private:\n  UnitTestImpl* const unit_test_;\n\n  DefaultGlobalTestPartResultReporter(\n      const DefaultGlobalTestPartResultReporter&) = delete;\n  DefaultGlobalTestPartResultReporter& operator=(\n      const DefaultGlobalTestPartResultReporter&) = delete;\n};\n\n// This is the default per thread test part result reporter used in\n// UnitTestImpl. This class should only be used by UnitTestImpl.\nclass DefaultPerThreadTestPartResultReporter\n    : public TestPartResultReporterInterface {\n public:\n  explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);\n  // Implements the TestPartResultReporterInterface. The implementation just\n  // delegates to the current global test part result reporter of *unit_test_.\n  void ReportTestPartResult(const TestPartResult& result) override;\n\n private:\n  UnitTestImpl* const unit_test_;\n\n  DefaultPerThreadTestPartResultReporter(\n      const DefaultPerThreadTestPartResultReporter&) = delete;\n  DefaultPerThreadTestPartResultReporter& operator=(\n      const DefaultPerThreadTestPartResultReporter&) = delete;\n};\n\n// The private implementation of the UnitTest class.  We don't protect\n// the methods under a mutex, as this class is not accessible by a\n// user and the UnitTest class that delegates work to this class does\n// proper locking.\nclass GTEST_API_ UnitTestImpl {\n public:\n  explicit UnitTestImpl(UnitTest* parent);\n  virtual ~UnitTestImpl();\n\n  // There are two different ways to register your own TestPartResultReporter.\n  // You can register your own repoter to listen either only for test results\n  // from the current thread or for results from all threads.\n  // By default, each per-thread test result repoter just passes a new\n  // TestPartResult to the global test result reporter, which registers the\n  // test part result for the currently running test.\n\n  // Returns the global test part result reporter.\n  TestPartResultReporterInterface* GetGlobalTestPartResultReporter();\n\n  // Sets the global test part result reporter.\n  void SetGlobalTestPartResultReporter(\n      TestPartResultReporterInterface* reporter);\n\n  // Returns the test part result reporter for the current thread.\n  TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();\n\n  // Sets the test part result reporter for the current thread.\n  void SetTestPartResultReporterForCurrentThread(\n      TestPartResultReporterInterface* reporter);\n\n  // Gets the number of successful test suites.\n  int successful_test_suite_count() const;\n\n  // Gets the number of failed test suites.\n  int failed_test_suite_count() const;\n\n  // Gets the number of all test suites.\n  int total_test_suite_count() const;\n\n  // Gets the number of all test suites that contain at least one test\n  // that should run.\n  int test_suite_to_run_count() const;\n\n  // Gets the number of successful tests.\n  int successful_test_count() const;\n\n  // Gets the number of skipped tests.\n  int skipped_test_count() const;\n\n  // Gets the number of failed tests.\n  int failed_test_count() const;\n\n  // Gets the number of disabled tests that will be reported in the XML report.\n  int reportable_disabled_test_count() const;\n\n  // Gets the number of disabled tests.\n  int disabled_test_count() const;\n\n  // Gets the number of tests to be printed in the XML report.\n  int reportable_test_count() const;\n\n  // Gets the number of all tests.\n  int total_test_count() const;\n\n  // Gets the number of tests that should run.\n  int test_to_run_count() const;\n\n  // Gets the time of the test program start, in ms from the start of the\n  // UNIX epoch.\n  TimeInMillis start_timestamp() const { return start_timestamp_; }\n\n  // Gets the elapsed time, in milliseconds.\n  TimeInMillis elapsed_time() const { return elapsed_time_; }\n\n  // Returns true if and only if the unit test passed (i.e. all test suites\n  // passed).\n  bool Passed() const { return !Failed(); }\n\n  // Returns true if and only if the unit test failed (i.e. some test suite\n  // failed or something outside of all tests failed).\n  bool Failed() const {\n    return failed_test_suite_count() > 0 || ad_hoc_test_result()->Failed();\n  }\n\n  // Gets the i-th test suite among all the test suites. i can range from 0 to\n  // total_test_suite_count() - 1. If i is not in that range, returns NULL.\n  const TestSuite* GetTestSuite(int i) const {\n    const int index = GetElementOr(test_suite_indices_, i, -1);\n    return index < 0 ? nullptr : test_suites_[static_cast<size_t>(i)];\n  }\n\n  //  Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  const TestCase* GetTestCase(int i) const { return GetTestSuite(i); }\n#endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n  // Gets the i-th test suite among all the test suites. i can range from 0 to\n  // total_test_suite_count() - 1. If i is not in that range, returns NULL.\n  TestSuite* GetMutableSuiteCase(int i) {\n    const int index = GetElementOr(test_suite_indices_, i, -1);\n    return index < 0 ? nullptr : test_suites_[static_cast<size_t>(index)];\n  }\n\n  // Provides access to the event listener list.\n  TestEventListeners* listeners() { return &listeners_; }\n\n  // Returns the TestResult for the test that's currently running, or\n  // the TestResult for the ad hoc test if no test is running.\n  TestResult* current_test_result();\n\n  // Returns the TestResult for the ad hoc test.\n  const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }\n\n  // Sets the OS stack trace getter.\n  //\n  // Does nothing if the input and the current OS stack trace getter\n  // are the same; otherwise, deletes the old getter and makes the\n  // input the current getter.\n  void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);\n\n  // Returns the current OS stack trace getter if it is not NULL;\n  // otherwise, creates an OsStackTraceGetter, makes it the current\n  // getter, and returns it.\n  OsStackTraceGetterInterface* os_stack_trace_getter();\n\n  // Returns the current OS stack trace as an std::string.\n  //\n  // The maximum number of stack frames to be included is specified by\n  // the gtest_stack_trace_depth flag.  The skip_count parameter\n  // specifies the number of top frames to be skipped, which doesn't\n  // count against the number of frames to be included.\n  //\n  // For example, if Foo() calls Bar(), which in turn calls\n  // CurrentOsStackTraceExceptTop(1), Foo() will be included in the\n  // trace but Bar() and CurrentOsStackTraceExceptTop() won't.\n  std::string CurrentOsStackTraceExceptTop(int skip_count)\n      GTEST_NO_INLINE_ GTEST_NO_TAIL_CALL_;\n\n  // Finds and returns a TestSuite with the given name.  If one doesn't\n  // exist, creates one and returns it.\n  //\n  // Arguments:\n  //\n  //   test_suite_name: name of the test suite\n  //   type_param:      the name of the test's type parameter, or NULL if\n  //                    this is not a typed or a type-parameterized test.\n  //   set_up_tc:       pointer to the function that sets up the test suite\n  //   tear_down_tc:    pointer to the function that tears down the test suite\n  TestSuite* GetTestSuite(const char* test_suite_name, const char* type_param,\n                          internal::SetUpTestSuiteFunc set_up_tc,\n                          internal::TearDownTestSuiteFunc tear_down_tc);\n\n//  Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  TestCase* GetTestCase(const char* test_case_name, const char* type_param,\n                        internal::SetUpTestSuiteFunc set_up_tc,\n                        internal::TearDownTestSuiteFunc tear_down_tc) {\n    return GetTestSuite(test_case_name, type_param, set_up_tc, tear_down_tc);\n  }\n#endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n  // Adds a TestInfo to the unit test.\n  //\n  // Arguments:\n  //\n  //   set_up_tc:    pointer to the function that sets up the test suite\n  //   tear_down_tc: pointer to the function that tears down the test suite\n  //   test_info:    the TestInfo object\n  void AddTestInfo(internal::SetUpTestSuiteFunc set_up_tc,\n                   internal::TearDownTestSuiteFunc tear_down_tc,\n                   TestInfo* test_info) {\n#if GTEST_HAS_DEATH_TEST\n    // In order to support thread-safe death tests, we need to\n    // remember the original working directory when the test program\n    // was first invoked.  We cannot do this in RUN_ALL_TESTS(), as\n    // the user may have changed the current directory before calling\n    // RUN_ALL_TESTS().  Therefore we capture the current directory in\n    // AddTestInfo(), which is called to register a TEST or TEST_F\n    // before main() is reached.\n    if (original_working_dir_.IsEmpty()) {\n      original_working_dir_.Set(FilePath::GetCurrentDir());\n      GTEST_CHECK_(!original_working_dir_.IsEmpty())\n          << \"Failed to get the current working directory.\";\n    }\n#endif  // GTEST_HAS_DEATH_TEST\n\n    GetTestSuite(test_info->test_suite_name(), test_info->type_param(),\n                 set_up_tc, tear_down_tc)\n        ->AddTestInfo(test_info);\n  }\n\n  // Returns ParameterizedTestSuiteRegistry object used to keep track of\n  // value-parameterized tests and instantiate and register them.\n  internal::ParameterizedTestSuiteRegistry& parameterized_test_registry() {\n    return parameterized_test_registry_;\n  }\n\n  std::set<std::string>* ignored_parameterized_test_suites() {\n    return &ignored_parameterized_test_suites_;\n  }\n\n  // Returns TypeParameterizedTestSuiteRegistry object used to keep track of\n  // type-parameterized tests and instantiations of them.\n  internal::TypeParameterizedTestSuiteRegistry&\n  type_parameterized_test_registry() {\n    return type_parameterized_test_registry_;\n  }\n\n  // Sets the TestSuite object for the test that's currently running.\n  void set_current_test_suite(TestSuite* a_current_test_suite) {\n    current_test_suite_ = a_current_test_suite;\n  }\n\n  // Sets the TestInfo object for the test that's currently running.  If\n  // current_test_info is NULL, the assertion results will be stored in\n  // ad_hoc_test_result_.\n  void set_current_test_info(TestInfo* a_current_test_info) {\n    current_test_info_ = a_current_test_info;\n  }\n\n  // Registers all parameterized tests defined using TEST_P and\n  // INSTANTIATE_TEST_SUITE_P, creating regular tests for each test/parameter\n  // combination. This method can be called more then once; it has guards\n  // protecting from registering the tests more then once.  If\n  // value-parameterized tests are disabled, RegisterParameterizedTests is\n  // present but does nothing.\n  void RegisterParameterizedTests();\n\n  // Runs all tests in this UnitTest object, prints the result, and\n  // returns true if all tests are successful.  If any exception is\n  // thrown during a test, this test is considered to be failed, but\n  // the rest of the tests will still be run.\n  bool RunAllTests();\n\n  // Clears the results of all tests, except the ad hoc tests.\n  void ClearNonAdHocTestResult() {\n    ForEach(test_suites_, TestSuite::ClearTestSuiteResult);\n  }\n\n  // Clears the results of ad-hoc test assertions.\n  void ClearAdHocTestResult() { ad_hoc_test_result_.Clear(); }\n\n  // Adds a TestProperty to the current TestResult object when invoked in a\n  // context of a test or a test suite, or to the global property set. If the\n  // result already contains a property with the same key, the value will be\n  // updated.\n  void RecordProperty(const TestProperty& test_property);\n\n  enum ReactionToSharding { HONOR_SHARDING_PROTOCOL, IGNORE_SHARDING_PROTOCOL };\n\n  // Matches the full name of each test against the user-specified\n  // filter to decide whether the test should run, then records the\n  // result in each TestSuite and TestInfo object.\n  // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests\n  // based on sharding variables in the environment.\n  // Returns the number of tests that should run.\n  int FilterTests(ReactionToSharding shard_tests);\n\n  // Prints the names of the tests matching the user-specified filter flag.\n  void ListTestsMatchingFilter();\n\n  const TestSuite* current_test_suite() const { return current_test_suite_; }\n  TestInfo* current_test_info() { return current_test_info_; }\n  const TestInfo* current_test_info() const { return current_test_info_; }\n\n  // Returns the vector of environments that need to be set-up/torn-down\n  // before/after the tests are run.\n  std::vector<Environment*>& environments() { return environments_; }\n\n  // Getters for the per-thread Google Test trace stack.\n  std::vector<TraceInfo>& gtest_trace_stack() {\n    return *(gtest_trace_stack_.pointer());\n  }\n  const std::vector<TraceInfo>& gtest_trace_stack() const {\n    return gtest_trace_stack_.get();\n  }\n\n#if GTEST_HAS_DEATH_TEST\n  void InitDeathTestSubprocessControlInfo() {\n    internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());\n  }\n  // Returns a pointer to the parsed --gtest_internal_run_death_test\n  // flag, or NULL if that flag was not specified.\n  // This information is useful only in a death test child process.\n  // Must not be called before a call to InitGoogleTest.\n  const InternalRunDeathTestFlag* internal_run_death_test_flag() const {\n    return internal_run_death_test_flag_.get();\n  }\n\n  // Returns a pointer to the current death test factory.\n  internal::DeathTestFactory* death_test_factory() {\n    return death_test_factory_.get();\n  }\n\n  void SuppressTestEventsIfInSubprocess();\n\n  friend class ReplaceDeathTestFactory;\n#endif  // GTEST_HAS_DEATH_TEST\n\n  // Initializes the event listener performing XML output as specified by\n  // UnitTestOptions. Must not be called before InitGoogleTest.\n  void ConfigureXmlOutput();\n\n#if GTEST_CAN_STREAM_RESULTS_\n  // Initializes the event listener for streaming test results to a socket.\n  // Must not be called before InitGoogleTest.\n  void ConfigureStreamingOutput();\n#endif\n\n  // Performs initialization dependent upon flag values obtained in\n  // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to\n  // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest\n  // this function is also called from RunAllTests.  Since this function can be\n  // called more than once, it has to be idempotent.\n  void PostFlagParsingInit();\n\n  // Gets the random seed used at the start of the current test iteration.\n  int random_seed() const { return random_seed_; }\n\n  // Gets the random number generator.\n  internal::Random* random() { return &random_; }\n\n  // Shuffles all test suites, and the tests within each test suite,\n  // making sure that death tests are still run first.\n  void ShuffleTests();\n\n  // Restores the test suites and tests to their order before the first shuffle.\n  void UnshuffleTests();\n\n  // Returns the value of GTEST_FLAG(catch_exceptions) at the moment\n  // UnitTest::Run() starts.\n  bool catch_exceptions() const { return catch_exceptions_; }\n\n private:\n  friend class ::testing::UnitTest;\n\n  // Used by UnitTest::Run() to capture the state of\n  // GTEST_FLAG(catch_exceptions) at the moment it starts.\n  void set_catch_exceptions(bool value) { catch_exceptions_ = value; }\n\n  // The UnitTest object that owns this implementation object.\n  UnitTest* const parent_;\n\n  // The working directory when the first TEST() or TEST_F() was\n  // executed.\n  internal::FilePath original_working_dir_;\n\n  // The default test part result reporters.\n  DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;\n  DefaultPerThreadTestPartResultReporter\n      default_per_thread_test_part_result_reporter_;\n\n  // Points to (but doesn't own) the global test part result reporter.\n  TestPartResultReporterInterface* global_test_part_result_repoter_;\n\n  // Protects read and write access to global_test_part_result_reporter_.\n  internal::Mutex global_test_part_result_reporter_mutex_;\n\n  // Points to (but doesn't own) the per-thread test part result reporter.\n  internal::ThreadLocal<TestPartResultReporterInterface*>\n      per_thread_test_part_result_reporter_;\n\n  // The vector of environments that need to be set-up/torn-down\n  // before/after the tests are run.\n  std::vector<Environment*> environments_;\n\n  // The vector of TestSuites in their original order.  It owns the\n  // elements in the vector.\n  std::vector<TestSuite*> test_suites_;\n\n  // Provides a level of indirection for the test suite list to allow\n  // easy shuffling and restoring the test suite order.  The i-th\n  // element of this vector is the index of the i-th test suite in the\n  // shuffled order.\n  std::vector<int> test_suite_indices_;\n\n  // ParameterizedTestRegistry object used to register value-parameterized\n  // tests.\n  internal::ParameterizedTestSuiteRegistry parameterized_test_registry_;\n  internal::TypeParameterizedTestSuiteRegistry\n      type_parameterized_test_registry_;\n\n  // The set holding the name of parameterized\n  // test suites that may go uninstantiated.\n  std::set<std::string> ignored_parameterized_test_suites_;\n\n  // Indicates whether RegisterParameterizedTests() has been called already.\n  bool parameterized_tests_registered_;\n\n  // Index of the last death test suite registered.  Initially -1.\n  int last_death_test_suite_;\n\n  // This points to the TestSuite for the currently running test.  It\n  // changes as Google Test goes through one test suite after another.\n  // When no test is running, this is set to NULL and Google Test\n  // stores assertion results in ad_hoc_test_result_.  Initially NULL.\n  TestSuite* current_test_suite_;\n\n  // This points to the TestInfo for the currently running test.  It\n  // changes as Google Test goes through one test after another.  When\n  // no test is running, this is set to NULL and Google Test stores\n  // assertion results in ad_hoc_test_result_.  Initially NULL.\n  TestInfo* current_test_info_;\n\n  // Normally, a user only writes assertions inside a TEST or TEST_F,\n  // or inside a function called by a TEST or TEST_F.  Since Google\n  // Test keeps track of which test is current running, it can\n  // associate such an assertion with the test it belongs to.\n  //\n  // If an assertion is encountered when no TEST or TEST_F is running,\n  // Google Test attributes the assertion result to an imaginary \"ad hoc\"\n  // test, and records the result in ad_hoc_test_result_.\n  TestResult ad_hoc_test_result_;\n\n  // The list of event listeners that can be used to track events inside\n  // Google Test.\n  TestEventListeners listeners_;\n\n  // The OS stack trace getter.  Will be deleted when the UnitTest\n  // object is destructed.  By default, an OsStackTraceGetter is used,\n  // but the user can set this field to use a custom getter if that is\n  // desired.\n  OsStackTraceGetterInterface* os_stack_trace_getter_;\n\n  // True if and only if PostFlagParsingInit() has been called.\n  bool post_flag_parse_init_performed_;\n\n  // The random number seed used at the beginning of the test run.\n  int random_seed_;\n\n  // Our random number generator.\n  internal::Random random_;\n\n  // The time of the test program start, in ms from the start of the\n  // UNIX epoch.\n  TimeInMillis start_timestamp_;\n\n  // How long the test took to run, in milliseconds.\n  TimeInMillis elapsed_time_;\n\n#if GTEST_HAS_DEATH_TEST\n  // The decomposed components of the gtest_internal_run_death_test flag,\n  // parsed when RUN_ALL_TESTS is called.\n  std::unique_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;\n  std::unique_ptr<internal::DeathTestFactory> death_test_factory_;\n#endif  // GTEST_HAS_DEATH_TEST\n\n  // A per-thread stack of traces created by the SCOPED_TRACE() macro.\n  internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;\n\n  // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()\n  // starts.\n  bool catch_exceptions_;\n\n  UnitTestImpl(const UnitTestImpl&) = delete;\n  UnitTestImpl& operator=(const UnitTestImpl&) = delete;\n};  // class UnitTestImpl\n\n// Convenience function for accessing the global UnitTest\n// implementation object.\ninline UnitTestImpl* GetUnitTestImpl() {\n  return UnitTest::GetInstance()->impl();\n}\n\n#if GTEST_USES_SIMPLE_RE\n\n// Internal helper functions for implementing the simple regular\n// expression matcher.\nGTEST_API_ bool IsInSet(char ch, const char* str);\nGTEST_API_ bool IsAsciiDigit(char ch);\nGTEST_API_ bool IsAsciiPunct(char ch);\nGTEST_API_ bool IsRepeat(char ch);\nGTEST_API_ bool IsAsciiWhiteSpace(char ch);\nGTEST_API_ bool IsAsciiWordChar(char ch);\nGTEST_API_ bool IsValidEscape(char ch);\nGTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);\nGTEST_API_ bool ValidateRegex(const char* regex);\nGTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);\nGTEST_API_ bool MatchRepetitionAndRegexAtHead(bool escaped, char ch,\n                                              char repeat, const char* regex,\n                                              const char* str);\nGTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);\n\n#endif  // GTEST_USES_SIMPLE_RE\n\n// Parses the command line for Google Test flags, without initializing\n// other parts of Google Test.\nGTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);\nGTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);\n\n#if GTEST_HAS_DEATH_TEST\n\n// Returns the message describing the last system error, regardless of the\n// platform.\nGTEST_API_ std::string GetLastErrnoDescription();\n\n// Attempts to parse a string into a positive integer pointed to by the\n// number parameter.  Returns true if that is possible.\n// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use\n// it here.\ntemplate <typename Integer>\nbool ParseNaturalNumber(const ::std::string& str, Integer* number) {\n  // Fail fast if the given string does not begin with a digit;\n  // this bypasses strtoXXX's \"optional leading whitespace and plus\n  // or minus sign\" semantics, which are undesirable here.\n  if (str.empty() || !IsDigit(str[0])) {\n    return false;\n  }\n  errno = 0;\n\n  char* end;\n  // BiggestConvertible is the largest integer type that system-provided\n  // string-to-number conversion routines can return.\n  using BiggestConvertible = unsigned long long;  // NOLINT\n\n  const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);  // NOLINT\n  const bool parse_success = *end == '\\0' && errno == 0;\n\n  GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));\n\n  const Integer result = static_cast<Integer>(parsed);\n  if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {\n    *number = result;\n    return true;\n  }\n  return false;\n}\n#endif  // GTEST_HAS_DEATH_TEST\n\n// TestResult contains some private methods that should be hidden from\n// Google Test user but are required for testing. This class allow our tests\n// to access them.\n//\n// This class is supplied only for the purpose of testing Google Test's own\n// constructs. Do not use it in user tests, either directly or indirectly.\nclass TestResultAccessor {\n public:\n  static void RecordProperty(TestResult* test_result,\n                             const std::string& xml_element,\n                             const TestProperty& property) {\n    test_result->RecordProperty(xml_element, property);\n  }\n\n  static void ClearTestPartResults(TestResult* test_result) {\n    test_result->ClearTestPartResults();\n  }\n\n  static const std::vector<testing::TestPartResult>& test_part_results(\n      const TestResult& test_result) {\n    return test_result.test_part_results();\n  }\n};\n\n#if GTEST_CAN_STREAM_RESULTS_\n\n// Streams test results to the given port on the given host machine.\nclass StreamingListener : public EmptyTestEventListener {\n public:\n  // Abstract base class for writing strings to a socket.\n  class AbstractSocketWriter {\n   public:\n    virtual ~AbstractSocketWriter() {}\n\n    // Sends a string to the socket.\n    virtual void Send(const std::string& message) = 0;\n\n    // Closes the socket.\n    virtual void CloseConnection() {}\n\n    // Sends a string and a newline to the socket.\n    void SendLn(const std::string& message) { Send(message + \"\\n\"); }\n  };\n\n  // Concrete class for actually writing strings to a socket.\n  class SocketWriter : public AbstractSocketWriter {\n   public:\n    SocketWriter(const std::string& host, const std::string& port)\n        : sockfd_(-1), host_name_(host), port_num_(port) {\n      MakeConnection();\n    }\n\n    ~SocketWriter() override {\n      if (sockfd_ != -1) CloseConnection();\n    }\n\n    // Sends a string to the socket.\n    void Send(const std::string& message) override {\n      GTEST_CHECK_(sockfd_ != -1)\n          << \"Send() can be called only when there is a connection.\";\n\n      const auto len = static_cast<size_t>(message.length());\n      if (write(sockfd_, message.c_str(), len) != static_cast<ssize_t>(len)) {\n        GTEST_LOG_(WARNING) << \"stream_result_to: failed to stream to \"\n                            << host_name_ << \":\" << port_num_;\n      }\n    }\n\n   private:\n    // Creates a client socket and connects to the server.\n    void MakeConnection();\n\n    // Closes the socket.\n    void CloseConnection() override {\n      GTEST_CHECK_(sockfd_ != -1)\n          << \"CloseConnection() can be called only when there is a connection.\";\n\n      close(sockfd_);\n      sockfd_ = -1;\n    }\n\n    int sockfd_;  // socket file descriptor\n    const std::string host_name_;\n    const std::string port_num_;\n\n    SocketWriter(const SocketWriter&) = delete;\n    SocketWriter& operator=(const SocketWriter&) = delete;\n  };  // class SocketWriter\n\n  // Escapes '=', '&', '%', and '\\n' characters in str as \"%xx\".\n  static std::string UrlEncode(const char* str);\n\n  StreamingListener(const std::string& host, const std::string& port)\n      : socket_writer_(new SocketWriter(host, port)) {\n    Start();\n  }\n\n  explicit StreamingListener(AbstractSocketWriter* socket_writer)\n      : socket_writer_(socket_writer) {\n    Start();\n  }\n\n  void OnTestProgramStart(const UnitTest& /* unit_test */) override {\n    SendLn(\"event=TestProgramStart\");\n  }\n\n  void OnTestProgramEnd(const UnitTest& unit_test) override {\n    // Note that Google Test current only report elapsed time for each\n    // test iteration, not for the entire test program.\n    SendLn(\"event=TestProgramEnd&passed=\" + FormatBool(unit_test.Passed()));\n\n    // Notify the streaming server to stop.\n    socket_writer_->CloseConnection();\n  }\n\n  void OnTestIterationStart(const UnitTest& /* unit_test */,\n                            int iteration) override {\n    SendLn(\"event=TestIterationStart&iteration=\" +\n           StreamableToString(iteration));\n  }\n\n  void OnTestIterationEnd(const UnitTest& unit_test,\n                          int /* iteration */) override {\n    SendLn(\"event=TestIterationEnd&passed=\" + FormatBool(unit_test.Passed()) +\n           \"&elapsed_time=\" + StreamableToString(unit_test.elapsed_time()) +\n           \"ms\");\n  }\n\n  // Note that \"event=TestCaseStart\" is a wire format and has to remain\n  // \"case\" for compatibility\n  void OnTestSuiteStart(const TestSuite& test_suite) override {\n    SendLn(std::string(\"event=TestCaseStart&name=\") + test_suite.name());\n  }\n\n  // Note that \"event=TestCaseEnd\" is a wire format and has to remain\n  // \"case\" for compatibility\n  void OnTestSuiteEnd(const TestSuite& test_suite) override {\n    SendLn(\"event=TestCaseEnd&passed=\" + FormatBool(test_suite.Passed()) +\n           \"&elapsed_time=\" + StreamableToString(test_suite.elapsed_time()) +\n           \"ms\");\n  }\n\n  void OnTestStart(const TestInfo& test_info) override {\n    SendLn(std::string(\"event=TestStart&name=\") + test_info.name());\n  }\n\n  void OnTestEnd(const TestInfo& test_info) override {\n    SendLn(\"event=TestEnd&passed=\" +\n           FormatBool((test_info.result())->Passed()) + \"&elapsed_time=\" +\n           StreamableToString((test_info.result())->elapsed_time()) + \"ms\");\n  }\n\n  void OnTestPartResult(const TestPartResult& test_part_result) override {\n    const char* file_name = test_part_result.file_name();\n    if (file_name == nullptr) file_name = \"\";\n    SendLn(\"event=TestPartResult&file=\" + UrlEncode(file_name) +\n           \"&line=\" + StreamableToString(test_part_result.line_number()) +\n           \"&message=\" + UrlEncode(test_part_result.message()));\n  }\n\n private:\n  // Sends the given message and a newline to the socket.\n  void SendLn(const std::string& message) { socket_writer_->SendLn(message); }\n\n  // Called at the start of streaming to notify the receiver what\n  // protocol we are using.\n  void Start() { SendLn(\"gtest_streaming_protocol_version=1.0\"); }\n\n  std::string FormatBool(bool value) { return value ? \"1\" : \"0\"; }\n\n  const std::unique_ptr<AbstractSocketWriter> socket_writer_;\n\n  StreamingListener(const StreamingListener&) = delete;\n  StreamingListener& operator=(const StreamingListener&) = delete;\n};  // class StreamingListener\n\n#endif  // GTEST_CAN_STREAM_RESULTS_\n\n}  // namespace internal\n}  // namespace testing\n\nGTEST_DISABLE_MSC_WARNINGS_POP_()  //  4251\n\n#endif  // GOOGLETEST_SRC_GTEST_INTERNAL_INL_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/src/gtest-matchers.cc",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// The Google C++ Testing and Mocking Framework (Google Test)\n//\n// This file implements just enough of the matcher interface to allow\n// EXPECT_DEATH and friends to accept a matcher argument.\n\n#include \"gtest/gtest-matchers.h\"\n\n#include <string>\n\n#include \"gtest/internal/gtest-internal.h\"\n#include \"gtest/internal/gtest-port.h\"\n\nnamespace testing {\n\n// Constructs a matcher that matches a const std::string& whose value is\n// equal to s.\nMatcher<const std::string&>::Matcher(const std::string& s) { *this = Eq(s); }\n\n// Constructs a matcher that matches a const std::string& whose value is\n// equal to s.\nMatcher<const std::string&>::Matcher(const char* s) {\n  *this = Eq(std::string(s));\n}\n\n// Constructs a matcher that matches a std::string whose value is equal to\n// s.\nMatcher<std::string>::Matcher(const std::string& s) { *this = Eq(s); }\n\n// Constructs a matcher that matches a std::string whose value is equal to\n// s.\nMatcher<std::string>::Matcher(const char* s) { *this = Eq(std::string(s)); }\n\n#if GTEST_INTERNAL_HAS_STRING_VIEW\n// Constructs a matcher that matches a const StringView& whose value is\n// equal to s.\nMatcher<const internal::StringView&>::Matcher(const std::string& s) {\n  *this = Eq(s);\n}\n\n// Constructs a matcher that matches a const StringView& whose value is\n// equal to s.\nMatcher<const internal::StringView&>::Matcher(const char* s) {\n  *this = Eq(std::string(s));\n}\n\n// Constructs a matcher that matches a const StringView& whose value is\n// equal to s.\nMatcher<const internal::StringView&>::Matcher(internal::StringView s) {\n  *this = Eq(std::string(s));\n}\n\n// Constructs a matcher that matches a StringView whose value is equal to\n// s.\nMatcher<internal::StringView>::Matcher(const std::string& s) { *this = Eq(s); }\n\n// Constructs a matcher that matches a StringView whose value is equal to\n// s.\nMatcher<internal::StringView>::Matcher(const char* s) {\n  *this = Eq(std::string(s));\n}\n\n// Constructs a matcher that matches a StringView whose value is equal to\n// s.\nMatcher<internal::StringView>::Matcher(internal::StringView s) {\n  *this = Eq(std::string(s));\n}\n#endif  // GTEST_INTERNAL_HAS_STRING_VIEW\n\n}  // namespace testing\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/src/gtest-port.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"gtest/internal/gtest-port.h\"\n\n#include <limits.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <cstdint>\n#include <fstream>\n#include <memory>\n\n#if GTEST_OS_WINDOWS\n#include <io.h>\n#include <sys/stat.h>\n#include <windows.h>\n\n#include <map>  // Used in ThreadLocal.\n#ifdef _MSC_VER\n#include <crtdbg.h>\n#endif  // _MSC_VER\n#else\n#include <unistd.h>\n#endif  // GTEST_OS_WINDOWS\n\n#if GTEST_OS_MAC\n#include <mach/mach_init.h>\n#include <mach/task.h>\n#include <mach/vm_map.h>\n#endif  // GTEST_OS_MAC\n\n#if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \\\n    GTEST_OS_NETBSD || GTEST_OS_OPENBSD\n#include <sys/sysctl.h>\n#if GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD\n#include <sys/user.h>\n#endif\n#endif\n\n#if GTEST_OS_QNX\n#include <devctl.h>\n#include <fcntl.h>\n#include <sys/procfs.h>\n#endif  // GTEST_OS_QNX\n\n#if GTEST_OS_AIX\n#include <procinfo.h>\n#include <sys/types.h>\n#endif  // GTEST_OS_AIX\n\n#if GTEST_OS_FUCHSIA\n#include <zircon/process.h>\n#include <zircon/syscalls.h>\n#endif  // GTEST_OS_FUCHSIA\n\n#include \"gtest/gtest-message.h\"\n#include \"gtest/gtest-spi.h\"\n#include \"gtest/internal/gtest-internal.h\"\n#include \"gtest/internal/gtest-string.h\"\n#include \"src/gtest-internal-inl.h\"\n\nnamespace testing {\nnamespace internal {\n\n#if GTEST_OS_LINUX || GTEST_OS_GNU_HURD\n\nnamespace {\ntemplate <typename T>\nT ReadProcFileField(const std::string& filename, int field) {\n  std::string dummy;\n  std::ifstream file(filename.c_str());\n  while (field-- > 0) {\n    file >> dummy;\n  }\n  T output = 0;\n  file >> output;\n  return output;\n}\n}  // namespace\n\n// Returns the number of active threads, or 0 when there is an error.\nsize_t GetThreadCount() {\n  const std::string filename =\n      (Message() << \"/proc/\" << getpid() << \"/stat\").GetString();\n  return ReadProcFileField<size_t>(filename, 19);\n}\n\n#elif GTEST_OS_MAC\n\nsize_t GetThreadCount() {\n  const task_t task = mach_task_self();\n  mach_msg_type_number_t thread_count;\n  thread_act_array_t thread_list;\n  const kern_return_t status = task_threads(task, &thread_list, &thread_count);\n  if (status == KERN_SUCCESS) {\n    // task_threads allocates resources in thread_list and we need to free them\n    // to avoid leaks.\n    vm_deallocate(task, reinterpret_cast<vm_address_t>(thread_list),\n                  sizeof(thread_t) * thread_count);\n    return static_cast<size_t>(thread_count);\n  } else {\n    return 0;\n  }\n}\n\n#elif GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD || \\\n    GTEST_OS_NETBSD\n\n#if GTEST_OS_NETBSD\n#undef KERN_PROC\n#define KERN_PROC KERN_PROC2\n#define kinfo_proc kinfo_proc2\n#endif\n\n#if GTEST_OS_DRAGONFLY\n#define KP_NLWP(kp) (kp.kp_nthreads)\n#elif GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD\n#define KP_NLWP(kp) (kp.ki_numthreads)\n#elif GTEST_OS_NETBSD\n#define KP_NLWP(kp) (kp.p_nlwps)\n#endif\n\n// Returns the number of threads running in the process, or 0 to indicate that\n// we cannot detect it.\nsize_t GetThreadCount() {\n  int mib[] = {\n    CTL_KERN,\n    KERN_PROC,\n    KERN_PROC_PID,\n    getpid(),\n#if GTEST_OS_NETBSD\n    sizeof(struct kinfo_proc),\n    1,\n#endif\n  };\n  u_int miblen = sizeof(mib) / sizeof(mib[0]);\n  struct kinfo_proc info;\n  size_t size = sizeof(info);\n  if (sysctl(mib, miblen, &info, &size, NULL, 0)) {\n    return 0;\n  }\n  return static_cast<size_t>(KP_NLWP(info));\n}\n#elif GTEST_OS_OPENBSD\n\n// Returns the number of threads running in the process, or 0 to indicate that\n// we cannot detect it.\nsize_t GetThreadCount() {\n  int mib[] = {\n      CTL_KERN,\n      KERN_PROC,\n      KERN_PROC_PID | KERN_PROC_SHOW_THREADS,\n      getpid(),\n      sizeof(struct kinfo_proc),\n      0,\n  };\n  u_int miblen = sizeof(mib) / sizeof(mib[0]);\n\n  // get number of structs\n  size_t size;\n  if (sysctl(mib, miblen, NULL, &size, NULL, 0)) {\n    return 0;\n  }\n\n  mib[5] = static_cast<int>(size / static_cast<size_t>(mib[4]));\n\n  // populate array of structs\n  struct kinfo_proc info[mib[5]];\n  if (sysctl(mib, miblen, &info, &size, NULL, 0)) {\n    return 0;\n  }\n\n  // exclude empty members\n  size_t nthreads = 0;\n  for (size_t i = 0; i < size / static_cast<size_t>(mib[4]); i++) {\n    if (info[i].p_tid != -1) nthreads++;\n  }\n  return nthreads;\n}\n\n#elif GTEST_OS_QNX\n\n// Returns the number of threads running in the process, or 0 to indicate that\n// we cannot detect it.\nsize_t GetThreadCount() {\n  const int fd = open(\"/proc/self/as\", O_RDONLY);\n  if (fd < 0) {\n    return 0;\n  }\n  procfs_info process_info;\n  const int status =\n      devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), nullptr);\n  close(fd);\n  if (status == EOK) {\n    return static_cast<size_t>(process_info.num_threads);\n  } else {\n    return 0;\n  }\n}\n\n#elif GTEST_OS_AIX\n\nsize_t GetThreadCount() {\n  struct procentry64 entry;\n  pid_t pid = getpid();\n  int status = getprocs64(&entry, sizeof(entry), nullptr, 0, &pid, 1);\n  if (status == 1) {\n    return entry.pi_thcount;\n  } else {\n    return 0;\n  }\n}\n\n#elif GTEST_OS_FUCHSIA\n\nsize_t GetThreadCount() {\n  int dummy_buffer;\n  size_t avail;\n  zx_status_t status =\n      zx_object_get_info(zx_process_self(), ZX_INFO_PROCESS_THREADS,\n                         &dummy_buffer, 0, nullptr, &avail);\n  if (status == ZX_OK) {\n    return avail;\n  } else {\n    return 0;\n  }\n}\n\n#else\n\nsize_t GetThreadCount() {\n  // There's no portable way to detect the number of threads, so we just\n  // return 0 to indicate that we cannot detect it.\n  return 0;\n}\n\n#endif  // GTEST_OS_LINUX\n\n#if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS\n\nAutoHandle::AutoHandle() : handle_(INVALID_HANDLE_VALUE) {}\n\nAutoHandle::AutoHandle(Handle handle) : handle_(handle) {}\n\nAutoHandle::~AutoHandle() { Reset(); }\n\nAutoHandle::Handle AutoHandle::Get() const { return handle_; }\n\nvoid AutoHandle::Reset() { Reset(INVALID_HANDLE_VALUE); }\n\nvoid AutoHandle::Reset(HANDLE handle) {\n  // Resetting with the same handle we already own is invalid.\n  if (handle_ != handle) {\n    if (IsCloseable()) {\n      ::CloseHandle(handle_);\n    }\n    handle_ = handle;\n  } else {\n    GTEST_CHECK_(!IsCloseable())\n        << \"Resetting a valid handle to itself is likely a programmer error \"\n           \"and thus not allowed.\";\n  }\n}\n\nbool AutoHandle::IsCloseable() const {\n  // Different Windows APIs may use either of these values to represent an\n  // invalid handle.\n  return handle_ != nullptr && handle_ != INVALID_HANDLE_VALUE;\n}\n\nMutex::Mutex()\n    : owner_thread_id_(0),\n      type_(kDynamic),\n      critical_section_init_phase_(0),\n      critical_section_(new CRITICAL_SECTION) {\n  ::InitializeCriticalSection(critical_section_);\n}\n\nMutex::~Mutex() {\n  // Static mutexes are leaked intentionally. It is not thread-safe to try\n  // to clean them up.\n  if (type_ == kDynamic) {\n    ::DeleteCriticalSection(critical_section_);\n    delete critical_section_;\n    critical_section_ = nullptr;\n  }\n}\n\nvoid Mutex::Lock() {\n  ThreadSafeLazyInit();\n  ::EnterCriticalSection(critical_section_);\n  owner_thread_id_ = ::GetCurrentThreadId();\n}\n\nvoid Mutex::Unlock() {\n  ThreadSafeLazyInit();\n  // We don't protect writing to owner_thread_id_ here, as it's the\n  // caller's responsibility to ensure that the current thread holds the\n  // mutex when this is called.\n  owner_thread_id_ = 0;\n  ::LeaveCriticalSection(critical_section_);\n}\n\n// Does nothing if the current thread holds the mutex. Otherwise, crashes\n// with high probability.\nvoid Mutex::AssertHeld() {\n  ThreadSafeLazyInit();\n  GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())\n      << \"The current thread is not holding the mutex @\" << this;\n}\n\nnamespace {\n\n#ifdef _MSC_VER\n// Use the RAII idiom to flag mem allocs that are intentionally never\n// deallocated. The motivation is to silence the false positive mem leaks\n// that are reported by the debug version of MS's CRT which can only detect\n// if an alloc is missing a matching deallocation.\n// Example:\n//    MemoryIsNotDeallocated memory_is_not_deallocated;\n//    critical_section_ = new CRITICAL_SECTION;\n//\nclass MemoryIsNotDeallocated {\n public:\n  MemoryIsNotDeallocated() : old_crtdbg_flag_(0) {\n    old_crtdbg_flag_ = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);\n    // Set heap allocation block type to _IGNORE_BLOCK so that MS debug CRT\n    // doesn't report mem leak if there's no matching deallocation.\n    (void)_CrtSetDbgFlag(old_crtdbg_flag_ & ~_CRTDBG_ALLOC_MEM_DF);\n  }\n\n  ~MemoryIsNotDeallocated() {\n    // Restore the original _CRTDBG_ALLOC_MEM_DF flag\n    (void)_CrtSetDbgFlag(old_crtdbg_flag_);\n  }\n\n private:\n  int old_crtdbg_flag_;\n\n  MemoryIsNotDeallocated(const MemoryIsNotDeallocated&) = delete;\n  MemoryIsNotDeallocated& operator=(const MemoryIsNotDeallocated&) = delete;\n};\n#endif  // _MSC_VER\n\n}  // namespace\n\n// Initializes owner_thread_id_ and critical_section_ in static mutexes.\nvoid Mutex::ThreadSafeLazyInit() {\n  // Dynamic mutexes are initialized in the constructor.\n  if (type_ == kStatic) {\n    switch (\n        ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {\n      case 0:\n        // If critical_section_init_phase_ was 0 before the exchange, we\n        // are the first to test it and need to perform the initialization.\n        owner_thread_id_ = 0;\n        {\n          // Use RAII to flag that following mem alloc is never deallocated.\n#ifdef _MSC_VER\n          MemoryIsNotDeallocated memory_is_not_deallocated;\n#endif  // _MSC_VER\n          critical_section_ = new CRITICAL_SECTION;\n        }\n        ::InitializeCriticalSection(critical_section_);\n        // Updates the critical_section_init_phase_ to 2 to signal\n        // initialization complete.\n        GTEST_CHECK_(::InterlockedCompareExchange(&critical_section_init_phase_,\n                                                  2L, 1L) == 1L);\n        break;\n      case 1:\n        // Somebody else is already initializing the mutex; spin until they\n        // are done.\n        while (::InterlockedCompareExchange(&critical_section_init_phase_, 2L,\n                                            2L) != 2L) {\n          // Possibly yields the rest of the thread's time slice to other\n          // threads.\n          ::Sleep(0);\n        }\n        break;\n\n      case 2:\n        break;  // The mutex is already initialized and ready for use.\n\n      default:\n        GTEST_CHECK_(false)\n            << \"Unexpected value of critical_section_init_phase_ \"\n            << \"while initializing a static mutex.\";\n    }\n  }\n}\n\nnamespace {\n\nclass ThreadWithParamSupport : public ThreadWithParamBase {\n public:\n  static HANDLE CreateThread(Runnable* runnable,\n                             Notification* thread_can_start) {\n    ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);\n    DWORD thread_id;\n    HANDLE thread_handle = ::CreateThread(\n        nullptr,  // Default security.\n        0,        // Default stack size.\n        &ThreadWithParamSupport::ThreadMain,\n        param,        // Parameter to ThreadMainStatic\n        0x0,          // Default creation flags.\n        &thread_id);  // Need a valid pointer for the call to work under Win98.\n    GTEST_CHECK_(thread_handle != nullptr)\n        << \"CreateThread failed with error \" << ::GetLastError() << \".\";\n    if (thread_handle == nullptr) {\n      delete param;\n    }\n    return thread_handle;\n  }\n\n private:\n  struct ThreadMainParam {\n    ThreadMainParam(Runnable* runnable, Notification* thread_can_start)\n        : runnable_(runnable), thread_can_start_(thread_can_start) {}\n    std::unique_ptr<Runnable> runnable_;\n    // Does not own.\n    Notification* thread_can_start_;\n  };\n\n  static DWORD WINAPI ThreadMain(void* ptr) {\n    // Transfers ownership.\n    std::unique_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));\n    if (param->thread_can_start_ != nullptr)\n      param->thread_can_start_->WaitForNotification();\n    param->runnable_->Run();\n    return 0;\n  }\n\n  // Prohibit instantiation.\n  ThreadWithParamSupport();\n\n  ThreadWithParamSupport(const ThreadWithParamSupport&) = delete;\n  ThreadWithParamSupport& operator=(const ThreadWithParamSupport&) = delete;\n};\n\n}  // namespace\n\nThreadWithParamBase::ThreadWithParamBase(Runnable* runnable,\n                                         Notification* thread_can_start)\n    : thread_(\n          ThreadWithParamSupport::CreateThread(runnable, thread_can_start)) {}\n\nThreadWithParamBase::~ThreadWithParamBase() { Join(); }\n\nvoid ThreadWithParamBase::Join() {\n  GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)\n      << \"Failed to join the thread with error \" << ::GetLastError() << \".\";\n}\n\n// Maps a thread to a set of ThreadIdToThreadLocals that have values\n// instantiated on that thread and notifies them when the thread exits.  A\n// ThreadLocal instance is expected to persist until all threads it has\n// values on have terminated.\nclass ThreadLocalRegistryImpl {\n public:\n  // Registers thread_local_instance as having value on the current thread.\n  // Returns a value that can be used to identify the thread from other threads.\n  static ThreadLocalValueHolderBase* GetValueOnCurrentThread(\n      const ThreadLocalBase* thread_local_instance) {\n#ifdef _MSC_VER\n    MemoryIsNotDeallocated memory_is_not_deallocated;\n#endif  // _MSC_VER\n    DWORD current_thread = ::GetCurrentThreadId();\n    MutexLock lock(&mutex_);\n    ThreadIdToThreadLocals* const thread_to_thread_locals =\n        GetThreadLocalsMapLocked();\n    ThreadIdToThreadLocals::iterator thread_local_pos =\n        thread_to_thread_locals->find(current_thread);\n    if (thread_local_pos == thread_to_thread_locals->end()) {\n      thread_local_pos =\n          thread_to_thread_locals\n              ->insert(std::make_pair(current_thread, ThreadLocalValues()))\n              .first;\n      StartWatcherThreadFor(current_thread);\n    }\n    ThreadLocalValues& thread_local_values = thread_local_pos->second;\n    ThreadLocalValues::iterator value_pos =\n        thread_local_values.find(thread_local_instance);\n    if (value_pos == thread_local_values.end()) {\n      value_pos =\n          thread_local_values\n              .insert(std::make_pair(\n                  thread_local_instance,\n                  std::shared_ptr<ThreadLocalValueHolderBase>(\n                      thread_local_instance->NewValueForCurrentThread())))\n              .first;\n    }\n    return value_pos->second.get();\n  }\n\n  static void OnThreadLocalDestroyed(\n      const ThreadLocalBase* thread_local_instance) {\n    std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;\n    // Clean up the ThreadLocalValues data structure while holding the lock, but\n    // defer the destruction of the ThreadLocalValueHolderBases.\n    {\n      MutexLock lock(&mutex_);\n      ThreadIdToThreadLocals* const thread_to_thread_locals =\n          GetThreadLocalsMapLocked();\n      for (ThreadIdToThreadLocals::iterator it =\n               thread_to_thread_locals->begin();\n           it != thread_to_thread_locals->end(); ++it) {\n        ThreadLocalValues& thread_local_values = it->second;\n        ThreadLocalValues::iterator value_pos =\n            thread_local_values.find(thread_local_instance);\n        if (value_pos != thread_local_values.end()) {\n          value_holders.push_back(value_pos->second);\n          thread_local_values.erase(value_pos);\n          // This 'if' can only be successful at most once, so theoretically we\n          // could break out of the loop here, but we don't bother doing so.\n        }\n      }\n    }\n    // Outside the lock, let the destructor for 'value_holders' deallocate the\n    // ThreadLocalValueHolderBases.\n  }\n\n  static void OnThreadExit(DWORD thread_id) {\n    GTEST_CHECK_(thread_id != 0) << ::GetLastError();\n    std::vector<std::shared_ptr<ThreadLocalValueHolderBase> > value_holders;\n    // Clean up the ThreadIdToThreadLocals data structure while holding the\n    // lock, but defer the destruction of the ThreadLocalValueHolderBases.\n    {\n      MutexLock lock(&mutex_);\n      ThreadIdToThreadLocals* const thread_to_thread_locals =\n          GetThreadLocalsMapLocked();\n      ThreadIdToThreadLocals::iterator thread_local_pos =\n          thread_to_thread_locals->find(thread_id);\n      if (thread_local_pos != thread_to_thread_locals->end()) {\n        ThreadLocalValues& thread_local_values = thread_local_pos->second;\n        for (ThreadLocalValues::iterator value_pos =\n                 thread_local_values.begin();\n             value_pos != thread_local_values.end(); ++value_pos) {\n          value_holders.push_back(value_pos->second);\n        }\n        thread_to_thread_locals->erase(thread_local_pos);\n      }\n    }\n    // Outside the lock, let the destructor for 'value_holders' deallocate the\n    // ThreadLocalValueHolderBases.\n  }\n\n private:\n  // In a particular thread, maps a ThreadLocal object to its value.\n  typedef std::map<const ThreadLocalBase*,\n                   std::shared_ptr<ThreadLocalValueHolderBase> >\n      ThreadLocalValues;\n  // Stores all ThreadIdToThreadLocals having values in a thread, indexed by\n  // thread's ID.\n  typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;\n\n  // Holds the thread id and thread handle that we pass from\n  // StartWatcherThreadFor to WatcherThreadFunc.\n  typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;\n\n  static void StartWatcherThreadFor(DWORD thread_id) {\n    // The returned handle will be kept in thread_map and closed by\n    // watcher_thread in WatcherThreadFunc.\n    HANDLE thread =\n        ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, FALSE, thread_id);\n    GTEST_CHECK_(thread != nullptr);\n    // We need to pass a valid thread ID pointer into CreateThread for it\n    // to work correctly under Win98.\n    DWORD watcher_thread_id;\n    HANDLE watcher_thread = ::CreateThread(\n        nullptr,  // Default security.\n        0,        // Default stack size\n        &ThreadLocalRegistryImpl::WatcherThreadFunc,\n        reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),\n        CREATE_SUSPENDED, &watcher_thread_id);\n    GTEST_CHECK_(watcher_thread != nullptr)\n        << \"CreateThread failed with error \" << ::GetLastError() << \".\";\n    // Give the watcher thread the same priority as ours to avoid being\n    // blocked by it.\n    ::SetThreadPriority(watcher_thread,\n                        ::GetThreadPriority(::GetCurrentThread()));\n    ::ResumeThread(watcher_thread);\n    ::CloseHandle(watcher_thread);\n  }\n\n  // Monitors exit from a given thread and notifies those\n  // ThreadIdToThreadLocals about thread termination.\n  static DWORD WINAPI WatcherThreadFunc(LPVOID param) {\n    const ThreadIdAndHandle* tah =\n        reinterpret_cast<const ThreadIdAndHandle*>(param);\n    GTEST_CHECK_(::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);\n    OnThreadExit(tah->first);\n    ::CloseHandle(tah->second);\n    delete tah;\n    return 0;\n  }\n\n  // Returns map of thread local instances.\n  static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {\n    mutex_.AssertHeld();\n#ifdef _MSC_VER\n    MemoryIsNotDeallocated memory_is_not_deallocated;\n#endif  // _MSC_VER\n    static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals();\n    return map;\n  }\n\n  // Protects access to GetThreadLocalsMapLocked() and its return value.\n  static Mutex mutex_;\n  // Protects access to GetThreadMapLocked() and its return value.\n  static Mutex thread_map_mutex_;\n};\n\nMutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);  // NOLINT\nMutex ThreadLocalRegistryImpl::thread_map_mutex_(\n    Mutex::kStaticMutex);  // NOLINT\n\nThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(\n    const ThreadLocalBase* thread_local_instance) {\n  return ThreadLocalRegistryImpl::GetValueOnCurrentThread(\n      thread_local_instance);\n}\n\nvoid ThreadLocalRegistry::OnThreadLocalDestroyed(\n    const ThreadLocalBase* thread_local_instance) {\n  ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);\n}\n\n#endif  // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS\n\n#if GTEST_USES_POSIX_RE\n\n// Implements RE.  Currently only needed for death tests.\n\nRE::~RE() {\n  if (is_valid_) {\n    // regfree'ing an invalid regex might crash because the content\n    // of the regex is undefined. Since the regex's are essentially\n    // the same, one cannot be valid (or invalid) without the other\n    // being so too.\n    regfree(&partial_regex_);\n    regfree(&full_regex_);\n  }\n  free(const_cast<char*>(pattern_));\n}\n\n// Returns true if and only if regular expression re matches the entire str.\nbool RE::FullMatch(const char* str, const RE& re) {\n  if (!re.is_valid_) return false;\n\n  regmatch_t match;\n  return regexec(&re.full_regex_, str, 1, &match, 0) == 0;\n}\n\n// Returns true if and only if regular expression re matches a substring of\n// str (including str itself).\nbool RE::PartialMatch(const char* str, const RE& re) {\n  if (!re.is_valid_) return false;\n\n  regmatch_t match;\n  return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;\n}\n\n// Initializes an RE from its string representation.\nvoid RE::Init(const char* regex) {\n  pattern_ = posix::StrDup(regex);\n\n  // Reserves enough bytes to hold the regular expression used for a\n  // full match.\n  const size_t full_regex_len = strlen(regex) + 10;\n  char* const full_pattern = new char[full_regex_len];\n\n  snprintf(full_pattern, full_regex_len, \"^(%s)$\", regex);\n  is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;\n  // We want to call regcomp(&partial_regex_, ...) even if the\n  // previous expression returns false.  Otherwise partial_regex_ may\n  // not be properly initialized can may cause trouble when it's\n  // freed.\n  //\n  // Some implementation of POSIX regex (e.g. on at least some\n  // versions of Cygwin) doesn't accept the empty string as a valid\n  // regex.  We change it to an equivalent form \"()\" to be safe.\n  if (is_valid_) {\n    const char* const partial_regex = (*regex == '\\0') ? \"()\" : regex;\n    is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;\n  }\n  EXPECT_TRUE(is_valid_)\n      << \"Regular expression \\\"\" << regex\n      << \"\\\" is not a valid POSIX Extended regular expression.\";\n\n  delete[] full_pattern;\n}\n\n#elif GTEST_USES_SIMPLE_RE\n\n// Returns true if and only if ch appears anywhere in str (excluding the\n// terminating '\\0' character).\nbool IsInSet(char ch, const char* str) {\n  return ch != '\\0' && strchr(str, ch) != nullptr;\n}\n\n// Returns true if and only if ch belongs to the given classification.\n// Unlike similar functions in <ctype.h>, these aren't affected by the\n// current locale.\nbool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }\nbool IsAsciiPunct(char ch) {\n  return IsInSet(ch, \"^-!\\\"#$%&'()*+,./:;<=>?@[\\\\]_`{|}~\");\n}\nbool IsRepeat(char ch) { return IsInSet(ch, \"?*+\"); }\nbool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, \" \\f\\n\\r\\t\\v\"); }\nbool IsAsciiWordChar(char ch) {\n  return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||\n         ('0' <= ch && ch <= '9') || ch == '_';\n}\n\n// Returns true if and only if \"\\\\c\" is a supported escape sequence.\nbool IsValidEscape(char c) {\n  return (IsAsciiPunct(c) || IsInSet(c, \"dDfnrsStvwW\"));\n}\n\n// Returns true if and only if the given atom (specified by escaped and\n// pattern) matches ch.  The result is undefined if the atom is invalid.\nbool AtomMatchesChar(bool escaped, char pattern_char, char ch) {\n  if (escaped) {  // \"\\\\p\" where p is pattern_char.\n    switch (pattern_char) {\n      case 'd':\n        return IsAsciiDigit(ch);\n      case 'D':\n        return !IsAsciiDigit(ch);\n      case 'f':\n        return ch == '\\f';\n      case 'n':\n        return ch == '\\n';\n      case 'r':\n        return ch == '\\r';\n      case 's':\n        return IsAsciiWhiteSpace(ch);\n      case 'S':\n        return !IsAsciiWhiteSpace(ch);\n      case 't':\n        return ch == '\\t';\n      case 'v':\n        return ch == '\\v';\n      case 'w':\n        return IsAsciiWordChar(ch);\n      case 'W':\n        return !IsAsciiWordChar(ch);\n    }\n    return IsAsciiPunct(pattern_char) && pattern_char == ch;\n  }\n\n  return (pattern_char == '.' && ch != '\\n') || pattern_char == ch;\n}\n\n// Helper function used by ValidateRegex() to format error messages.\nstatic std::string FormatRegexSyntaxError(const char* regex, int index) {\n  return (Message() << \"Syntax error at index \" << index\n                    << \" in simple regular expression \\\"\" << regex << \"\\\": \")\n      .GetString();\n}\n\n// Generates non-fatal failures and returns false if regex is invalid;\n// otherwise returns true.\nbool ValidateRegex(const char* regex) {\n  if (regex == nullptr) {\n    ADD_FAILURE() << \"NULL is not a valid simple regular expression.\";\n    return false;\n  }\n\n  bool is_valid = true;\n\n  // True if and only if ?, *, or + can follow the previous atom.\n  bool prev_repeatable = false;\n  for (int i = 0; regex[i]; i++) {\n    if (regex[i] == '\\\\') {  // An escape sequence\n      i++;\n      if (regex[i] == '\\0') {\n        ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)\n                      << \"'\\\\' cannot appear at the end.\";\n        return false;\n      }\n\n      if (!IsValidEscape(regex[i])) {\n        ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)\n                      << \"invalid escape sequence \\\"\\\\\" << regex[i] << \"\\\".\";\n        is_valid = false;\n      }\n      prev_repeatable = true;\n    } else {  // Not an escape sequence.\n      const char ch = regex[i];\n\n      if (ch == '^' && i > 0) {\n        ADD_FAILURE() << FormatRegexSyntaxError(regex, i)\n                      << \"'^' can only appear at the beginning.\";\n        is_valid = false;\n      } else if (ch == '$' && regex[i + 1] != '\\0') {\n        ADD_FAILURE() << FormatRegexSyntaxError(regex, i)\n                      << \"'$' can only appear at the end.\";\n        is_valid = false;\n      } else if (IsInSet(ch, \"()[]{}|\")) {\n        ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << \"'\" << ch\n                      << \"' is unsupported.\";\n        is_valid = false;\n      } else if (IsRepeat(ch) && !prev_repeatable) {\n        ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << \"'\" << ch\n                      << \"' can only follow a repeatable token.\";\n        is_valid = false;\n      }\n\n      prev_repeatable = !IsInSet(ch, \"^$?*+\");\n    }\n  }\n\n  return is_valid;\n}\n\n// Matches a repeated regex atom followed by a valid simple regular\n// expression.  The regex atom is defined as c if escaped is false,\n// or \\c otherwise.  repeat is the repetition meta character (?, *,\n// or +).  The behavior is undefined if str contains too many\n// characters to be indexable by size_t, in which case the test will\n// probably time out anyway.  We are fine with this limitation as\n// std::string has it too.\nbool MatchRepetitionAndRegexAtHead(bool escaped, char c, char repeat,\n                                   const char* regex, const char* str) {\n  const size_t min_count = (repeat == '+') ? 1 : 0;\n  const size_t max_count = (repeat == '?') ? 1 : static_cast<size_t>(-1) - 1;\n  // We cannot call numeric_limits::max() as it conflicts with the\n  // max() macro on Windows.\n\n  for (size_t i = 0; i <= max_count; ++i) {\n    // We know that the atom matches each of the first i characters in str.\n    if (i >= min_count && MatchRegexAtHead(regex, str + i)) {\n      // We have enough matches at the head, and the tail matches too.\n      // Since we only care about *whether* the pattern matches str\n      // (as opposed to *how* it matches), there is no need to find a\n      // greedy match.\n      return true;\n    }\n    if (str[i] == '\\0' || !AtomMatchesChar(escaped, c, str[i])) return false;\n  }\n  return false;\n}\n\n// Returns true if and only if regex matches a prefix of str. regex must\n// be a valid simple regular expression and not start with \"^\", or the\n// result is undefined.\nbool MatchRegexAtHead(const char* regex, const char* str) {\n  if (*regex == '\\0')  // An empty regex matches a prefix of anything.\n    return true;\n\n  // \"$\" only matches the end of a string.  Note that regex being\n  // valid guarantees that there's nothing after \"$\" in it.\n  if (*regex == '$') return *str == '\\0';\n\n  // Is the first thing in regex an escape sequence?\n  const bool escaped = *regex == '\\\\';\n  if (escaped) ++regex;\n  if (IsRepeat(regex[1])) {\n    // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so\n    // here's an indirect recursion.  It terminates as the regex gets\n    // shorter in each recursion.\n    return MatchRepetitionAndRegexAtHead(escaped, regex[0], regex[1], regex + 2,\n                                         str);\n  } else {\n    // regex isn't empty, isn't \"$\", and doesn't start with a\n    // repetition.  We match the first atom of regex with the first\n    // character of str and recurse.\n    return (*str != '\\0') && AtomMatchesChar(escaped, *regex, *str) &&\n           MatchRegexAtHead(regex + 1, str + 1);\n  }\n}\n\n// Returns true if and only if regex matches any substring of str.  regex must\n// be a valid simple regular expression, or the result is undefined.\n//\n// The algorithm is recursive, but the recursion depth doesn't exceed\n// the regex length, so we won't need to worry about running out of\n// stack space normally.  In rare cases the time complexity can be\n// exponential with respect to the regex length + the string length,\n// but usually it's must faster (often close to linear).\nbool MatchRegexAnywhere(const char* regex, const char* str) {\n  if (regex == nullptr || str == nullptr) return false;\n\n  if (*regex == '^') return MatchRegexAtHead(regex + 1, str);\n\n  // A successful match can be anywhere in str.\n  do {\n    if (MatchRegexAtHead(regex, str)) return true;\n  } while (*str++ != '\\0');\n  return false;\n}\n\n// Implements the RE class.\n\nRE::~RE() {\n  free(const_cast<char*>(pattern_));\n  free(const_cast<char*>(full_pattern_));\n}\n\n// Returns true if and only if regular expression re matches the entire str.\nbool RE::FullMatch(const char* str, const RE& re) {\n  return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);\n}\n\n// Returns true if and only if regular expression re matches a substring of\n// str (including str itself).\nbool RE::PartialMatch(const char* str, const RE& re) {\n  return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);\n}\n\n// Initializes an RE from its string representation.\nvoid RE::Init(const char* regex) {\n  pattern_ = full_pattern_ = nullptr;\n  if (regex != nullptr) {\n    pattern_ = posix::StrDup(regex);\n  }\n\n  is_valid_ = ValidateRegex(regex);\n  if (!is_valid_) {\n    // No need to calculate the full pattern when the regex is invalid.\n    return;\n  }\n\n  const size_t len = strlen(regex);\n  // Reserves enough bytes to hold the regular expression used for a\n  // full match: we need space to prepend a '^', append a '$', and\n  // terminate the string with '\\0'.\n  char* buffer = static_cast<char*>(malloc(len + 3));\n  full_pattern_ = buffer;\n\n  if (*regex != '^')\n    *buffer++ = '^';  // Makes sure full_pattern_ starts with '^'.\n\n  // We don't use snprintf or strncpy, as they trigger a warning when\n  // compiled with VC++ 8.0.\n  memcpy(buffer, regex, len);\n  buffer += len;\n\n  if (len == 0 || regex[len - 1] != '$')\n    *buffer++ = '$';  // Makes sure full_pattern_ ends with '$'.\n\n  *buffer = '\\0';\n}\n\n#endif  // GTEST_USES_POSIX_RE\n\nconst char kUnknownFile[] = \"unknown file\";\n\n// Formats a source file path and a line number as they would appear\n// in an error message from the compiler used to compile this code.\nGTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {\n  const std::string file_name(file == nullptr ? kUnknownFile : file);\n\n  if (line < 0) {\n    return file_name + \":\";\n  }\n#ifdef _MSC_VER\n  return file_name + \"(\" + StreamableToString(line) + \"):\";\n#else\n  return file_name + \":\" + StreamableToString(line) + \":\";\n#endif  // _MSC_VER\n}\n\n// Formats a file location for compiler-independent XML output.\n// Although this function is not platform dependent, we put it next to\n// FormatFileLocation in order to contrast the two functions.\n// Note that FormatCompilerIndependentFileLocation() does NOT append colon\n// to the file location it produces, unlike FormatFileLocation().\nGTEST_API_ ::std::string FormatCompilerIndependentFileLocation(const char* file,\n                                                               int line) {\n  const std::string file_name(file == nullptr ? kUnknownFile : file);\n\n  if (line < 0)\n    return file_name;\n  else\n    return file_name + \":\" + StreamableToString(line);\n}\n\nGTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)\n    : severity_(severity) {\n  const char* const marker = severity == GTEST_INFO      ? \"[  INFO ]\"\n                             : severity == GTEST_WARNING ? \"[WARNING]\"\n                             : severity == GTEST_ERROR   ? \"[ ERROR ]\"\n                                                         : \"[ FATAL ]\";\n  GetStream() << ::std::endl\n              << marker << \" \" << FormatFileLocation(file, line).c_str()\n              << \": \";\n}\n\n// Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.\nGTestLog::~GTestLog() {\n  GetStream() << ::std::endl;\n  if (severity_ == GTEST_FATAL) {\n    fflush(stderr);\n    posix::Abort();\n  }\n}\n\n// Disable Microsoft deprecation warnings for POSIX functions called from\n// this class (creat, dup, dup2, and close)\nGTEST_DISABLE_MSC_DEPRECATED_PUSH_()\n\n#if GTEST_HAS_STREAM_REDIRECTION\n\n// Object that captures an output stream (stdout/stderr).\nclass CapturedStream {\n public:\n  // The ctor redirects the stream to a temporary file.\n  explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {\n#if GTEST_OS_WINDOWS\n    char temp_dir_path[MAX_PATH + 1] = {'\\0'};   // NOLINT\n    char temp_file_path[MAX_PATH + 1] = {'\\0'};  // NOLINT\n\n    ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);\n    const UINT success = ::GetTempFileNameA(temp_dir_path, \"gtest_redir\",\n                                            0,  // Generate unique file name.\n                                            temp_file_path);\n    GTEST_CHECK_(success != 0)\n        << \"Unable to create a temporary file in \" << temp_dir_path;\n    const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);\n    GTEST_CHECK_(captured_fd != -1)\n        << \"Unable to open temporary file \" << temp_file_path;\n    filename_ = temp_file_path;\n#else\n    // There's no guarantee that a test has write access to the current\n    // directory, so we create the temporary file in a temporary directory.\n    std::string name_template;\n\n#if GTEST_OS_LINUX_ANDROID\n    // Note: Android applications are expected to call the framework's\n    // Context.getExternalStorageDirectory() method through JNI to get\n    // the location of the world-writable SD Card directory. However,\n    // this requires a Context handle, which cannot be retrieved\n    // globally from native code. Doing so also precludes running the\n    // code as part of a regular standalone executable, which doesn't\n    // run in a Dalvik process (e.g. when running it through 'adb shell').\n    //\n    // The location /data/local/tmp is directly accessible from native code.\n    // '/sdcard' and other variants cannot be relied on, as they are not\n    // guaranteed to be mounted, or may have a delay in mounting.\n    name_template = \"/data/local/tmp/\";\n#elif GTEST_OS_IOS\n    char user_temp_dir[PATH_MAX + 1];\n\n    // Documented alternative to NSTemporaryDirectory() (for obtaining creating\n    // a temporary directory) at\n    // https://developer.apple.com/library/archive/documentation/Security/Conceptual/SecureCodingGuide/Articles/RaceConditions.html#//apple_ref/doc/uid/TP40002585-SW10\n    //\n    // _CS_DARWIN_USER_TEMP_DIR (as well as _CS_DARWIN_USER_CACHE_DIR) is not\n    // documented in the confstr() man page at\n    // https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/confstr.3.html#//apple_ref/doc/man/3/confstr\n    // but are still available, according to the WebKit patches at\n    // https://trac.webkit.org/changeset/262004/webkit\n    // https://trac.webkit.org/changeset/263705/webkit\n    //\n    // The confstr() implementation falls back to getenv(\"TMPDIR\"). See\n    // https://opensource.apple.com/source/Libc/Libc-1439.100.3/gen/confstr.c.auto.html\n    ::confstr(_CS_DARWIN_USER_TEMP_DIR, user_temp_dir, sizeof(user_temp_dir));\n\n    name_template = user_temp_dir;\n    if (name_template.back() != GTEST_PATH_SEP_[0])\n      name_template.push_back(GTEST_PATH_SEP_[0]);\n#else\n    name_template = \"/tmp/\";\n#endif\n    name_template.append(\"gtest_captured_stream.XXXXXX\");\n\n    // mkstemp() modifies the string bytes in place, and does not go beyond the\n    // string's length. This results in well-defined behavior in C++17.\n    //\n    // The const_cast is needed below C++17. The constraints on std::string\n    // implementations in C++11 and above make assumption behind the const_cast\n    // fairly safe.\n    const int captured_fd = ::mkstemp(const_cast<char*>(name_template.data()));\n    if (captured_fd == -1) {\n      GTEST_LOG_(WARNING)\n          << \"Failed to create tmp file \" << name_template\n          << \" for test; does the test have access to the /tmp directory?\";\n    }\n    filename_ = std::move(name_template);\n#endif  // GTEST_OS_WINDOWS\n    fflush(nullptr);\n    dup2(captured_fd, fd_);\n    close(captured_fd);\n  }\n\n  ~CapturedStream() { remove(filename_.c_str()); }\n\n  std::string GetCapturedString() {\n    if (uncaptured_fd_ != -1) {\n      // Restores the original stream.\n      fflush(nullptr);\n      dup2(uncaptured_fd_, fd_);\n      close(uncaptured_fd_);\n      uncaptured_fd_ = -1;\n    }\n\n    FILE* const file = posix::FOpen(filename_.c_str(), \"r\");\n    if (file == nullptr) {\n      GTEST_LOG_(FATAL) << \"Failed to open tmp file \" << filename_\n                        << \" for capturing stream.\";\n    }\n    const std::string content = ReadEntireFile(file);\n    posix::FClose(file);\n    return content;\n  }\n\n private:\n  const int fd_;  // A stream to capture.\n  int uncaptured_fd_;\n  // Name of the temporary file holding the stderr output.\n  ::std::string filename_;\n\n  CapturedStream(const CapturedStream&) = delete;\n  CapturedStream& operator=(const CapturedStream&) = delete;\n};\n\nGTEST_DISABLE_MSC_DEPRECATED_POP_()\n\nstatic CapturedStream* g_captured_stderr = nullptr;\nstatic CapturedStream* g_captured_stdout = nullptr;\n\n// Starts capturing an output stream (stdout/stderr).\nstatic void CaptureStream(int fd, const char* stream_name,\n                          CapturedStream** stream) {\n  if (*stream != nullptr) {\n    GTEST_LOG_(FATAL) << \"Only one \" << stream_name\n                      << \" capturer can exist at a time.\";\n  }\n  *stream = new CapturedStream(fd);\n}\n\n// Stops capturing the output stream and returns the captured string.\nstatic std::string GetCapturedStream(CapturedStream** captured_stream) {\n  const std::string content = (*captured_stream)->GetCapturedString();\n\n  delete *captured_stream;\n  *captured_stream = nullptr;\n\n  return content;\n}\n\n#if defined(_MSC_VER) || defined(__BORLANDC__)\n// MSVC and C++Builder do not provide a definition of STDERR_FILENO.\nconst int kStdOutFileno = 1;\nconst int kStdErrFileno = 2;\n#else\nconst int kStdOutFileno = STDOUT_FILENO;\nconst int kStdErrFileno = STDERR_FILENO;\n#endif  // defined(_MSC_VER) || defined(__BORLANDC__)\n\n// Starts capturing stdout.\nvoid CaptureStdout() {\n  CaptureStream(kStdOutFileno, \"stdout\", &g_captured_stdout);\n}\n\n// Starts capturing stderr.\nvoid CaptureStderr() {\n  CaptureStream(kStdErrFileno, \"stderr\", &g_captured_stderr);\n}\n\n// Stops capturing stdout and returns the captured string.\nstd::string GetCapturedStdout() {\n  return GetCapturedStream(&g_captured_stdout);\n}\n\n// Stops capturing stderr and returns the captured string.\nstd::string GetCapturedStderr() {\n  return GetCapturedStream(&g_captured_stderr);\n}\n\n#endif  // GTEST_HAS_STREAM_REDIRECTION\n\nsize_t GetFileSize(FILE* file) {\n  fseek(file, 0, SEEK_END);\n  return static_cast<size_t>(ftell(file));\n}\n\nstd::string ReadEntireFile(FILE* file) {\n  const size_t file_size = GetFileSize(file);\n  char* const buffer = new char[file_size];\n\n  size_t bytes_last_read = 0;  // # of bytes read in the last fread()\n  size_t bytes_read = 0;       // # of bytes read so far\n\n  fseek(file, 0, SEEK_SET);\n\n  // Keeps reading the file until we cannot read further or the\n  // pre-determined file size is reached.\n  do {\n    bytes_last_read =\n        fread(buffer + bytes_read, 1, file_size - bytes_read, file);\n    bytes_read += bytes_last_read;\n  } while (bytes_last_read > 0 && bytes_read < file_size);\n\n  const std::string content(buffer, bytes_read);\n  delete[] buffer;\n\n  return content;\n}\n\n#if GTEST_HAS_DEATH_TEST\nstatic const std::vector<std::string>* g_injected_test_argvs =\n    nullptr;  // Owned.\n\nstd::vector<std::string> GetInjectableArgvs() {\n  if (g_injected_test_argvs != nullptr) {\n    return *g_injected_test_argvs;\n  }\n  return GetArgvs();\n}\n\nvoid SetInjectableArgvs(const std::vector<std::string>* new_argvs) {\n  if (g_injected_test_argvs != new_argvs) delete g_injected_test_argvs;\n  g_injected_test_argvs = new_argvs;\n}\n\nvoid SetInjectableArgvs(const std::vector<std::string>& new_argvs) {\n  SetInjectableArgvs(\n      new std::vector<std::string>(new_argvs.begin(), new_argvs.end()));\n}\n\nvoid ClearInjectableArgvs() {\n  delete g_injected_test_argvs;\n  g_injected_test_argvs = nullptr;\n}\n#endif  // GTEST_HAS_DEATH_TEST\n\n#if GTEST_OS_WINDOWS_MOBILE\nnamespace posix {\nvoid Abort() {\n  DebugBreak();\n  TerminateProcess(GetCurrentProcess(), 1);\n}\n}  // namespace posix\n#endif  // GTEST_OS_WINDOWS_MOBILE\n\n// Returns the name of the environment variable corresponding to the\n// given flag.  For example, FlagToEnvVar(\"foo\") will return\n// \"GTEST_FOO\" in the open-source version.\nstatic std::string FlagToEnvVar(const char* flag) {\n  const std::string full_flag =\n      (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();\n\n  Message env_var;\n  for (size_t i = 0; i != full_flag.length(); i++) {\n    env_var << ToUpper(full_flag.c_str()[i]);\n  }\n\n  return env_var.GetString();\n}\n\n// Parses 'str' for a 32-bit signed integer.  If successful, writes\n// the result to *value and returns true; otherwise leaves *value\n// unchanged and returns false.\nbool ParseInt32(const Message& src_text, const char* str, int32_t* value) {\n  // Parses the environment variable as a decimal integer.\n  char* end = nullptr;\n  const long long_value = strtol(str, &end, 10);  // NOLINT\n\n  // Has strtol() consumed all characters in the string?\n  if (*end != '\\0') {\n    // No - an invalid character was encountered.\n    Message msg;\n    msg << \"WARNING: \" << src_text\n        << \" is expected to be a 32-bit integer, but actually\"\n        << \" has value \\\"\" << str << \"\\\".\\n\";\n    printf(\"%s\", msg.GetString().c_str());\n    fflush(stdout);\n    return false;\n  }\n\n  // Is the parsed value in the range of an int32_t?\n  const auto result = static_cast<int32_t>(long_value);\n  if (long_value == LONG_MAX || long_value == LONG_MIN ||\n      // The parsed value overflows as a long.  (strtol() returns\n      // LONG_MAX or LONG_MIN when the input overflows.)\n      result != long_value\n      // The parsed value overflows as an int32_t.\n  ) {\n    Message msg;\n    msg << \"WARNING: \" << src_text\n        << \" is expected to be a 32-bit integer, but actually\"\n        << \" has value \" << str << \", which overflows.\\n\";\n    printf(\"%s\", msg.GetString().c_str());\n    fflush(stdout);\n    return false;\n  }\n\n  *value = result;\n  return true;\n}\n\n// Reads and returns the Boolean environment variable corresponding to\n// the given flag; if it's not set, returns default_value.\n//\n// The value is considered true if and only if it's not \"0\".\nbool BoolFromGTestEnv(const char* flag, bool default_value) {\n#if defined(GTEST_GET_BOOL_FROM_ENV_)\n  return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);\n#else\n  const std::string env_var = FlagToEnvVar(flag);\n  const char* const string_value = posix::GetEnv(env_var.c_str());\n  return string_value == nullptr ? default_value\n                                 : strcmp(string_value, \"0\") != 0;\n#endif  // defined(GTEST_GET_BOOL_FROM_ENV_)\n}\n\n// Reads and returns a 32-bit integer stored in the environment\n// variable corresponding to the given flag; if it isn't set or\n// doesn't represent a valid 32-bit integer, returns default_value.\nint32_t Int32FromGTestEnv(const char* flag, int32_t default_value) {\n#if defined(GTEST_GET_INT32_FROM_ENV_)\n  return GTEST_GET_INT32_FROM_ENV_(flag, default_value);\n#else\n  const std::string env_var = FlagToEnvVar(flag);\n  const char* const string_value = posix::GetEnv(env_var.c_str());\n  if (string_value == nullptr) {\n    // The environment variable is not set.\n    return default_value;\n  }\n\n  int32_t result = default_value;\n  if (!ParseInt32(Message() << \"Environment variable \" << env_var, string_value,\n                  &result)) {\n    printf(\"The default value %s is used.\\n\",\n           (Message() << default_value).GetString().c_str());\n    fflush(stdout);\n    return default_value;\n  }\n\n  return result;\n#endif  // defined(GTEST_GET_INT32_FROM_ENV_)\n}\n\n// As a special case for the 'output' flag, if GTEST_OUTPUT is not\n// set, we look for XML_OUTPUT_FILE, which is set by the Bazel build\n// system.  The value of XML_OUTPUT_FILE is a filename without the\n// \"xml:\" prefix of GTEST_OUTPUT.\n// Note that this is meant to be called at the call site so it does\n// not check that the flag is 'output'\n// In essence this checks an env variable called XML_OUTPUT_FILE\n// and if it is set we prepend \"xml:\" to its value, if it not set we return \"\"\nstd::string OutputFlagAlsoCheckEnvVar() {\n  std::string default_value_for_output_flag = \"\";\n  const char* xml_output_file_env = posix::GetEnv(\"XML_OUTPUT_FILE\");\n  if (nullptr != xml_output_file_env) {\n    default_value_for_output_flag = std::string(\"xml:\") + xml_output_file_env;\n  }\n  return default_value_for_output_flag;\n}\n\n// Reads and returns the string environment variable corresponding to\n// the given flag; if it's not set, returns default_value.\nconst char* StringFromGTestEnv(const char* flag, const char* default_value) {\n#if defined(GTEST_GET_STRING_FROM_ENV_)\n  return GTEST_GET_STRING_FROM_ENV_(flag, default_value);\n#else\n  const std::string env_var = FlagToEnvVar(flag);\n  const char* const value = posix::GetEnv(env_var.c_str());\n  return value == nullptr ? default_value : value;\n#endif  // defined(GTEST_GET_STRING_FROM_ENV_)\n}\n\n}  // namespace internal\n}  // namespace testing\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/src/gtest-printers.cc",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Test - The Google C++ Testing and Mocking Framework\n//\n// This file implements a universal value printer that can print a\n// value of any type T:\n//\n//   void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);\n//\n// It uses the << operator when possible, and prints the bytes in the\n// object otherwise.  A user can override its behavior for a class\n// type Foo by defining either operator<<(::std::ostream&, const Foo&)\n// or void PrintTo(const Foo&, ::std::ostream*) in the namespace that\n// defines Foo.\n\n#include \"gtest/gtest-printers.h\"\n\n#include <stdio.h>\n\n#include <cctype>\n#include <cstdint>\n#include <cwchar>\n#include <ostream>  // NOLINT\n#include <string>\n#include <type_traits>\n\n#include \"gtest/internal/gtest-port.h\"\n#include \"src/gtest-internal-inl.h\"\n\nnamespace testing {\n\nnamespace {\n\nusing ::std::ostream;\n\n// Prints a segment of bytes in the given object.\nGTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_\nGTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_\nGTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_\nGTEST_ATTRIBUTE_NO_SANITIZE_THREAD_\nvoid PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,\n                                size_t count, ostream* os) {\n  char text[5] = \"\";\n  for (size_t i = 0; i != count; i++) {\n    const size_t j = start + i;\n    if (i != 0) {\n      // Organizes the bytes into groups of 2 for easy parsing by\n      // human.\n      if ((j % 2) == 0)\n        *os << ' ';\n      else\n        *os << '-';\n    }\n    GTEST_SNPRINTF_(text, sizeof(text), \"%02X\", obj_bytes[j]);\n    *os << text;\n  }\n}\n\n// Prints the bytes in the given value to the given ostream.\nvoid PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,\n                              ostream* os) {\n  // Tells the user how big the object is.\n  *os << count << \"-byte object <\";\n\n  const size_t kThreshold = 132;\n  const size_t kChunkSize = 64;\n  // If the object size is bigger than kThreshold, we'll have to omit\n  // some details by printing only the first and the last kChunkSize\n  // bytes.\n  if (count < kThreshold) {\n    PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);\n  } else {\n    PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);\n    *os << \" ... \";\n    // Rounds up to 2-byte boundary.\n    const size_t resume_pos = (count - kChunkSize + 1) / 2 * 2;\n    PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);\n  }\n  *os << \">\";\n}\n\n// Helpers for widening a character to char32_t. Since the standard does not\n// specify if char / wchar_t is signed or unsigned, it is important to first\n// convert it to the unsigned type of the same width before widening it to\n// char32_t.\ntemplate <typename CharType>\nchar32_t ToChar32(CharType in) {\n  return static_cast<char32_t>(\n      static_cast<typename std::make_unsigned<CharType>::type>(in));\n}\n\n}  // namespace\n\nnamespace internal {\n\n// Delegates to PrintBytesInObjectToImpl() to print the bytes in the\n// given object.  The delegation simplifies the implementation, which\n// uses the << operator and thus is easier done outside of the\n// ::testing::internal namespace, which contains a << operator that\n// sometimes conflicts with the one in STL.\nvoid PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,\n                          ostream* os) {\n  PrintBytesInObjectToImpl(obj_bytes, count, os);\n}\n\n// Depending on the value of a char (or wchar_t), we print it in one\n// of three formats:\n//   - as is if it's a printable ASCII (e.g. 'a', '2', ' '),\n//   - as a hexadecimal escape sequence (e.g. '\\x7F'), or\n//   - as a special escape sequence (e.g. '\\r', '\\n').\nenum CharFormat { kAsIs, kHexEscape, kSpecialEscape };\n\n// Returns true if c is a printable ASCII character.  We test the\n// value of c directly instead of calling isprint(), which is buggy on\n// Windows Mobile.\ninline bool IsPrintableAscii(char32_t c) { return 0x20 <= c && c <= 0x7E; }\n\n// Prints c (of type char, char8_t, char16_t, char32_t, or wchar_t) as a\n// character literal without the quotes, escaping it when necessary; returns how\n// c was formatted.\ntemplate <typename Char>\nstatic CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {\n  const char32_t u_c = ToChar32(c);\n  switch (u_c) {\n    case L'\\0':\n      *os << \"\\\\0\";\n      break;\n    case L'\\'':\n      *os << \"\\\\'\";\n      break;\n    case L'\\\\':\n      *os << \"\\\\\\\\\";\n      break;\n    case L'\\a':\n      *os << \"\\\\a\";\n      break;\n    case L'\\b':\n      *os << \"\\\\b\";\n      break;\n    case L'\\f':\n      *os << \"\\\\f\";\n      break;\n    case L'\\n':\n      *os << \"\\\\n\";\n      break;\n    case L'\\r':\n      *os << \"\\\\r\";\n      break;\n    case L'\\t':\n      *os << \"\\\\t\";\n      break;\n    case L'\\v':\n      *os << \"\\\\v\";\n      break;\n    default:\n      if (IsPrintableAscii(u_c)) {\n        *os << static_cast<char>(c);\n        return kAsIs;\n      } else {\n        ostream::fmtflags flags = os->flags();\n        *os << \"\\\\x\" << std::hex << std::uppercase << static_cast<int>(u_c);\n        os->flags(flags);\n        return kHexEscape;\n      }\n  }\n  return kSpecialEscape;\n}\n\n// Prints a char32_t c as if it's part of a string literal, escaping it when\n// necessary; returns how c was formatted.\nstatic CharFormat PrintAsStringLiteralTo(char32_t c, ostream* os) {\n  switch (c) {\n    case L'\\'':\n      *os << \"'\";\n      return kAsIs;\n    case L'\"':\n      *os << \"\\\\\\\"\";\n      return kSpecialEscape;\n    default:\n      return PrintAsCharLiteralTo(c, os);\n  }\n}\n\nstatic const char* GetCharWidthPrefix(char) { return \"\"; }\n\nstatic const char* GetCharWidthPrefix(signed char) { return \"\"; }\n\nstatic const char* GetCharWidthPrefix(unsigned char) { return \"\"; }\n\n#ifdef __cpp_char8_t\nstatic const char* GetCharWidthPrefix(char8_t) { return \"u8\"; }\n#endif\n\nstatic const char* GetCharWidthPrefix(char16_t) { return \"u\"; }\n\nstatic const char* GetCharWidthPrefix(char32_t) { return \"U\"; }\n\nstatic const char* GetCharWidthPrefix(wchar_t) { return \"L\"; }\n\n// Prints a char c as if it's part of a string literal, escaping it when\n// necessary; returns how c was formatted.\nstatic CharFormat PrintAsStringLiteralTo(char c, ostream* os) {\n  return PrintAsStringLiteralTo(ToChar32(c), os);\n}\n\n#ifdef __cpp_char8_t\nstatic CharFormat PrintAsStringLiteralTo(char8_t c, ostream* os) {\n  return PrintAsStringLiteralTo(ToChar32(c), os);\n}\n#endif\n\nstatic CharFormat PrintAsStringLiteralTo(char16_t c, ostream* os) {\n  return PrintAsStringLiteralTo(ToChar32(c), os);\n}\n\nstatic CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {\n  return PrintAsStringLiteralTo(ToChar32(c), os);\n}\n\n// Prints a character c (of type char, char8_t, char16_t, char32_t, or wchar_t)\n// and its code. '\\0' is printed as \"'\\\\0'\", other unprintable characters are\n// also properly escaped using the standard C++ escape sequence.\ntemplate <typename Char>\nvoid PrintCharAndCodeTo(Char c, ostream* os) {\n  // First, print c as a literal in the most readable form we can find.\n  *os << GetCharWidthPrefix(c) << \"'\";\n  const CharFormat format = PrintAsCharLiteralTo(c, os);\n  *os << \"'\";\n\n  // To aid user debugging, we also print c's code in decimal, unless\n  // it's 0 (in which case c was printed as '\\\\0', making the code\n  // obvious).\n  if (c == 0) return;\n  *os << \" (\" << static_cast<int>(c);\n\n  // For more convenience, we print c's code again in hexadecimal,\n  // unless c was already printed in the form '\\x##' or the code is in\n  // [1, 9].\n  if (format == kHexEscape || (1 <= c && c <= 9)) {\n    // Do nothing.\n  } else {\n    *os << \", 0x\" << String::FormatHexInt(static_cast<int>(c));\n  }\n  *os << \")\";\n}\n\nvoid PrintTo(unsigned char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); }\nvoid PrintTo(signed char c, ::std::ostream* os) { PrintCharAndCodeTo(c, os); }\n\n// Prints a wchar_t as a symbol if it is printable or as its internal\n// code otherwise and also as its code.  L'\\0' is printed as \"L'\\\\0'\".\nvoid PrintTo(wchar_t wc, ostream* os) { PrintCharAndCodeTo(wc, os); }\n\n// TODO(dcheng): Consider making this delegate to PrintCharAndCodeTo() as well.\nvoid PrintTo(char32_t c, ::std::ostream* os) {\n  *os << std::hex << \"U+\" << std::uppercase << std::setfill('0') << std::setw(4)\n      << static_cast<uint32_t>(c);\n}\n\n// gcc/clang __{u,}int128_t\n#if defined(__SIZEOF_INT128__)\nvoid PrintTo(__uint128_t v, ::std::ostream* os) {\n  if (v == 0) {\n    *os << \"0\";\n    return;\n  }\n\n  // Buffer large enough for ceil(log10(2^128))==39 and the null terminator\n  char buf[40];\n  char* p = buf + sizeof(buf);\n\n  // Some configurations have a __uint128_t, but no support for built in\n  // division. Do manual long division instead.\n\n  uint64_t high = static_cast<uint64_t>(v >> 64);\n  uint64_t low = static_cast<uint64_t>(v);\n\n  *--p = 0;\n  while (high != 0 || low != 0) {\n    uint64_t high_mod = high % 10;\n    high = high / 10;\n    // This is the long division algorithm specialized for a divisor of 10 and\n    // only two elements.\n    // Notable values:\n    //   2^64 / 10 == 1844674407370955161\n    //   2^64 % 10 == 6\n    const uint64_t carry = 6 * high_mod + low % 10;\n    low = low / 10 + high_mod * 1844674407370955161 + carry / 10;\n\n    char digit = static_cast<char>(carry % 10);\n    *--p = '0' + digit;\n  }\n  *os << p;\n}\nvoid PrintTo(__int128_t v, ::std::ostream* os) {\n  __uint128_t uv = static_cast<__uint128_t>(v);\n  if (v < 0) {\n    *os << \"-\";\n    uv = -uv;\n  }\n  PrintTo(uv, os);\n}\n#endif  // __SIZEOF_INT128__\n\n// Prints the given array of characters to the ostream.  CharType must be either\n// char, char8_t, char16_t, char32_t, or wchar_t.\n// The array starts at begin, the length is len, it may include '\\0' characters\n// and may not be NUL-terminated.\ntemplate <typename CharType>\nGTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_\n    GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_\n        GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ static CharFormat\n        PrintCharsAsStringTo(const CharType* begin, size_t len, ostream* os) {\n  const char* const quote_prefix = GetCharWidthPrefix(*begin);\n  *os << quote_prefix << \"\\\"\";\n  bool is_previous_hex = false;\n  CharFormat print_format = kAsIs;\n  for (size_t index = 0; index < len; ++index) {\n    const CharType cur = begin[index];\n    if (is_previous_hex && IsXDigit(cur)) {\n      // Previous character is of '\\x..' form and this character can be\n      // interpreted as another hexadecimal digit in its number. Break string to\n      // disambiguate.\n      *os << \"\\\" \" << quote_prefix << \"\\\"\";\n    }\n    is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;\n    // Remember if any characters required hex escaping.\n    if (is_previous_hex) {\n      print_format = kHexEscape;\n    }\n  }\n  *os << \"\\\"\";\n  return print_format;\n}\n\n// Prints a (const) char/wchar_t array of 'len' elements, starting at address\n// 'begin'.  CharType must be either char or wchar_t.\ntemplate <typename CharType>\nGTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_\n    GTEST_ATTRIBUTE_NO_SANITIZE_HWADDRESS_\n        GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ static void\n        UniversalPrintCharArray(const CharType* begin, size_t len,\n                                ostream* os) {\n  // The code\n  //   const char kFoo[] = \"foo\";\n  // generates an array of 4, not 3, elements, with the last one being '\\0'.\n  //\n  // Therefore when printing a char array, we don't print the last element if\n  // it's '\\0', such that the output matches the string literal as it's\n  // written in the source code.\n  if (len > 0 && begin[len - 1] == '\\0') {\n    PrintCharsAsStringTo(begin, len - 1, os);\n    return;\n  }\n\n  // If, however, the last element in the array is not '\\0', e.g.\n  //    const char kFoo[] = { 'f', 'o', 'o' };\n  // we must print the entire array.  We also print a message to indicate\n  // that the array is not NUL-terminated.\n  PrintCharsAsStringTo(begin, len, os);\n  *os << \" (no terminating NUL)\";\n}\n\n// Prints a (const) char array of 'len' elements, starting at address 'begin'.\nvoid UniversalPrintArray(const char* begin, size_t len, ostream* os) {\n  UniversalPrintCharArray(begin, len, os);\n}\n\n#ifdef __cpp_char8_t\n// Prints a (const) char8_t array of 'len' elements, starting at address\n// 'begin'.\nvoid UniversalPrintArray(const char8_t* begin, size_t len, ostream* os) {\n  UniversalPrintCharArray(begin, len, os);\n}\n#endif\n\n// Prints a (const) char16_t array of 'len' elements, starting at address\n// 'begin'.\nvoid UniversalPrintArray(const char16_t* begin, size_t len, ostream* os) {\n  UniversalPrintCharArray(begin, len, os);\n}\n\n// Prints a (const) char32_t array of 'len' elements, starting at address\n// 'begin'.\nvoid UniversalPrintArray(const char32_t* begin, size_t len, ostream* os) {\n  UniversalPrintCharArray(begin, len, os);\n}\n\n// Prints a (const) wchar_t array of 'len' elements, starting at address\n// 'begin'.\nvoid UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {\n  UniversalPrintCharArray(begin, len, os);\n}\n\nnamespace {\n\n// Prints a null-terminated C-style string to the ostream.\ntemplate <typename Char>\nvoid PrintCStringTo(const Char* s, ostream* os) {\n  if (s == nullptr) {\n    *os << \"NULL\";\n  } else {\n    *os << ImplicitCast_<const void*>(s) << \" pointing to \";\n    PrintCharsAsStringTo(s, std::char_traits<Char>::length(s), os);\n  }\n}\n\n}  // anonymous namespace\n\nvoid PrintTo(const char* s, ostream* os) { PrintCStringTo(s, os); }\n\n#ifdef __cpp_char8_t\nvoid PrintTo(const char8_t* s, ostream* os) { PrintCStringTo(s, os); }\n#endif\n\nvoid PrintTo(const char16_t* s, ostream* os) { PrintCStringTo(s, os); }\n\nvoid PrintTo(const char32_t* s, ostream* os) { PrintCStringTo(s, os); }\n\n// MSVC compiler can be configured to define whar_t as a typedef\n// of unsigned short. Defining an overload for const wchar_t* in that case\n// would cause pointers to unsigned shorts be printed as wide strings,\n// possibly accessing more memory than intended and causing invalid\n// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when\n// wchar_t is implemented as a native type.\n#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)\n// Prints the given wide C string to the ostream.\nvoid PrintTo(const wchar_t* s, ostream* os) { PrintCStringTo(s, os); }\n#endif  // wchar_t is native\n\nnamespace {\n\nbool ContainsUnprintableControlCodes(const char* str, size_t length) {\n  const unsigned char* s = reinterpret_cast<const unsigned char*>(str);\n\n  for (size_t i = 0; i < length; i++) {\n    unsigned char ch = *s++;\n    if (std::iscntrl(ch)) {\n      switch (ch) {\n        case '\\t':\n        case '\\n':\n        case '\\r':\n          break;\n        default:\n          return true;\n      }\n    }\n  }\n  return false;\n}\n\nbool IsUTF8TrailByte(unsigned char t) { return 0x80 <= t && t <= 0xbf; }\n\nbool IsValidUTF8(const char* str, size_t length) {\n  const unsigned char* s = reinterpret_cast<const unsigned char*>(str);\n\n  for (size_t i = 0; i < length;) {\n    unsigned char lead = s[i++];\n\n    if (lead <= 0x7f) {\n      continue;  // single-byte character (ASCII) 0..7F\n    }\n    if (lead < 0xc2) {\n      return false;  // trail byte or non-shortest form\n    } else if (lead <= 0xdf && (i + 1) <= length && IsUTF8TrailByte(s[i])) {\n      ++i;  // 2-byte character\n    } else if (0xe0 <= lead && lead <= 0xef && (i + 2) <= length &&\n               IsUTF8TrailByte(s[i]) && IsUTF8TrailByte(s[i + 1]) &&\n               // check for non-shortest form and surrogate\n               (lead != 0xe0 || s[i] >= 0xa0) &&\n               (lead != 0xed || s[i] < 0xa0)) {\n      i += 2;  // 3-byte character\n    } else if (0xf0 <= lead && lead <= 0xf4 && (i + 3) <= length &&\n               IsUTF8TrailByte(s[i]) && IsUTF8TrailByte(s[i + 1]) &&\n               IsUTF8TrailByte(s[i + 2]) &&\n               // check for non-shortest form\n               (lead != 0xf0 || s[i] >= 0x90) &&\n               (lead != 0xf4 || s[i] < 0x90)) {\n      i += 3;  // 4-byte character\n    } else {\n      return false;\n    }\n  }\n  return true;\n}\n\nvoid ConditionalPrintAsText(const char* str, size_t length, ostream* os) {\n  if (!ContainsUnprintableControlCodes(str, length) &&\n      IsValidUTF8(str, length)) {\n    *os << \"\\n    As Text: \\\"\" << str << \"\\\"\";\n  }\n}\n\n}  // anonymous namespace\n\nvoid PrintStringTo(const ::std::string& s, ostream* os) {\n  if (PrintCharsAsStringTo(s.data(), s.size(), os) == kHexEscape) {\n    if (GTEST_FLAG_GET(print_utf8)) {\n      ConditionalPrintAsText(s.data(), s.size(), os);\n    }\n  }\n}\n\n#ifdef __cpp_char8_t\nvoid PrintU8StringTo(const ::std::u8string& s, ostream* os) {\n  PrintCharsAsStringTo(s.data(), s.size(), os);\n}\n#endif\n\nvoid PrintU16StringTo(const ::std::u16string& s, ostream* os) {\n  PrintCharsAsStringTo(s.data(), s.size(), os);\n}\n\nvoid PrintU32StringTo(const ::std::u32string& s, ostream* os) {\n  PrintCharsAsStringTo(s.data(), s.size(), os);\n}\n\n#if GTEST_HAS_STD_WSTRING\nvoid PrintWideStringTo(const ::std::wstring& s, ostream* os) {\n  PrintCharsAsStringTo(s.data(), s.size(), os);\n}\n#endif  // GTEST_HAS_STD_WSTRING\n\n}  // namespace internal\n\n}  // namespace testing\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/src/gtest-test-part.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// The Google C++ Testing and Mocking Framework (Google Test)\n\n#include \"gtest/gtest-test-part.h\"\n\n#include \"gtest/internal/gtest-port.h\"\n#include \"src/gtest-internal-inl.h\"\n\nnamespace testing {\n\nusing internal::GetUnitTestImpl;\n\n// Gets the summary of the failure message by omitting the stack trace\n// in it.\nstd::string TestPartResult::ExtractSummary(const char* message) {\n  const char* const stack_trace = strstr(message, internal::kStackTraceMarker);\n  return stack_trace == nullptr ? message : std::string(message, stack_trace);\n}\n\n// Prints a TestPartResult object.\nstd::ostream& operator<<(std::ostream& os, const TestPartResult& result) {\n  return os << internal::FormatFileLocation(result.file_name(),\n                                            result.line_number())\n            << \" \"\n            << (result.type() == TestPartResult::kSuccess ? \"Success\"\n                : result.type() == TestPartResult::kSkip  ? \"Skipped\"\n                : result.type() == TestPartResult::kFatalFailure\n                    ? \"Fatal failure\"\n                    : \"Non-fatal failure\")\n            << \":\\n\"\n            << result.message() << std::endl;\n}\n\n// Appends a TestPartResult to the array.\nvoid TestPartResultArray::Append(const TestPartResult& result) {\n  array_.push_back(result);\n}\n\n// Returns the TestPartResult at the given index (0-based).\nconst TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {\n  if (index < 0 || index >= size()) {\n    printf(\"\\nInvalid index (%d) into TestPartResultArray.\\n\", index);\n    internal::posix::Abort();\n  }\n\n  return array_[static_cast<size_t>(index)];\n}\n\n// Returns the number of TestPartResult objects in the array.\nint TestPartResultArray::size() const {\n  return static_cast<int>(array_.size());\n}\n\nnamespace internal {\n\nHasNewFatalFailureHelper::HasNewFatalFailureHelper()\n    : has_new_fatal_failure_(false),\n      original_reporter_(\n          GetUnitTestImpl()->GetTestPartResultReporterForCurrentThread()) {\n  GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);\n}\n\nHasNewFatalFailureHelper::~HasNewFatalFailureHelper() {\n  GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(\n      original_reporter_);\n}\n\nvoid HasNewFatalFailureHelper::ReportTestPartResult(\n    const TestPartResult& result) {\n  if (result.fatally_failed()) has_new_fatal_failure_ = true;\n  original_reporter_->ReportTestPartResult(result);\n}\n\n}  // namespace internal\n\n}  // namespace testing\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/src/gtest-typed-test.cc",
    "content": "// Copyright 2008 Google Inc.\n// All Rights Reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"gtest/gtest-typed-test.h\"\n\n#include \"gtest/gtest.h\"\n\nnamespace testing {\nnamespace internal {\n\n// Skips to the first non-space char in str. Returns an empty string if str\n// contains only whitespace characters.\nstatic const char* SkipSpaces(const char* str) {\n  while (IsSpace(*str)) str++;\n  return str;\n}\n\nstatic std::vector<std::string> SplitIntoTestNames(const char* src) {\n  std::vector<std::string> name_vec;\n  src = SkipSpaces(src);\n  for (; src != nullptr; src = SkipComma(src)) {\n    name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src)));\n  }\n  return name_vec;\n}\n\n// Verifies that registered_tests match the test names in\n// registered_tests_; returns registered_tests if successful, or\n// aborts the program otherwise.\nconst char* TypedTestSuitePState::VerifyRegisteredTestNames(\n    const char* test_suite_name, const char* file, int line,\n    const char* registered_tests) {\n  RegisterTypeParameterizedTestSuite(test_suite_name, CodeLocation(file, line));\n\n  typedef RegisteredTestsMap::const_iterator RegisteredTestIter;\n  registered_ = true;\n\n  std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests);\n\n  Message errors;\n\n  std::set<std::string> tests;\n  for (std::vector<std::string>::const_iterator name_it = name_vec.begin();\n       name_it != name_vec.end(); ++name_it) {\n    const std::string& name = *name_it;\n    if (tests.count(name) != 0) {\n      errors << \"Test \" << name << \" is listed more than once.\\n\";\n      continue;\n    }\n\n    if (registered_tests_.count(name) != 0) {\n      tests.insert(name);\n    } else {\n      errors << \"No test named \" << name\n             << \" can be found in this test suite.\\n\";\n    }\n  }\n\n  for (RegisteredTestIter it = registered_tests_.begin();\n       it != registered_tests_.end(); ++it) {\n    if (tests.count(it->first) == 0) {\n      errors << \"You forgot to list test \" << it->first << \".\\n\";\n    }\n  }\n\n  const std::string& errors_str = errors.GetString();\n  if (errors_str != \"\") {\n    fprintf(stderr, \"%s %s\", FormatFileLocation(file, line).c_str(),\n            errors_str.c_str());\n    fflush(stderr);\n    posix::Abort();\n  }\n\n  return registered_tests;\n}\n\n}  // namespace internal\n}  // namespace testing\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/src/gtest.cc",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// The Google C++ Testing and Mocking Framework (Google Test)\n\n#include \"gtest/gtest.h\"\n\n#include <ctype.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <wchar.h>\n#include <wctype.h>\n\n#include <algorithm>\n#include <chrono>  // NOLINT\n#include <cmath>\n#include <cstdint>\n#include <initializer_list>\n#include <iomanip>\n#include <iterator>\n#include <limits>\n#include <list>\n#include <map>\n#include <ostream>  // NOLINT\n#include <sstream>\n#include <unordered_set>\n#include <vector>\n\n#include \"gtest/gtest-assertion-result.h\"\n#include \"gtest/gtest-spi.h\"\n#include \"gtest/internal/custom/gtest.h\"\n\n#if GTEST_OS_LINUX\n\n#include <fcntl.h>   // NOLINT\n#include <limits.h>  // NOLINT\n#include <sched.h>   // NOLINT\n// Declares vsnprintf().  This header is not available on Windows.\n#include <strings.h>   // NOLINT\n#include <sys/mman.h>  // NOLINT\n#include <sys/time.h>  // NOLINT\n#include <unistd.h>    // NOLINT\n\n#include <string>\n\n#elif GTEST_OS_ZOS\n#include <sys/time.h>  // NOLINT\n\n// On z/OS we additionally need strings.h for strcasecmp.\n#include <strings.h>   // NOLINT\n\n#elif GTEST_OS_WINDOWS_MOBILE  // We are on Windows CE.\n\n#include <windows.h>  // NOLINT\n#undef min\n\n#elif GTEST_OS_WINDOWS  // We are on Windows proper.\n\n#include <windows.h>  // NOLINT\n#undef min\n\n#ifdef _MSC_VER\n#include <crtdbg.h>  // NOLINT\n#endif\n\n#include <io.h>         // NOLINT\n#include <sys/stat.h>   // NOLINT\n#include <sys/timeb.h>  // NOLINT\n#include <sys/types.h>  // NOLINT\n\n#if GTEST_OS_WINDOWS_MINGW\n#include <sys/time.h>  // NOLINT\n#endif                 // GTEST_OS_WINDOWS_MINGW\n\n#else\n\n// cpplint thinks that the header is already included, so we want to\n// silence it.\n#include <sys/time.h>  // NOLINT\n#include <unistd.h>    // NOLINT\n\n#endif  // GTEST_OS_LINUX\n\n#if GTEST_HAS_EXCEPTIONS\n#include <stdexcept>\n#endif\n\n#if GTEST_CAN_STREAM_RESULTS_\n#include <arpa/inet.h>   // NOLINT\n#include <netdb.h>       // NOLINT\n#include <sys/socket.h>  // NOLINT\n#include <sys/types.h>   // NOLINT\n#endif\n\n#include \"src/gtest-internal-inl.h\"\n\n#if GTEST_OS_WINDOWS\n#define vsnprintf _vsnprintf\n#endif  // GTEST_OS_WINDOWS\n\n#if GTEST_OS_MAC\n#ifndef GTEST_OS_IOS\n#include <crt_externs.h>\n#endif\n#endif\n\n#if GTEST_HAS_ABSL\n#include \"absl/debugging/failure_signal_handler.h\"\n#include \"absl/debugging/stacktrace.h\"\n#include \"absl/debugging/symbolize.h\"\n#include \"absl/flags/parse.h\"\n#include \"absl/flags/usage.h\"\n#include \"absl/strings/str_cat.h\"\n#include \"absl/strings/str_replace.h\"\n#endif  // GTEST_HAS_ABSL\n\nnamespace testing {\n\nusing internal::CountIf;\nusing internal::ForEach;\nusing internal::GetElementOr;\nusing internal::Shuffle;\n\n// Constants.\n\n// A test whose test suite name or test name matches this filter is\n// disabled and not run.\nstatic const char kDisableTestFilter[] = \"DISABLED_*:*/DISABLED_*\";\n\n// A test suite whose name matches this filter is considered a death\n// test suite and will be run before test suites whose name doesn't\n// match this filter.\nstatic const char kDeathTestSuiteFilter[] = \"*DeathTest:*DeathTest/*\";\n\n// A test filter that matches everything.\nstatic const char kUniversalFilter[] = \"*\";\n\n// The default output format.\nstatic const char kDefaultOutputFormat[] = \"xml\";\n// The default output file.\nstatic const char kDefaultOutputFile[] = \"test_detail\";\n\n// The environment variable name for the test shard index.\nstatic const char kTestShardIndex[] = \"GTEST_SHARD_INDEX\";\n// The environment variable name for the total number of test shards.\nstatic const char kTestTotalShards[] = \"GTEST_TOTAL_SHARDS\";\n// The environment variable name for the test shard status file.\nstatic const char kTestShardStatusFile[] = \"GTEST_SHARD_STATUS_FILE\";\n\nnamespace internal {\n\n// The text used in failure messages to indicate the start of the\n// stack trace.\nconst char kStackTraceMarker[] = \"\\nStack trace:\\n\";\n\n// g_help_flag is true if and only if the --help flag or an equivalent form\n// is specified on the command line.\nbool g_help_flag = false;\n\n// Utility function to Open File for Writing\nstatic FILE* OpenFileForWriting(const std::string& output_file) {\n  FILE* fileout = nullptr;\n  FilePath output_file_path(output_file);\n  FilePath output_dir(output_file_path.RemoveFileName());\n\n  if (output_dir.CreateDirectoriesRecursively()) {\n    fileout = posix::FOpen(output_file.c_str(), \"w\");\n  }\n  if (fileout == nullptr) {\n    GTEST_LOG_(FATAL) << \"Unable to open file \\\"\" << output_file << \"\\\"\";\n  }\n  return fileout;\n}\n\n}  // namespace internal\n\n// Bazel passes in the argument to '--test_filter' via the TESTBRIDGE_TEST_ONLY\n// environment variable.\nstatic const char* GetDefaultFilter() {\n  const char* const testbridge_test_only =\n      internal::posix::GetEnv(\"TESTBRIDGE_TEST_ONLY\");\n  if (testbridge_test_only != nullptr) {\n    return testbridge_test_only;\n  }\n  return kUniversalFilter;\n}\n\n// Bazel passes in the argument to '--test_runner_fail_fast' via the\n// TESTBRIDGE_TEST_RUNNER_FAIL_FAST environment variable.\nstatic bool GetDefaultFailFast() {\n  const char* const testbridge_test_runner_fail_fast =\n      internal::posix::GetEnv(\"TESTBRIDGE_TEST_RUNNER_FAIL_FAST\");\n  if (testbridge_test_runner_fail_fast != nullptr) {\n    return strcmp(testbridge_test_runner_fail_fast, \"1\") == 0;\n  }\n  return false;\n}\n\n}  // namespace testing\n\nGTEST_DEFINE_bool_(\n    fail_fast,\n    testing::internal::BoolFromGTestEnv(\"fail_fast\",\n                                        testing::GetDefaultFailFast()),\n    \"True if and only if a test failure should stop further test execution.\");\n\nGTEST_DEFINE_bool_(\n    also_run_disabled_tests,\n    testing::internal::BoolFromGTestEnv(\"also_run_disabled_tests\", false),\n    \"Run disabled tests too, in addition to the tests normally being run.\");\n\nGTEST_DEFINE_bool_(\n    break_on_failure,\n    testing::internal::BoolFromGTestEnv(\"break_on_failure\", false),\n    \"True if and only if a failed assertion should be a debugger \"\n    \"break-point.\");\n\nGTEST_DEFINE_bool_(catch_exceptions,\n                   testing::internal::BoolFromGTestEnv(\"catch_exceptions\",\n                                                       true),\n                   \"True if and only if \" GTEST_NAME_\n                   \" should catch exceptions and treat them as test failures.\");\n\nGTEST_DEFINE_string_(\n    color, testing::internal::StringFromGTestEnv(\"color\", \"auto\"),\n    \"Whether to use colors in the output.  Valid values: yes, no, \"\n    \"and auto.  'auto' means to use colors if the output is \"\n    \"being sent to a terminal and the TERM environment variable \"\n    \"is set to a terminal type that supports colors.\");\n\nGTEST_DEFINE_string_(\n    filter,\n    testing::internal::StringFromGTestEnv(\"filter\",\n                                          testing::GetDefaultFilter()),\n    \"A colon-separated list of glob (not regex) patterns \"\n    \"for filtering the tests to run, optionally followed by a \"\n    \"'-' and a : separated list of negative patterns (tests to \"\n    \"exclude).  A test is run if it matches one of the positive \"\n    \"patterns and does not match any of the negative patterns.\");\n\nGTEST_DEFINE_bool_(\n    install_failure_signal_handler,\n    testing::internal::BoolFromGTestEnv(\"install_failure_signal_handler\",\n                                        false),\n    \"If true and supported on the current platform, \" GTEST_NAME_\n    \" should \"\n    \"install a signal handler that dumps debugging information when fatal \"\n    \"signals are raised.\");\n\nGTEST_DEFINE_bool_(list_tests, false, \"List all tests without running them.\");\n\n// The net priority order after flag processing is thus:\n//   --gtest_output command line flag\n//   GTEST_OUTPUT environment variable\n//   XML_OUTPUT_FILE environment variable\n//   ''\nGTEST_DEFINE_string_(\n    output,\n    testing::internal::StringFromGTestEnv(\n        \"output\", testing::internal::OutputFlagAlsoCheckEnvVar().c_str()),\n    \"A format (defaults to \\\"xml\\\" but can be specified to be \\\"json\\\"), \"\n    \"optionally followed by a colon and an output file name or directory. \"\n    \"A directory is indicated by a trailing pathname separator. \"\n    \"Examples: \\\"xml:filename.xml\\\", \\\"xml::directoryname/\\\". \"\n    \"If a directory is specified, output files will be created \"\n    \"within that directory, with file-names based on the test \"\n    \"executable's name and, if necessary, made unique by adding \"\n    \"digits.\");\n\nGTEST_DEFINE_bool_(\n    brief, testing::internal::BoolFromGTestEnv(\"brief\", false),\n    \"True if only test failures should be displayed in text output.\");\n\nGTEST_DEFINE_bool_(print_time,\n                   testing::internal::BoolFromGTestEnv(\"print_time\", true),\n                   \"True if and only if \" GTEST_NAME_\n                   \" should display elapsed time in text output.\");\n\nGTEST_DEFINE_bool_(print_utf8,\n                   testing::internal::BoolFromGTestEnv(\"print_utf8\", true),\n                   \"True if and only if \" GTEST_NAME_\n                   \" prints UTF8 characters as text.\");\n\nGTEST_DEFINE_int32_(\n    random_seed, testing::internal::Int32FromGTestEnv(\"random_seed\", 0),\n    \"Random number seed to use when shuffling test orders.  Must be in range \"\n    \"[1, 99999], or 0 to use a seed based on the current time.\");\n\nGTEST_DEFINE_int32_(\n    repeat, testing::internal::Int32FromGTestEnv(\"repeat\", 1),\n    \"How many times to repeat each test.  Specify a negative number \"\n    \"for repeating forever.  Useful for shaking out flaky tests.\");\n\nGTEST_DEFINE_bool_(\n    recreate_environments_when_repeating,\n    testing::internal::BoolFromGTestEnv(\"recreate_environments_when_repeating\",\n                                        false),\n    \"Controls whether global test environments are recreated for each repeat \"\n    \"of the tests. If set to false the global test environments are only set \"\n    \"up once, for the first iteration, and only torn down once, for the last. \"\n    \"Useful for shaking out flaky tests with stable, expensive test \"\n    \"environments. If --gtest_repeat is set to a negative number, meaning \"\n    \"there is no last run, the environments will always be recreated to avoid \"\n    \"leaks.\");\n\nGTEST_DEFINE_bool_(show_internal_stack_frames, false,\n                   \"True if and only if \" GTEST_NAME_\n                   \" should include internal stack frames when \"\n                   \"printing test failure stack traces.\");\n\nGTEST_DEFINE_bool_(shuffle,\n                   testing::internal::BoolFromGTestEnv(\"shuffle\", false),\n                   \"True if and only if \" GTEST_NAME_\n                   \" should randomize tests' order on every run.\");\n\nGTEST_DEFINE_int32_(\n    stack_trace_depth,\n    testing::internal::Int32FromGTestEnv(\"stack_trace_depth\",\n                                         testing::kMaxStackTraceDepth),\n    \"The maximum number of stack frames to print when an \"\n    \"assertion fails.  The valid range is 0 through 100, inclusive.\");\n\nGTEST_DEFINE_string_(\n    stream_result_to,\n    testing::internal::StringFromGTestEnv(\"stream_result_to\", \"\"),\n    \"This flag specifies the host name and the port number on which to stream \"\n    \"test results. Example: \\\"localhost:555\\\". The flag is effective only on \"\n    \"Linux.\");\n\nGTEST_DEFINE_bool_(\n    throw_on_failure,\n    testing::internal::BoolFromGTestEnv(\"throw_on_failure\", false),\n    \"When this flag is specified, a failed assertion will throw an exception \"\n    \"if exceptions are enabled or exit the program with a non-zero code \"\n    \"otherwise. For use with an external test framework.\");\n\n#if GTEST_USE_OWN_FLAGFILE_FLAG_\nGTEST_DEFINE_string_(\n    flagfile, testing::internal::StringFromGTestEnv(\"flagfile\", \"\"),\n    \"This flag specifies the flagfile to read command-line flags from.\");\n#endif  // GTEST_USE_OWN_FLAGFILE_FLAG_\n\nnamespace testing {\nnamespace internal {\n\n// Generates a random number from [0, range), using a Linear\n// Congruential Generator (LCG).  Crashes if 'range' is 0 or greater\n// than kMaxRange.\nuint32_t Random::Generate(uint32_t range) {\n  // These constants are the same as are used in glibc's rand(3).\n  // Use wider types than necessary to prevent unsigned overflow diagnostics.\n  state_ = static_cast<uint32_t>(1103515245ULL * state_ + 12345U) % kMaxRange;\n\n  GTEST_CHECK_(range > 0) << \"Cannot generate a number in the range [0, 0).\";\n  GTEST_CHECK_(range <= kMaxRange)\n      << \"Generation of a number in [0, \" << range << \") was requested, \"\n      << \"but this can only generate numbers in [0, \" << kMaxRange << \").\";\n\n  // Converting via modulus introduces a bit of downward bias, but\n  // it's simple, and a linear congruential generator isn't too good\n  // to begin with.\n  return state_ % range;\n}\n\n// GTestIsInitialized() returns true if and only if the user has initialized\n// Google Test.  Useful for catching the user mistake of not initializing\n// Google Test before calling RUN_ALL_TESTS().\nstatic bool GTestIsInitialized() { return GetArgvs().size() > 0; }\n\n// Iterates over a vector of TestSuites, keeping a running sum of the\n// results of calling a given int-returning method on each.\n// Returns the sum.\nstatic int SumOverTestSuiteList(const std::vector<TestSuite*>& case_list,\n                                int (TestSuite::*method)() const) {\n  int sum = 0;\n  for (size_t i = 0; i < case_list.size(); i++) {\n    sum += (case_list[i]->*method)();\n  }\n  return sum;\n}\n\n// Returns true if and only if the test suite passed.\nstatic bool TestSuitePassed(const TestSuite* test_suite) {\n  return test_suite->should_run() && test_suite->Passed();\n}\n\n// Returns true if and only if the test suite failed.\nstatic bool TestSuiteFailed(const TestSuite* test_suite) {\n  return test_suite->should_run() && test_suite->Failed();\n}\n\n// Returns true if and only if test_suite contains at least one test that\n// should run.\nstatic bool ShouldRunTestSuite(const TestSuite* test_suite) {\n  return test_suite->should_run();\n}\n\n// AssertHelper constructor.\nAssertHelper::AssertHelper(TestPartResult::Type type, const char* file,\n                           int line, const char* message)\n    : data_(new AssertHelperData(type, file, line, message)) {}\n\nAssertHelper::~AssertHelper() { delete data_; }\n\n// Message assignment, for assertion streaming support.\nvoid AssertHelper::operator=(const Message& message) const {\n  UnitTest::GetInstance()->AddTestPartResult(\n      data_->type, data_->file, data_->line,\n      AppendUserMessage(data_->message, message),\n      UnitTest::GetInstance()->impl()->CurrentOsStackTraceExceptTop(1)\n      // Skips the stack frame for this function itself.\n  );  // NOLINT\n}\n\nnamespace {\n\n// When TEST_P is found without a matching INSTANTIATE_TEST_SUITE_P\n// to creates test cases for it, a synthetic test case is\n// inserted to report ether an error or a log message.\n//\n// This configuration bit will likely be removed at some point.\nconstexpr bool kErrorOnUninstantiatedParameterizedTest = true;\nconstexpr bool kErrorOnUninstantiatedTypeParameterizedTest = true;\n\n// A test that fails at a given file/line location with a given message.\nclass FailureTest : public Test {\n public:\n  explicit FailureTest(const CodeLocation& loc, std::string error_message,\n                       bool as_error)\n      : loc_(loc),\n        error_message_(std::move(error_message)),\n        as_error_(as_error) {}\n\n  void TestBody() override {\n    if (as_error_) {\n      AssertHelper(TestPartResult::kNonFatalFailure, loc_.file.c_str(),\n                   loc_.line, \"\") = Message() << error_message_;\n    } else {\n      std::cout << error_message_ << std::endl;\n    }\n  }\n\n private:\n  const CodeLocation loc_;\n  const std::string error_message_;\n  const bool as_error_;\n};\n\n}  // namespace\n\nstd::set<std::string>* GetIgnoredParameterizedTestSuites() {\n  return UnitTest::GetInstance()->impl()->ignored_parameterized_test_suites();\n}\n\n// Add a given test_suit to the list of them allow to go un-instantiated.\nMarkAsIgnored::MarkAsIgnored(const char* test_suite) {\n  GetIgnoredParameterizedTestSuites()->insert(test_suite);\n}\n\n// If this parameterized test suite has no instantiations (and that\n// has not been marked as okay), emit a test case reporting that.\nvoid InsertSyntheticTestCase(const std::string& name, CodeLocation location,\n                             bool has_test_p) {\n  const auto& ignored = *GetIgnoredParameterizedTestSuites();\n  if (ignored.find(name) != ignored.end()) return;\n\n  const char kMissingInstantiation[] =  //\n      \" is defined via TEST_P, but never instantiated. None of the test cases \"\n      \"will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only \"\n      \"ones provided expand to nothing.\"\n      \"\\n\\n\"\n      \"Ideally, TEST_P definitions should only ever be included as part of \"\n      \"binaries that intend to use them. (As opposed to, for example, being \"\n      \"placed in a library that may be linked in to get other utilities.)\";\n\n  const char kMissingTestCase[] =  //\n      \" is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are \"\n      \"defined via TEST_P . No test cases will run.\"\n      \"\\n\\n\"\n      \"Ideally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from \"\n      \"code that always depend on code that provides TEST_P. Failing to do \"\n      \"so is often an indication of dead code, e.g. the last TEST_P was \"\n      \"removed but the rest got left behind.\";\n\n  std::string message =\n      \"Parameterized test suite \" + name +\n      (has_test_p ? kMissingInstantiation : kMissingTestCase) +\n      \"\\n\\n\"\n      \"To suppress this error for this test suite, insert the following line \"\n      \"(in a non-header) in the namespace it is defined in:\"\n      \"\\n\\n\"\n      \"GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(\" +\n      name + \");\";\n\n  std::string full_name = \"UninstantiatedParameterizedTestSuite<\" + name + \">\";\n  RegisterTest(  //\n      \"GoogleTestVerification\", full_name.c_str(),\n      nullptr,  // No type parameter.\n      nullptr,  // No value parameter.\n      location.file.c_str(), location.line, [message, location] {\n        return new FailureTest(location, message,\n                               kErrorOnUninstantiatedParameterizedTest);\n      });\n}\n\nvoid RegisterTypeParameterizedTestSuite(const char* test_suite_name,\n                                        CodeLocation code_location) {\n  GetUnitTestImpl()->type_parameterized_test_registry().RegisterTestSuite(\n      test_suite_name, code_location);\n}\n\nvoid RegisterTypeParameterizedTestSuiteInstantiation(const char* case_name) {\n  GetUnitTestImpl()->type_parameterized_test_registry().RegisterInstantiation(\n      case_name);\n}\n\nvoid TypeParameterizedTestSuiteRegistry::RegisterTestSuite(\n    const char* test_suite_name, CodeLocation code_location) {\n  suites_.emplace(std::string(test_suite_name),\n                  TypeParameterizedTestSuiteInfo(code_location));\n}\n\nvoid TypeParameterizedTestSuiteRegistry::RegisterInstantiation(\n    const char* test_suite_name) {\n  auto it = suites_.find(std::string(test_suite_name));\n  if (it != suites_.end()) {\n    it->second.instantiated = true;\n  } else {\n    GTEST_LOG_(ERROR) << \"Unknown type parameterized test suit '\"\n                      << test_suite_name << \"'\";\n  }\n}\n\nvoid TypeParameterizedTestSuiteRegistry::CheckForInstantiations() {\n  const auto& ignored = *GetIgnoredParameterizedTestSuites();\n  for (const auto& testcase : suites_) {\n    if (testcase.second.instantiated) continue;\n    if (ignored.find(testcase.first) != ignored.end()) continue;\n\n    std::string message =\n        \"Type parameterized test suite \" + testcase.first +\n        \" is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated \"\n        \"via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run.\"\n        \"\\n\\n\"\n        \"Ideally, TYPED_TEST_P definitions should only ever be included as \"\n        \"part of binaries that intend to use them. (As opposed to, for \"\n        \"example, being placed in a library that may be linked in to get other \"\n        \"utilities.)\"\n        \"\\n\\n\"\n        \"To suppress this error for this test suite, insert the following line \"\n        \"(in a non-header) in the namespace it is defined in:\"\n        \"\\n\\n\"\n        \"GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(\" +\n        testcase.first + \");\";\n\n    std::string full_name =\n        \"UninstantiatedTypeParameterizedTestSuite<\" + testcase.first + \">\";\n    RegisterTest(  //\n        \"GoogleTestVerification\", full_name.c_str(),\n        nullptr,  // No type parameter.\n        nullptr,  // No value parameter.\n        testcase.second.code_location.file.c_str(),\n        testcase.second.code_location.line, [message, testcase] {\n          return new FailureTest(testcase.second.code_location, message,\n                                 kErrorOnUninstantiatedTypeParameterizedTest);\n        });\n  }\n}\n\n// A copy of all command line arguments.  Set by InitGoogleTest().\nstatic ::std::vector<std::string> g_argvs;\n\n::std::vector<std::string> GetArgvs() {\n#if defined(GTEST_CUSTOM_GET_ARGVS_)\n  // GTEST_CUSTOM_GET_ARGVS_() may return a container of std::string or\n  // ::string. This code converts it to the appropriate type.\n  const auto& custom = GTEST_CUSTOM_GET_ARGVS_();\n  return ::std::vector<std::string>(custom.begin(), custom.end());\n#else   // defined(GTEST_CUSTOM_GET_ARGVS_)\n  return g_argvs;\n#endif  // defined(GTEST_CUSTOM_GET_ARGVS_)\n}\n\n// Returns the current application's name, removing directory path if that\n// is present.\nFilePath GetCurrentExecutableName() {\n  FilePath result;\n\n#if GTEST_OS_WINDOWS || GTEST_OS_OS2\n  result.Set(FilePath(GetArgvs()[0]).RemoveExtension(\"exe\"));\n#else\n  result.Set(FilePath(GetArgvs()[0]));\n#endif  // GTEST_OS_WINDOWS\n\n  return result.RemoveDirectoryName();\n}\n\n// Functions for processing the gtest_output flag.\n\n// Returns the output format, or \"\" for normal printed output.\nstd::string UnitTestOptions::GetOutputFormat() {\n  std::string s = GTEST_FLAG_GET(output);\n  const char* const gtest_output_flag = s.c_str();\n  const char* const colon = strchr(gtest_output_flag, ':');\n  return (colon == nullptr)\n             ? std::string(gtest_output_flag)\n             : std::string(gtest_output_flag,\n                           static_cast<size_t>(colon - gtest_output_flag));\n}\n\n// Returns the name of the requested output file, or the default if none\n// was explicitly specified.\nstd::string UnitTestOptions::GetAbsolutePathToOutputFile() {\n  std::string s = GTEST_FLAG_GET(output);\n  const char* const gtest_output_flag = s.c_str();\n\n  std::string format = GetOutputFormat();\n  if (format.empty()) format = std::string(kDefaultOutputFormat);\n\n  const char* const colon = strchr(gtest_output_flag, ':');\n  if (colon == nullptr)\n    return internal::FilePath::MakeFileName(\n               internal::FilePath(\n                   UnitTest::GetInstance()->original_working_dir()),\n               internal::FilePath(kDefaultOutputFile), 0, format.c_str())\n        .string();\n\n  internal::FilePath output_name(colon + 1);\n  if (!output_name.IsAbsolutePath())\n    output_name = internal::FilePath::ConcatPaths(\n        internal::FilePath(UnitTest::GetInstance()->original_working_dir()),\n        internal::FilePath(colon + 1));\n\n  if (!output_name.IsDirectory()) return output_name.string();\n\n  internal::FilePath result(internal::FilePath::GenerateUniqueFileName(\n      output_name, internal::GetCurrentExecutableName(),\n      GetOutputFormat().c_str()));\n  return result.string();\n}\n\n// Returns true if and only if the wildcard pattern matches the string. Each\n// pattern consists of regular characters, single-character wildcards (?), and\n// multi-character wildcards (*).\n//\n// This function implements a linear-time string globbing algorithm based on\n// https://research.swtch.com/glob.\nstatic bool PatternMatchesString(const std::string& name_str,\n                                 const char* pattern, const char* pattern_end) {\n  const char* name = name_str.c_str();\n  const char* const name_begin = name;\n  const char* const name_end = name + name_str.size();\n\n  const char* pattern_next = pattern;\n  const char* name_next = name;\n\n  while (pattern < pattern_end || name < name_end) {\n    if (pattern < pattern_end) {\n      switch (*pattern) {\n        default:  // Match an ordinary character.\n          if (name < name_end && *name == *pattern) {\n            ++pattern;\n            ++name;\n            continue;\n          }\n          break;\n        case '?':  // Match any single character.\n          if (name < name_end) {\n            ++pattern;\n            ++name;\n            continue;\n          }\n          break;\n        case '*':\n          // Match zero or more characters. Start by skipping over the wildcard\n          // and matching zero characters from name. If that fails, restart and\n          // match one more character than the last attempt.\n          pattern_next = pattern;\n          name_next = name + 1;\n          ++pattern;\n          continue;\n      }\n    }\n    // Failed to match a character. Restart if possible.\n    if (name_begin < name_next && name_next <= name_end) {\n      pattern = pattern_next;\n      name = name_next;\n      continue;\n    }\n    return false;\n  }\n  return true;\n}\n\nnamespace {\n\nbool IsGlobPattern(const std::string& pattern) {\n  return std::any_of(pattern.begin(), pattern.end(),\n                     [](const char c) { return c == '?' || c == '*'; });\n}\n\nclass UnitTestFilter {\n public:\n  UnitTestFilter() = default;\n\n  // Constructs a filter from a string of patterns separated by `:`.\n  explicit UnitTestFilter(const std::string& filter) {\n    // By design \"\" filter matches \"\" string.\n    std::vector<std::string> all_patterns;\n    SplitString(filter, ':', &all_patterns);\n    const auto exact_match_patterns_begin = std::partition(\n        all_patterns.begin(), all_patterns.end(), &IsGlobPattern);\n\n    glob_patterns_.reserve(static_cast<size_t>(\n        std::distance(all_patterns.begin(), exact_match_patterns_begin)));\n    std::move(all_patterns.begin(), exact_match_patterns_begin,\n              std::inserter(glob_patterns_, glob_patterns_.begin()));\n    std::move(\n        exact_match_patterns_begin, all_patterns.end(),\n        std::inserter(exact_match_patterns_, exact_match_patterns_.begin()));\n  }\n\n  // Returns true if and only if name matches at least one of the patterns in\n  // the filter.\n  bool MatchesName(const std::string& name) const {\n    return exact_match_patterns_.count(name) > 0 ||\n           std::any_of(glob_patterns_.begin(), glob_patterns_.end(),\n                       [&name](const std::string& pattern) {\n                         return PatternMatchesString(\n                             name, pattern.c_str(),\n                             pattern.c_str() + pattern.size());\n                       });\n  }\n\n private:\n  std::vector<std::string> glob_patterns_;\n  std::unordered_set<std::string> exact_match_patterns_;\n};\n\nclass PositiveAndNegativeUnitTestFilter {\n public:\n  // Constructs a positive and a negative filter from a string. The string\n  // contains a positive filter optionally followed by a '-' character and a\n  // negative filter. In case only a negative filter is provided the positive\n  // filter will be assumed \"*\".\n  // A filter is a list of patterns separated by ':'.\n  explicit PositiveAndNegativeUnitTestFilter(const std::string& filter) {\n    std::vector<std::string> positive_and_negative_filters;\n\n    // NOTE: `SplitString` always returns a non-empty container.\n    SplitString(filter, '-', &positive_and_negative_filters);\n    const auto& positive_filter = positive_and_negative_filters.front();\n\n    if (positive_and_negative_filters.size() > 1) {\n      positive_filter_ = UnitTestFilter(\n          positive_filter.empty() ? kUniversalFilter : positive_filter);\n\n      // TODO(b/214626361): Fail on multiple '-' characters\n      // For the moment to preserve old behavior we concatenate the rest of the\n      // string parts with `-` as separator to generate the negative filter.\n      auto negative_filter_string = positive_and_negative_filters[1];\n      for (std::size_t i = 2; i < positive_and_negative_filters.size(); i++)\n        negative_filter_string =\n            negative_filter_string + '-' + positive_and_negative_filters[i];\n      negative_filter_ = UnitTestFilter(negative_filter_string);\n    } else {\n      // In case we don't have a negative filter and positive filter is \"\"\n      // we do not use kUniversalFilter by design as opposed to when we have a\n      // negative filter.\n      positive_filter_ = UnitTestFilter(positive_filter);\n    }\n  }\n\n  // Returns true if and only if test name (this is generated by appending test\n  // suit name and test name via a '.' character) matches the positive filter\n  // and does not match the negative filter.\n  bool MatchesTest(const std::string& test_suite_name,\n                   const std::string& test_name) const {\n    return MatchesName(test_suite_name + \".\" + test_name);\n  }\n\n  // Returns true if and only if name matches the positive filter and does not\n  // match the negative filter.\n  bool MatchesName(const std::string& name) const {\n    return positive_filter_.MatchesName(name) &&\n           !negative_filter_.MatchesName(name);\n  }\n\n private:\n  UnitTestFilter positive_filter_;\n  UnitTestFilter negative_filter_;\n};\n}  // namespace\n\nbool UnitTestOptions::MatchesFilter(const std::string& name_str,\n                                    const char* filter) {\n  return UnitTestFilter(filter).MatchesName(name_str);\n}\n\n// Returns true if and only if the user-specified filter matches the test\n// suite name and the test name.\nbool UnitTestOptions::FilterMatchesTest(const std::string& test_suite_name,\n                                        const std::string& test_name) {\n  // Split --gtest_filter at '-', if there is one, to separate into\n  // positive filter and negative filter portions\n  return PositiveAndNegativeUnitTestFilter(GTEST_FLAG_GET(filter))\n      .MatchesTest(test_suite_name, test_name);\n}\n\n#if GTEST_HAS_SEH\n// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the\n// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.\n// This function is useful as an __except condition.\nint UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {\n  // Google Test should handle a SEH exception if:\n  //   1. the user wants it to, AND\n  //   2. this is not a breakpoint exception, AND\n  //   3. this is not a C++ exception (VC++ implements them via SEH,\n  //      apparently).\n  //\n  // SEH exception code for C++ exceptions.\n  // (see http://support.microsoft.com/kb/185294 for more information).\n  const DWORD kCxxExceptionCode = 0xe06d7363;\n\n  bool should_handle = true;\n\n  if (!GTEST_FLAG_GET(catch_exceptions))\n    should_handle = false;\n  else if (exception_code == EXCEPTION_BREAKPOINT)\n    should_handle = false;\n  else if (exception_code == kCxxExceptionCode)\n    should_handle = false;\n\n  return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;\n}\n#endif  // GTEST_HAS_SEH\n\n}  // namespace internal\n\n// The c'tor sets this object as the test part result reporter used by\n// Google Test.  The 'result' parameter specifies where to report the\n// results. Intercepts only failures from the current thread.\nScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(\n    TestPartResultArray* result)\n    : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), result_(result) {\n  Init();\n}\n\n// The c'tor sets this object as the test part result reporter used by\n// Google Test.  The 'result' parameter specifies where to report the\n// results.\nScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(\n    InterceptMode intercept_mode, TestPartResultArray* result)\n    : intercept_mode_(intercept_mode), result_(result) {\n  Init();\n}\n\nvoid ScopedFakeTestPartResultReporter::Init() {\n  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\n  if (intercept_mode_ == INTERCEPT_ALL_THREADS) {\n    old_reporter_ = impl->GetGlobalTestPartResultReporter();\n    impl->SetGlobalTestPartResultReporter(this);\n  } else {\n    old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();\n    impl->SetTestPartResultReporterForCurrentThread(this);\n  }\n}\n\n// The d'tor restores the test part result reporter used by Google Test\n// before.\nScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {\n  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\n  if (intercept_mode_ == INTERCEPT_ALL_THREADS) {\n    impl->SetGlobalTestPartResultReporter(old_reporter_);\n  } else {\n    impl->SetTestPartResultReporterForCurrentThread(old_reporter_);\n  }\n}\n\n// Increments the test part result count and remembers the result.\n// This method is from the TestPartResultReporterInterface interface.\nvoid ScopedFakeTestPartResultReporter::ReportTestPartResult(\n    const TestPartResult& result) {\n  result_->Append(result);\n}\n\nnamespace internal {\n\n// Returns the type ID of ::testing::Test.  We should always call this\n// instead of GetTypeId< ::testing::Test>() to get the type ID of\n// testing::Test.  This is to work around a suspected linker bug when\n// using Google Test as a framework on Mac OS X.  The bug causes\n// GetTypeId< ::testing::Test>() to return different values depending\n// on whether the call is from the Google Test framework itself or\n// from user test code.  GetTestTypeId() is guaranteed to always\n// return the same value, as it always calls GetTypeId<>() from the\n// gtest.cc, which is within the Google Test framework.\nTypeId GetTestTypeId() { return GetTypeId<Test>(); }\n\n// The value of GetTestTypeId() as seen from within the Google Test\n// library.  This is solely for testing GetTestTypeId().\nextern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();\n\n// This predicate-formatter checks that 'results' contains a test part\n// failure of the given type and that the failure message contains the\n// given substring.\nstatic AssertionResult HasOneFailure(const char* /* results_expr */,\n                                     const char* /* type_expr */,\n                                     const char* /* substr_expr */,\n                                     const TestPartResultArray& results,\n                                     TestPartResult::Type type,\n                                     const std::string& substr) {\n  const std::string expected(type == TestPartResult::kFatalFailure\n                                 ? \"1 fatal failure\"\n                                 : \"1 non-fatal failure\");\n  Message msg;\n  if (results.size() != 1) {\n    msg << \"Expected: \" << expected << \"\\n\"\n        << \"  Actual: \" << results.size() << \" failures\";\n    for (int i = 0; i < results.size(); i++) {\n      msg << \"\\n\" << results.GetTestPartResult(i);\n    }\n    return AssertionFailure() << msg;\n  }\n\n  const TestPartResult& r = results.GetTestPartResult(0);\n  if (r.type() != type) {\n    return AssertionFailure() << \"Expected: \" << expected << \"\\n\"\n                              << \"  Actual:\\n\"\n                              << r;\n  }\n\n  if (strstr(r.message(), substr.c_str()) == nullptr) {\n    return AssertionFailure()\n           << \"Expected: \" << expected << \" containing \\\"\" << substr << \"\\\"\\n\"\n           << \"  Actual:\\n\"\n           << r;\n  }\n\n  return AssertionSuccess();\n}\n\n// The constructor of SingleFailureChecker remembers where to look up\n// test part results, what type of failure we expect, and what\n// substring the failure message should contain.\nSingleFailureChecker::SingleFailureChecker(const TestPartResultArray* results,\n                                           TestPartResult::Type type,\n                                           const std::string& substr)\n    : results_(results), type_(type), substr_(substr) {}\n\n// The destructor of SingleFailureChecker verifies that the given\n// TestPartResultArray contains exactly one failure that has the given\n// type and contains the given substring.  If that's not the case, a\n// non-fatal failure will be generated.\nSingleFailureChecker::~SingleFailureChecker() {\n  EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);\n}\n\nDefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(\n    UnitTestImpl* unit_test)\n    : unit_test_(unit_test) {}\n\nvoid DefaultGlobalTestPartResultReporter::ReportTestPartResult(\n    const TestPartResult& result) {\n  unit_test_->current_test_result()->AddTestPartResult(result);\n  unit_test_->listeners()->repeater()->OnTestPartResult(result);\n}\n\nDefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(\n    UnitTestImpl* unit_test)\n    : unit_test_(unit_test) {}\n\nvoid DefaultPerThreadTestPartResultReporter::ReportTestPartResult(\n    const TestPartResult& result) {\n  unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);\n}\n\n// Returns the global test part result reporter.\nTestPartResultReporterInterface*\nUnitTestImpl::GetGlobalTestPartResultReporter() {\n  internal::MutexLock lock(&global_test_part_result_reporter_mutex_);\n  return global_test_part_result_repoter_;\n}\n\n// Sets the global test part result reporter.\nvoid UnitTestImpl::SetGlobalTestPartResultReporter(\n    TestPartResultReporterInterface* reporter) {\n  internal::MutexLock lock(&global_test_part_result_reporter_mutex_);\n  global_test_part_result_repoter_ = reporter;\n}\n\n// Returns the test part result reporter for the current thread.\nTestPartResultReporterInterface*\nUnitTestImpl::GetTestPartResultReporterForCurrentThread() {\n  return per_thread_test_part_result_reporter_.get();\n}\n\n// Sets the test part result reporter for the current thread.\nvoid UnitTestImpl::SetTestPartResultReporterForCurrentThread(\n    TestPartResultReporterInterface* reporter) {\n  per_thread_test_part_result_reporter_.set(reporter);\n}\n\n// Gets the number of successful test suites.\nint UnitTestImpl::successful_test_suite_count() const {\n  return CountIf(test_suites_, TestSuitePassed);\n}\n\n// Gets the number of failed test suites.\nint UnitTestImpl::failed_test_suite_count() const {\n  return CountIf(test_suites_, TestSuiteFailed);\n}\n\n// Gets the number of all test suites.\nint UnitTestImpl::total_test_suite_count() const {\n  return static_cast<int>(test_suites_.size());\n}\n\n// Gets the number of all test suites that contain at least one test\n// that should run.\nint UnitTestImpl::test_suite_to_run_count() const {\n  return CountIf(test_suites_, ShouldRunTestSuite);\n}\n\n// Gets the number of successful tests.\nint UnitTestImpl::successful_test_count() const {\n  return SumOverTestSuiteList(test_suites_, &TestSuite::successful_test_count);\n}\n\n// Gets the number of skipped tests.\nint UnitTestImpl::skipped_test_count() const {\n  return SumOverTestSuiteList(test_suites_, &TestSuite::skipped_test_count);\n}\n\n// Gets the number of failed tests.\nint UnitTestImpl::failed_test_count() const {\n  return SumOverTestSuiteList(test_suites_, &TestSuite::failed_test_count);\n}\n\n// Gets the number of disabled tests that will be reported in the XML report.\nint UnitTestImpl::reportable_disabled_test_count() const {\n  return SumOverTestSuiteList(test_suites_,\n                              &TestSuite::reportable_disabled_test_count);\n}\n\n// Gets the number of disabled tests.\nint UnitTestImpl::disabled_test_count() const {\n  return SumOverTestSuiteList(test_suites_, &TestSuite::disabled_test_count);\n}\n\n// Gets the number of tests to be printed in the XML report.\nint UnitTestImpl::reportable_test_count() const {\n  return SumOverTestSuiteList(test_suites_, &TestSuite::reportable_test_count);\n}\n\n// Gets the number of all tests.\nint UnitTestImpl::total_test_count() const {\n  return SumOverTestSuiteList(test_suites_, &TestSuite::total_test_count);\n}\n\n// Gets the number of tests that should run.\nint UnitTestImpl::test_to_run_count() const {\n  return SumOverTestSuiteList(test_suites_, &TestSuite::test_to_run_count);\n}\n\n// Returns the current OS stack trace as an std::string.\n//\n// The maximum number of stack frames to be included is specified by\n// the gtest_stack_trace_depth flag.  The skip_count parameter\n// specifies the number of top frames to be skipped, which doesn't\n// count against the number of frames to be included.\n//\n// For example, if Foo() calls Bar(), which in turn calls\n// CurrentOsStackTraceExceptTop(1), Foo() will be included in the\n// trace but Bar() and CurrentOsStackTraceExceptTop() won't.\nstd::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {\n  return os_stack_trace_getter()->CurrentStackTrace(\n      static_cast<int>(GTEST_FLAG_GET(stack_trace_depth)), skip_count + 1\n      // Skips the user-specified number of frames plus this function\n      // itself.\n  );  // NOLINT\n}\n\n// A helper class for measuring elapsed times.\nclass Timer {\n public:\n  Timer() : start_(std::chrono::steady_clock::now()) {}\n\n  // Return time elapsed in milliseconds since the timer was created.\n  TimeInMillis Elapsed() {\n    return std::chrono::duration_cast<std::chrono::milliseconds>(\n               std::chrono::steady_clock::now() - start_)\n        .count();\n  }\n\n private:\n  std::chrono::steady_clock::time_point start_;\n};\n\n// Returns a timestamp as milliseconds since the epoch. Note this time may jump\n// around subject to adjustments by the system, to measure elapsed time use\n// Timer instead.\nTimeInMillis GetTimeInMillis() {\n  return std::chrono::duration_cast<std::chrono::milliseconds>(\n             std::chrono::system_clock::now() -\n             std::chrono::system_clock::from_time_t(0))\n      .count();\n}\n\n// Utilities\n\n// class String.\n\n#if GTEST_OS_WINDOWS_MOBILE\n// Creates a UTF-16 wide string from the given ANSI string, allocating\n// memory using new. The caller is responsible for deleting the return\n// value using delete[]. Returns the wide string, or NULL if the\n// input is NULL.\nLPCWSTR String::AnsiToUtf16(const char* ansi) {\n  if (!ansi) return nullptr;\n  const int length = strlen(ansi);\n  const int unicode_length =\n      MultiByteToWideChar(CP_ACP, 0, ansi, length, nullptr, 0);\n  WCHAR* unicode = new WCHAR[unicode_length + 1];\n  MultiByteToWideChar(CP_ACP, 0, ansi, length, unicode, unicode_length);\n  unicode[unicode_length] = 0;\n  return unicode;\n}\n\n// Creates an ANSI string from the given wide string, allocating\n// memory using new. The caller is responsible for deleting the return\n// value using delete[]. Returns the ANSI string, or NULL if the\n// input is NULL.\nconst char* String::Utf16ToAnsi(LPCWSTR utf16_str) {\n  if (!utf16_str) return nullptr;\n  const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, nullptr,\n                                              0, nullptr, nullptr);\n  char* ansi = new char[ansi_length + 1];\n  WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, nullptr,\n                      nullptr);\n  ansi[ansi_length] = 0;\n  return ansi;\n}\n\n#endif  // GTEST_OS_WINDOWS_MOBILE\n\n// Compares two C strings.  Returns true if and only if they have the same\n// content.\n//\n// Unlike strcmp(), this function can handle NULL argument(s).  A NULL\n// C string is considered different to any non-NULL C string,\n// including the empty string.\nbool String::CStringEquals(const char* lhs, const char* rhs) {\n  if (lhs == nullptr) return rhs == nullptr;\n\n  if (rhs == nullptr) return false;\n\n  return strcmp(lhs, rhs) == 0;\n}\n\n#if GTEST_HAS_STD_WSTRING\n\n// Converts an array of wide chars to a narrow string using the UTF-8\n// encoding, and streams the result to the given Message object.\nstatic void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,\n                                     Message* msg) {\n  for (size_t i = 0; i != length;) {  // NOLINT\n    if (wstr[i] != L'\\0') {\n      *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));\n      while (i != length && wstr[i] != L'\\0') i++;\n    } else {\n      *msg << '\\0';\n      i++;\n    }\n  }\n}\n\n#endif  // GTEST_HAS_STD_WSTRING\n\nvoid SplitString(const ::std::string& str, char delimiter,\n                 ::std::vector< ::std::string>* dest) {\n  ::std::vector< ::std::string> parsed;\n  ::std::string::size_type pos = 0;\n  while (::testing::internal::AlwaysTrue()) {\n    const ::std::string::size_type colon = str.find(delimiter, pos);\n    if (colon == ::std::string::npos) {\n      parsed.push_back(str.substr(pos));\n      break;\n    } else {\n      parsed.push_back(str.substr(pos, colon - pos));\n      pos = colon + 1;\n    }\n  }\n  dest->swap(parsed);\n}\n\n}  // namespace internal\n\n// Constructs an empty Message.\n// We allocate the stringstream separately because otherwise each use of\n// ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's\n// stack frame leading to huge stack frames in some cases; gcc does not reuse\n// the stack space.\nMessage::Message() : ss_(new ::std::stringstream) {\n  // By default, we want there to be enough precision when printing\n  // a double to a Message.\n  *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);\n}\n\n// These two overloads allow streaming a wide C string to a Message\n// using the UTF-8 encoding.\nMessage& Message::operator<<(const wchar_t* wide_c_str) {\n  return *this << internal::String::ShowWideCString(wide_c_str);\n}\nMessage& Message::operator<<(wchar_t* wide_c_str) {\n  return *this << internal::String::ShowWideCString(wide_c_str);\n}\n\n#if GTEST_HAS_STD_WSTRING\n// Converts the given wide string to a narrow string using the UTF-8\n// encoding, and streams the result to this Message object.\nMessage& Message::operator<<(const ::std::wstring& wstr) {\n  internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);\n  return *this;\n}\n#endif  // GTEST_HAS_STD_WSTRING\n\n// Gets the text streamed to this object so far as an std::string.\n// Each '\\0' character in the buffer is replaced with \"\\\\0\".\nstd::string Message::GetString() const {\n  return internal::StringStreamToString(ss_.get());\n}\n\nnamespace internal {\n\nnamespace edit_distance {\nstd::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,\n                                            const std::vector<size_t>& right) {\n  std::vector<std::vector<double> > costs(\n      left.size() + 1, std::vector<double>(right.size() + 1));\n  std::vector<std::vector<EditType> > best_move(\n      left.size() + 1, std::vector<EditType>(right.size() + 1));\n\n  // Populate for empty right.\n  for (size_t l_i = 0; l_i < costs.size(); ++l_i) {\n    costs[l_i][0] = static_cast<double>(l_i);\n    best_move[l_i][0] = kRemove;\n  }\n  // Populate for empty left.\n  for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {\n    costs[0][r_i] = static_cast<double>(r_i);\n    best_move[0][r_i] = kAdd;\n  }\n\n  for (size_t l_i = 0; l_i < left.size(); ++l_i) {\n    for (size_t r_i = 0; r_i < right.size(); ++r_i) {\n      if (left[l_i] == right[r_i]) {\n        // Found a match. Consume it.\n        costs[l_i + 1][r_i + 1] = costs[l_i][r_i];\n        best_move[l_i + 1][r_i + 1] = kMatch;\n        continue;\n      }\n\n      const double add = costs[l_i + 1][r_i];\n      const double remove = costs[l_i][r_i + 1];\n      const double replace = costs[l_i][r_i];\n      if (add < remove && add < replace) {\n        costs[l_i + 1][r_i + 1] = add + 1;\n        best_move[l_i + 1][r_i + 1] = kAdd;\n      } else if (remove < add && remove < replace) {\n        costs[l_i + 1][r_i + 1] = remove + 1;\n        best_move[l_i + 1][r_i + 1] = kRemove;\n      } else {\n        // We make replace a little more expensive than add/remove to lower\n        // their priority.\n        costs[l_i + 1][r_i + 1] = replace + 1.00001;\n        best_move[l_i + 1][r_i + 1] = kReplace;\n      }\n    }\n  }\n\n  // Reconstruct the best path. We do it in reverse order.\n  std::vector<EditType> best_path;\n  for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {\n    EditType move = best_move[l_i][r_i];\n    best_path.push_back(move);\n    l_i -= move != kAdd;\n    r_i -= move != kRemove;\n  }\n  std::reverse(best_path.begin(), best_path.end());\n  return best_path;\n}\n\nnamespace {\n\n// Helper class to convert string into ids with deduplication.\nclass InternalStrings {\n public:\n  size_t GetId(const std::string& str) {\n    IdMap::iterator it = ids_.find(str);\n    if (it != ids_.end()) return it->second;\n    size_t id = ids_.size();\n    return ids_[str] = id;\n  }\n\n private:\n  typedef std::map<std::string, size_t> IdMap;\n  IdMap ids_;\n};\n\n}  // namespace\n\nstd::vector<EditType> CalculateOptimalEdits(\n    const std::vector<std::string>& left,\n    const std::vector<std::string>& right) {\n  std::vector<size_t> left_ids, right_ids;\n  {\n    InternalStrings intern_table;\n    for (size_t i = 0; i < left.size(); ++i) {\n      left_ids.push_back(intern_table.GetId(left[i]));\n    }\n    for (size_t i = 0; i < right.size(); ++i) {\n      right_ids.push_back(intern_table.GetId(right[i]));\n    }\n  }\n  return CalculateOptimalEdits(left_ids, right_ids);\n}\n\nnamespace {\n\n// Helper class that holds the state for one hunk and prints it out to the\n// stream.\n// It reorders adds/removes when possible to group all removes before all\n// adds. It also adds the hunk header before printint into the stream.\nclass Hunk {\n public:\n  Hunk(size_t left_start, size_t right_start)\n      : left_start_(left_start),\n        right_start_(right_start),\n        adds_(),\n        removes_(),\n        common_() {}\n\n  void PushLine(char edit, const char* line) {\n    switch (edit) {\n      case ' ':\n        ++common_;\n        FlushEdits();\n        hunk_.push_back(std::make_pair(' ', line));\n        break;\n      case '-':\n        ++removes_;\n        hunk_removes_.push_back(std::make_pair('-', line));\n        break;\n      case '+':\n        ++adds_;\n        hunk_adds_.push_back(std::make_pair('+', line));\n        break;\n    }\n  }\n\n  void PrintTo(std::ostream* os) {\n    PrintHeader(os);\n    FlushEdits();\n    for (std::list<std::pair<char, const char*> >::const_iterator it =\n             hunk_.begin();\n         it != hunk_.end(); ++it) {\n      *os << it->first << it->second << \"\\n\";\n    }\n  }\n\n  bool has_edits() const { return adds_ || removes_; }\n\n private:\n  void FlushEdits() {\n    hunk_.splice(hunk_.end(), hunk_removes_);\n    hunk_.splice(hunk_.end(), hunk_adds_);\n  }\n\n  // Print a unified diff header for one hunk.\n  // The format is\n  //   \"@@ -<left_start>,<left_length> +<right_start>,<right_length> @@\"\n  // where the left/right parts are omitted if unnecessary.\n  void PrintHeader(std::ostream* ss) const {\n    *ss << \"@@ \";\n    if (removes_) {\n      *ss << \"-\" << left_start_ << \",\" << (removes_ + common_);\n    }\n    if (removes_ && adds_) {\n      *ss << \" \";\n    }\n    if (adds_) {\n      *ss << \"+\" << right_start_ << \",\" << (adds_ + common_);\n    }\n    *ss << \" @@\\n\";\n  }\n\n  size_t left_start_, right_start_;\n  size_t adds_, removes_, common_;\n  std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;\n};\n\n}  // namespace\n\n// Create a list of diff hunks in Unified diff format.\n// Each hunk has a header generated by PrintHeader above plus a body with\n// lines prefixed with ' ' for no change, '-' for deletion and '+' for\n// addition.\n// 'context' represents the desired unchanged prefix/suffix around the diff.\n// If two hunks are close enough that their contexts overlap, then they are\n// joined into one hunk.\nstd::string CreateUnifiedDiff(const std::vector<std::string>& left,\n                              const std::vector<std::string>& right,\n                              size_t context) {\n  const std::vector<EditType> edits = CalculateOptimalEdits(left, right);\n\n  size_t l_i = 0, r_i = 0, edit_i = 0;\n  std::stringstream ss;\n  while (edit_i < edits.size()) {\n    // Find first edit.\n    while (edit_i < edits.size() && edits[edit_i] == kMatch) {\n      ++l_i;\n      ++r_i;\n      ++edit_i;\n    }\n\n    // Find the first line to include in the hunk.\n    const size_t prefix_context = std::min(l_i, context);\n    Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);\n    for (size_t i = prefix_context; i > 0; --i) {\n      hunk.PushLine(' ', left[l_i - i].c_str());\n    }\n\n    // Iterate the edits until we found enough suffix for the hunk or the input\n    // is over.\n    size_t n_suffix = 0;\n    for (; edit_i < edits.size(); ++edit_i) {\n      if (n_suffix >= context) {\n        // Continue only if the next hunk is very close.\n        auto it = edits.begin() + static_cast<int>(edit_i);\n        while (it != edits.end() && *it == kMatch) ++it;\n        if (it == edits.end() ||\n            static_cast<size_t>(it - edits.begin()) - edit_i >= context) {\n          // There is no next edit or it is too far away.\n          break;\n        }\n      }\n\n      EditType edit = edits[edit_i];\n      // Reset count when a non match is found.\n      n_suffix = edit == kMatch ? n_suffix + 1 : 0;\n\n      if (edit == kMatch || edit == kRemove || edit == kReplace) {\n        hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());\n      }\n      if (edit == kAdd || edit == kReplace) {\n        hunk.PushLine('+', right[r_i].c_str());\n      }\n\n      // Advance indices, depending on edit type.\n      l_i += edit != kAdd;\n      r_i += edit != kRemove;\n    }\n\n    if (!hunk.has_edits()) {\n      // We are done. We don't want this hunk.\n      break;\n    }\n\n    hunk.PrintTo(&ss);\n  }\n  return ss.str();\n}\n\n}  // namespace edit_distance\n\nnamespace {\n\n// The string representation of the values received in EqFailure() are already\n// escaped. Split them on escaped '\\n' boundaries. Leave all other escaped\n// characters the same.\nstd::vector<std::string> SplitEscapedString(const std::string& str) {\n  std::vector<std::string> lines;\n  size_t start = 0, end = str.size();\n  if (end > 2 && str[0] == '\"' && str[end - 1] == '\"') {\n    ++start;\n    --end;\n  }\n  bool escaped = false;\n  for (size_t i = start; i + 1 < end; ++i) {\n    if (escaped) {\n      escaped = false;\n      if (str[i] == 'n') {\n        lines.push_back(str.substr(start, i - start - 1));\n        start = i + 1;\n      }\n    } else {\n      escaped = str[i] == '\\\\';\n    }\n  }\n  lines.push_back(str.substr(start, end - start));\n  return lines;\n}\n\n}  // namespace\n\n// Constructs and returns the message for an equality assertion\n// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.\n//\n// The first four parameters are the expressions used in the assertion\n// and their values, as strings.  For example, for ASSERT_EQ(foo, bar)\n// where foo is 5 and bar is 6, we have:\n//\n//   lhs_expression: \"foo\"\n//   rhs_expression: \"bar\"\n//   lhs_value:      \"5\"\n//   rhs_value:      \"6\"\n//\n// The ignoring_case parameter is true if and only if the assertion is a\n// *_STRCASEEQ*.  When it's true, the string \"Ignoring case\" will\n// be inserted into the message.\nAssertionResult EqFailure(const char* lhs_expression,\n                          const char* rhs_expression,\n                          const std::string& lhs_value,\n                          const std::string& rhs_value, bool ignoring_case) {\n  Message msg;\n  msg << \"Expected equality of these values:\";\n  msg << \"\\n  \" << lhs_expression;\n  if (lhs_value != lhs_expression) {\n    msg << \"\\n    Which is: \" << lhs_value;\n  }\n  msg << \"\\n  \" << rhs_expression;\n  if (rhs_value != rhs_expression) {\n    msg << \"\\n    Which is: \" << rhs_value;\n  }\n\n  if (ignoring_case) {\n    msg << \"\\nIgnoring case\";\n  }\n\n  if (!lhs_value.empty() && !rhs_value.empty()) {\n    const std::vector<std::string> lhs_lines = SplitEscapedString(lhs_value);\n    const std::vector<std::string> rhs_lines = SplitEscapedString(rhs_value);\n    if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {\n      msg << \"\\nWith diff:\\n\"\n          << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);\n    }\n  }\n\n  return AssertionFailure() << msg;\n}\n\n// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.\nstd::string GetBoolAssertionFailureMessage(\n    const AssertionResult& assertion_result, const char* expression_text,\n    const char* actual_predicate_value, const char* expected_predicate_value) {\n  const char* actual_message = assertion_result.message();\n  Message msg;\n  msg << \"Value of: \" << expression_text\n      << \"\\n  Actual: \" << actual_predicate_value;\n  if (actual_message[0] != '\\0') msg << \" (\" << actual_message << \")\";\n  msg << \"\\nExpected: \" << expected_predicate_value;\n  return msg.GetString();\n}\n\n// Helper function for implementing ASSERT_NEAR.\nAssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2,\n                                     const char* abs_error_expr, double val1,\n                                     double val2, double abs_error) {\n  const double diff = fabs(val1 - val2);\n  if (diff <= abs_error) return AssertionSuccess();\n\n  // Find the value which is closest to zero.\n  const double min_abs = std::min(fabs(val1), fabs(val2));\n  // Find the distance to the next double from that value.\n  const double epsilon =\n      nextafter(min_abs, std::numeric_limits<double>::infinity()) - min_abs;\n  // Detect the case where abs_error is so small that EXPECT_NEAR is\n  // effectively the same as EXPECT_EQUAL, and give an informative error\n  // message so that the situation can be more easily understood without\n  // requiring exotic floating-point knowledge.\n  // Don't do an epsilon check if abs_error is zero because that implies\n  // that an equality check was actually intended.\n  if (!(std::isnan)(val1) && !(std::isnan)(val2) && abs_error > 0 &&\n      abs_error < epsilon) {\n    return AssertionFailure()\n           << \"The difference between \" << expr1 << \" and \" << expr2 << \" is \"\n           << diff << \", where\\n\"\n           << expr1 << \" evaluates to \" << val1 << \",\\n\"\n           << expr2 << \" evaluates to \" << val2 << \".\\nThe abs_error parameter \"\n           << abs_error_expr << \" evaluates to \" << abs_error\n           << \" which is smaller than the minimum distance between doubles for \"\n              \"numbers of this magnitude which is \"\n           << epsilon\n           << \", thus making this EXPECT_NEAR check equivalent to \"\n              \"EXPECT_EQUAL. Consider using EXPECT_DOUBLE_EQ instead.\";\n  }\n  return AssertionFailure()\n         << \"The difference between \" << expr1 << \" and \" << expr2 << \" is \"\n         << diff << \", which exceeds \" << abs_error_expr << \", where\\n\"\n         << expr1 << \" evaluates to \" << val1 << \",\\n\"\n         << expr2 << \" evaluates to \" << val2 << \", and\\n\"\n         << abs_error_expr << \" evaluates to \" << abs_error << \".\";\n}\n\n// Helper template for implementing FloatLE() and DoubleLE().\ntemplate <typename RawType>\nAssertionResult FloatingPointLE(const char* expr1, const char* expr2,\n                                RawType val1, RawType val2) {\n  // Returns success if val1 is less than val2,\n  if (val1 < val2) {\n    return AssertionSuccess();\n  }\n\n  // or if val1 is almost equal to val2.\n  const FloatingPoint<RawType> lhs(val1), rhs(val2);\n  if (lhs.AlmostEquals(rhs)) {\n    return AssertionSuccess();\n  }\n\n  // Note that the above two checks will both fail if either val1 or\n  // val2 is NaN, as the IEEE floating-point standard requires that\n  // any predicate involving a NaN must return false.\n\n  ::std::stringstream val1_ss;\n  val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)\n          << val1;\n\n  ::std::stringstream val2_ss;\n  val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)\n          << val2;\n\n  return AssertionFailure()\n         << \"Expected: (\" << expr1 << \") <= (\" << expr2 << \")\\n\"\n         << \"  Actual: \" << StringStreamToString(&val1_ss) << \" vs \"\n         << StringStreamToString(&val2_ss);\n}\n\n}  // namespace internal\n\n// Asserts that val1 is less than, or almost equal to, val2.  Fails\n// otherwise.  In particular, it fails if either val1 or val2 is NaN.\nAssertionResult FloatLE(const char* expr1, const char* expr2, float val1,\n                        float val2) {\n  return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);\n}\n\n// Asserts that val1 is less than, or almost equal to, val2.  Fails\n// otherwise.  In particular, it fails if either val1 or val2 is NaN.\nAssertionResult DoubleLE(const char* expr1, const char* expr2, double val1,\n                         double val2) {\n  return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);\n}\n\nnamespace internal {\n\n// The helper function for {ASSERT|EXPECT}_STREQ.\nAssertionResult CmpHelperSTREQ(const char* lhs_expression,\n                               const char* rhs_expression, const char* lhs,\n                               const char* rhs) {\n  if (String::CStringEquals(lhs, rhs)) {\n    return AssertionSuccess();\n  }\n\n  return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),\n                   PrintToString(rhs), false);\n}\n\n// The helper function for {ASSERT|EXPECT}_STRCASEEQ.\nAssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,\n                                   const char* rhs_expression, const char* lhs,\n                                   const char* rhs) {\n  if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {\n    return AssertionSuccess();\n  }\n\n  return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),\n                   PrintToString(rhs), true);\n}\n\n// The helper function for {ASSERT|EXPECT}_STRNE.\nAssertionResult CmpHelperSTRNE(const char* s1_expression,\n                               const char* s2_expression, const char* s1,\n                               const char* s2) {\n  if (!String::CStringEquals(s1, s2)) {\n    return AssertionSuccess();\n  } else {\n    return AssertionFailure()\n           << \"Expected: (\" << s1_expression << \") != (\" << s2_expression\n           << \"), actual: \\\"\" << s1 << \"\\\" vs \\\"\" << s2 << \"\\\"\";\n  }\n}\n\n// The helper function for {ASSERT|EXPECT}_STRCASENE.\nAssertionResult CmpHelperSTRCASENE(const char* s1_expression,\n                                   const char* s2_expression, const char* s1,\n                                   const char* s2) {\n  if (!String::CaseInsensitiveCStringEquals(s1, s2)) {\n    return AssertionSuccess();\n  } else {\n    return AssertionFailure()\n           << \"Expected: (\" << s1_expression << \") != (\" << s2_expression\n           << \") (ignoring case), actual: \\\"\" << s1 << \"\\\" vs \\\"\" << s2 << \"\\\"\";\n  }\n}\n\n}  // namespace internal\n\nnamespace {\n\n// Helper functions for implementing IsSubString() and IsNotSubstring().\n\n// This group of overloaded functions return true if and only if needle\n// is a substring of haystack.  NULL is considered a substring of\n// itself only.\n\nbool IsSubstringPred(const char* needle, const char* haystack) {\n  if (needle == nullptr || haystack == nullptr) return needle == haystack;\n\n  return strstr(haystack, needle) != nullptr;\n}\n\nbool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {\n  if (needle == nullptr || haystack == nullptr) return needle == haystack;\n\n  return wcsstr(haystack, needle) != nullptr;\n}\n\n// StringType here can be either ::std::string or ::std::wstring.\ntemplate <typename StringType>\nbool IsSubstringPred(const StringType& needle, const StringType& haystack) {\n  return haystack.find(needle) != StringType::npos;\n}\n\n// This function implements either IsSubstring() or IsNotSubstring(),\n// depending on the value of the expected_to_be_substring parameter.\n// StringType here can be const char*, const wchar_t*, ::std::string,\n// or ::std::wstring.\ntemplate <typename StringType>\nAssertionResult IsSubstringImpl(bool expected_to_be_substring,\n                                const char* needle_expr,\n                                const char* haystack_expr,\n                                const StringType& needle,\n                                const StringType& haystack) {\n  if (IsSubstringPred(needle, haystack) == expected_to_be_substring)\n    return AssertionSuccess();\n\n  const bool is_wide_string = sizeof(needle[0]) > 1;\n  const char* const begin_string_quote = is_wide_string ? \"L\\\"\" : \"\\\"\";\n  return AssertionFailure()\n         << \"Value of: \" << needle_expr << \"\\n\"\n         << \"  Actual: \" << begin_string_quote << needle << \"\\\"\\n\"\n         << \"Expected: \" << (expected_to_be_substring ? \"\" : \"not \")\n         << \"a substring of \" << haystack_expr << \"\\n\"\n         << \"Which is: \" << begin_string_quote << haystack << \"\\\"\";\n}\n\n}  // namespace\n\n// IsSubstring() and IsNotSubstring() check whether needle is a\n// substring of haystack (NULL is considered a substring of itself\n// only), and return an appropriate error message when they fail.\n\nAssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,\n                            const char* needle, const char* haystack) {\n  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);\n}\n\nAssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,\n                            const wchar_t* needle, const wchar_t* haystack) {\n  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);\n}\n\nAssertionResult IsNotSubstring(const char* needle_expr,\n                               const char* haystack_expr, const char* needle,\n                               const char* haystack) {\n  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);\n}\n\nAssertionResult IsNotSubstring(const char* needle_expr,\n                               const char* haystack_expr, const wchar_t* needle,\n                               const wchar_t* haystack) {\n  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);\n}\n\nAssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,\n                            const ::std::string& needle,\n                            const ::std::string& haystack) {\n  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);\n}\n\nAssertionResult IsNotSubstring(const char* needle_expr,\n                               const char* haystack_expr,\n                               const ::std::string& needle,\n                               const ::std::string& haystack) {\n  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);\n}\n\n#if GTEST_HAS_STD_WSTRING\nAssertionResult IsSubstring(const char* needle_expr, const char* haystack_expr,\n                            const ::std::wstring& needle,\n                            const ::std::wstring& haystack) {\n  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);\n}\n\nAssertionResult IsNotSubstring(const char* needle_expr,\n                               const char* haystack_expr,\n                               const ::std::wstring& needle,\n                               const ::std::wstring& haystack) {\n  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);\n}\n#endif  // GTEST_HAS_STD_WSTRING\n\nnamespace internal {\n\n#if GTEST_OS_WINDOWS\n\nnamespace {\n\n// Helper function for IsHRESULT{SuccessFailure} predicates\nAssertionResult HRESULTFailureHelper(const char* expr, const char* expected,\n                                     long hr) {  // NOLINT\n#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_TV_TITLE\n\n  // Windows CE doesn't support FormatMessage.\n  const char error_text[] = \"\";\n\n#else\n\n  // Looks up the human-readable system message for the HRESULT code\n  // and since we're not passing any params to FormatMessage, we don't\n  // want inserts expanded.\n  const DWORD kFlags =\n      FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;\n  const DWORD kBufSize = 4096;\n  // Gets the system's human readable message string for this HRESULT.\n  char error_text[kBufSize] = {'\\0'};\n  DWORD message_length = ::FormatMessageA(kFlags,\n                                          0,  // no source, we're asking system\n                                          static_cast<DWORD>(hr),  // the error\n                                          0,  // no line width restrictions\n                                          error_text,  // output buffer\n                                          kBufSize,    // buf size\n                                          nullptr);  // no arguments for inserts\n  // Trims tailing white space (FormatMessage leaves a trailing CR-LF)\n  for (; message_length && IsSpace(error_text[message_length - 1]);\n       --message_length) {\n    error_text[message_length - 1] = '\\0';\n  }\n\n#endif  // GTEST_OS_WINDOWS_MOBILE\n\n  const std::string error_hex(\"0x\" + String::FormatHexInt(hr));\n  return ::testing::AssertionFailure()\n         << \"Expected: \" << expr << \" \" << expected << \".\\n\"\n         << \"  Actual: \" << error_hex << \" \" << error_text << \"\\n\";\n}\n\n}  // namespace\n\nAssertionResult IsHRESULTSuccess(const char* expr, long hr) {  // NOLINT\n  if (SUCCEEDED(hr)) {\n    return AssertionSuccess();\n  }\n  return HRESULTFailureHelper(expr, \"succeeds\", hr);\n}\n\nAssertionResult IsHRESULTFailure(const char* expr, long hr) {  // NOLINT\n  if (FAILED(hr)) {\n    return AssertionSuccess();\n  }\n  return HRESULTFailureHelper(expr, \"fails\", hr);\n}\n\n#endif  // GTEST_OS_WINDOWS\n\n// Utility functions for encoding Unicode text (wide strings) in\n// UTF-8.\n\n// A Unicode code-point can have up to 21 bits, and is encoded in UTF-8\n// like this:\n//\n// Code-point length   Encoding\n//   0 -  7 bits       0xxxxxxx\n//   8 - 11 bits       110xxxxx 10xxxxxx\n//  12 - 16 bits       1110xxxx 10xxxxxx 10xxxxxx\n//  17 - 21 bits       11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n\n// The maximum code-point a one-byte UTF-8 sequence can represent.\nconstexpr uint32_t kMaxCodePoint1 = (static_cast<uint32_t>(1) << 7) - 1;\n\n// The maximum code-point a two-byte UTF-8 sequence can represent.\nconstexpr uint32_t kMaxCodePoint2 = (static_cast<uint32_t>(1) << (5 + 6)) - 1;\n\n// The maximum code-point a three-byte UTF-8 sequence can represent.\nconstexpr uint32_t kMaxCodePoint3 =\n    (static_cast<uint32_t>(1) << (4 + 2 * 6)) - 1;\n\n// The maximum code-point a four-byte UTF-8 sequence can represent.\nconstexpr uint32_t kMaxCodePoint4 =\n    (static_cast<uint32_t>(1) << (3 + 3 * 6)) - 1;\n\n// Chops off the n lowest bits from a bit pattern.  Returns the n\n// lowest bits.  As a side effect, the original bit pattern will be\n// shifted to the right by n bits.\ninline uint32_t ChopLowBits(uint32_t* bits, int n) {\n  const uint32_t low_bits = *bits & ((static_cast<uint32_t>(1) << n) - 1);\n  *bits >>= n;\n  return low_bits;\n}\n\n// Converts a Unicode code point to a narrow string in UTF-8 encoding.\n// code_point parameter is of type uint32_t because wchar_t may not be\n// wide enough to contain a code point.\n// If the code_point is not a valid Unicode code point\n// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted\n// to \"(Invalid Unicode 0xXXXXXXXX)\".\nstd::string CodePointToUtf8(uint32_t code_point) {\n  if (code_point > kMaxCodePoint4) {\n    return \"(Invalid Unicode 0x\" + String::FormatHexUInt32(code_point) + \")\";\n  }\n\n  char str[5];  // Big enough for the largest valid code point.\n  if (code_point <= kMaxCodePoint1) {\n    str[1] = '\\0';\n    str[0] = static_cast<char>(code_point);  // 0xxxxxxx\n  } else if (code_point <= kMaxCodePoint2) {\n    str[2] = '\\0';\n    str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx\n    str[0] = static_cast<char>(0xC0 | code_point);                   // 110xxxxx\n  } else if (code_point <= kMaxCodePoint3) {\n    str[3] = '\\0';\n    str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx\n    str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx\n    str[0] = static_cast<char>(0xE0 | code_point);                   // 1110xxxx\n  } else {  // code_point <= kMaxCodePoint4\n    str[4] = '\\0';\n    str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx\n    str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx\n    str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx\n    str[0] = static_cast<char>(0xF0 | code_point);                   // 11110xxx\n  }\n  return str;\n}\n\n// The following two functions only make sense if the system\n// uses UTF-16 for wide string encoding. All supported systems\n// with 16 bit wchar_t (Windows, Cygwin) do use UTF-16.\n\n// Determines if the arguments constitute UTF-16 surrogate pair\n// and thus should be combined into a single Unicode code point\n// using CreateCodePointFromUtf16SurrogatePair.\ninline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {\n  return sizeof(wchar_t) == 2 && (first & 0xFC00) == 0xD800 &&\n         (second & 0xFC00) == 0xDC00;\n}\n\n// Creates a Unicode code point from UTF16 surrogate pair.\ninline uint32_t CreateCodePointFromUtf16SurrogatePair(wchar_t first,\n                                                      wchar_t second) {\n  const auto first_u = static_cast<uint32_t>(first);\n  const auto second_u = static_cast<uint32_t>(second);\n  const uint32_t mask = (1 << 10) - 1;\n  return (sizeof(wchar_t) == 2)\n             ? (((first_u & mask) << 10) | (second_u & mask)) + 0x10000\n             :\n             // This function should not be called when the condition is\n             // false, but we provide a sensible default in case it is.\n             first_u;\n}\n\n// Converts a wide string to a narrow string in UTF-8 encoding.\n// The wide string is assumed to have the following encoding:\n//   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin)\n//   UTF-32 if sizeof(wchar_t) == 4 (on Linux)\n// Parameter str points to a null-terminated wide string.\n// Parameter num_chars may additionally limit the number\n// of wchar_t characters processed. -1 is used when the entire string\n// should be processed.\n// If the string contains code points that are not valid Unicode code points\n// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output\n// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding\n// and contains invalid UTF-16 surrogate pairs, values in those pairs\n// will be encoded as individual Unicode characters from Basic Normal Plane.\nstd::string WideStringToUtf8(const wchar_t* str, int num_chars) {\n  if (num_chars == -1) num_chars = static_cast<int>(wcslen(str));\n\n  ::std::stringstream stream;\n  for (int i = 0; i < num_chars; ++i) {\n    uint32_t unicode_code_point;\n\n    if (str[i] == L'\\0') {\n      break;\n    } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {\n      unicode_code_point =\n          CreateCodePointFromUtf16SurrogatePair(str[i], str[i + 1]);\n      i++;\n    } else {\n      unicode_code_point = static_cast<uint32_t>(str[i]);\n    }\n\n    stream << CodePointToUtf8(unicode_code_point);\n  }\n  return StringStreamToString(&stream);\n}\n\n// Converts a wide C string to an std::string using the UTF-8 encoding.\n// NULL will be converted to \"(null)\".\nstd::string String::ShowWideCString(const wchar_t* wide_c_str) {\n  if (wide_c_str == nullptr) return \"(null)\";\n\n  return internal::WideStringToUtf8(wide_c_str, -1);\n}\n\n// Compares two wide C strings.  Returns true if and only if they have the\n// same content.\n//\n// Unlike wcscmp(), this function can handle NULL argument(s).  A NULL\n// C string is considered different to any non-NULL C string,\n// including the empty string.\nbool String::WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs) {\n  if (lhs == nullptr) return rhs == nullptr;\n\n  if (rhs == nullptr) return false;\n\n  return wcscmp(lhs, rhs) == 0;\n}\n\n// Helper function for *_STREQ on wide strings.\nAssertionResult CmpHelperSTREQ(const char* lhs_expression,\n                               const char* rhs_expression, const wchar_t* lhs,\n                               const wchar_t* rhs) {\n  if (String::WideCStringEquals(lhs, rhs)) {\n    return AssertionSuccess();\n  }\n\n  return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs),\n                   PrintToString(rhs), false);\n}\n\n// Helper function for *_STRNE on wide strings.\nAssertionResult CmpHelperSTRNE(const char* s1_expression,\n                               const char* s2_expression, const wchar_t* s1,\n                               const wchar_t* s2) {\n  if (!String::WideCStringEquals(s1, s2)) {\n    return AssertionSuccess();\n  }\n\n  return AssertionFailure()\n         << \"Expected: (\" << s1_expression << \") != (\" << s2_expression\n         << \"), actual: \" << PrintToString(s1) << \" vs \" << PrintToString(s2);\n}\n\n// Compares two C strings, ignoring case.  Returns true if and only if they have\n// the same content.\n//\n// Unlike strcasecmp(), this function can handle NULL argument(s).  A\n// NULL C string is considered different to any non-NULL C string,\n// including the empty string.\nbool String::CaseInsensitiveCStringEquals(const char* lhs, const char* rhs) {\n  if (lhs == nullptr) return rhs == nullptr;\n  if (rhs == nullptr) return false;\n  return posix::StrCaseCmp(lhs, rhs) == 0;\n}\n\n// Compares two wide C strings, ignoring case.  Returns true if and only if they\n// have the same content.\n//\n// Unlike wcscasecmp(), this function can handle NULL argument(s).\n// A NULL C string is considered different to any non-NULL wide C string,\n// including the empty string.\n// NB: The implementations on different platforms slightly differ.\n// On windows, this method uses _wcsicmp which compares according to LC_CTYPE\n// environment variable. On GNU platform this method uses wcscasecmp\n// which compares according to LC_CTYPE category of the current locale.\n// On MacOS X, it uses towlower, which also uses LC_CTYPE category of the\n// current locale.\nbool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,\n                                              const wchar_t* rhs) {\n  if (lhs == nullptr) return rhs == nullptr;\n\n  if (rhs == nullptr) return false;\n\n#if GTEST_OS_WINDOWS\n  return _wcsicmp(lhs, rhs) == 0;\n#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID\n  return wcscasecmp(lhs, rhs) == 0;\n#else\n  // Android, Mac OS X and Cygwin don't define wcscasecmp.\n  // Other unknown OSes may not define it either.\n  wint_t left, right;\n  do {\n    left = towlower(static_cast<wint_t>(*lhs++));\n    right = towlower(static_cast<wint_t>(*rhs++));\n  } while (left && left == right);\n  return left == right;\n#endif  // OS selector\n}\n\n// Returns true if and only if str ends with the given suffix, ignoring case.\n// Any string is considered to end with an empty suffix.\nbool String::EndsWithCaseInsensitive(const std::string& str,\n                                     const std::string& suffix) {\n  const size_t str_len = str.length();\n  const size_t suffix_len = suffix.length();\n  return (str_len >= suffix_len) &&\n         CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,\n                                      suffix.c_str());\n}\n\n// Formats an int value as \"%02d\".\nstd::string String::FormatIntWidth2(int value) {\n  return FormatIntWidthN(value, 2);\n}\n\n// Formats an int value to given width with leading zeros.\nstd::string String::FormatIntWidthN(int value, int width) {\n  std::stringstream ss;\n  ss << std::setfill('0') << std::setw(width) << value;\n  return ss.str();\n}\n\n// Formats an int value as \"%X\".\nstd::string String::FormatHexUInt32(uint32_t value) {\n  std::stringstream ss;\n  ss << std::hex << std::uppercase << value;\n  return ss.str();\n}\n\n// Formats an int value as \"%X\".\nstd::string String::FormatHexInt(int value) {\n  return FormatHexUInt32(static_cast<uint32_t>(value));\n}\n\n// Formats a byte as \"%02X\".\nstd::string String::FormatByte(unsigned char value) {\n  std::stringstream ss;\n  ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase\n     << static_cast<unsigned int>(value);\n  return ss.str();\n}\n\n// Converts the buffer in a stringstream to an std::string, converting NUL\n// bytes to \"\\\\0\" along the way.\nstd::string StringStreamToString(::std::stringstream* ss) {\n  const ::std::string& str = ss->str();\n  const char* const start = str.c_str();\n  const char* const end = start + str.length();\n\n  std::string result;\n  result.reserve(static_cast<size_t>(2 * (end - start)));\n  for (const char* ch = start; ch != end; ++ch) {\n    if (*ch == '\\0') {\n      result += \"\\\\0\";  // Replaces NUL with \"\\\\0\";\n    } else {\n      result += *ch;\n    }\n  }\n\n  return result;\n}\n\n// Appends the user-supplied message to the Google-Test-generated message.\nstd::string AppendUserMessage(const std::string& gtest_msg,\n                              const Message& user_msg) {\n  // Appends the user message if it's non-empty.\n  const std::string user_msg_string = user_msg.GetString();\n  if (user_msg_string.empty()) {\n    return gtest_msg;\n  }\n  if (gtest_msg.empty()) {\n    return user_msg_string;\n  }\n  return gtest_msg + \"\\n\" + user_msg_string;\n}\n\n}  // namespace internal\n\n// class TestResult\n\n// Creates an empty TestResult.\nTestResult::TestResult()\n    : death_test_count_(0), start_timestamp_(0), elapsed_time_(0) {}\n\n// D'tor.\nTestResult::~TestResult() {}\n\n// Returns the i-th test part result among all the results. i can\n// range from 0 to total_part_count() - 1. If i is not in that range,\n// aborts the program.\nconst TestPartResult& TestResult::GetTestPartResult(int i) const {\n  if (i < 0 || i >= total_part_count()) internal::posix::Abort();\n  return test_part_results_.at(static_cast<size_t>(i));\n}\n\n// Returns the i-th test property. i can range from 0 to\n// test_property_count() - 1. If i is not in that range, aborts the\n// program.\nconst TestProperty& TestResult::GetTestProperty(int i) const {\n  if (i < 0 || i >= test_property_count()) internal::posix::Abort();\n  return test_properties_.at(static_cast<size_t>(i));\n}\n\n// Clears the test part results.\nvoid TestResult::ClearTestPartResults() { test_part_results_.clear(); }\n\n// Adds a test part result to the list.\nvoid TestResult::AddTestPartResult(const TestPartResult& test_part_result) {\n  test_part_results_.push_back(test_part_result);\n}\n\n// Adds a test property to the list. If a property with the same key as the\n// supplied property is already represented, the value of this test_property\n// replaces the old value for that key.\nvoid TestResult::RecordProperty(const std::string& xml_element,\n                                const TestProperty& test_property) {\n  if (!ValidateTestProperty(xml_element, test_property)) {\n    return;\n  }\n  internal::MutexLock lock(&test_properties_mutex_);\n  const std::vector<TestProperty>::iterator property_with_matching_key =\n      std::find_if(test_properties_.begin(), test_properties_.end(),\n                   internal::TestPropertyKeyIs(test_property.key()));\n  if (property_with_matching_key == test_properties_.end()) {\n    test_properties_.push_back(test_property);\n    return;\n  }\n  property_with_matching_key->SetValue(test_property.value());\n}\n\n// The list of reserved attributes used in the <testsuites> element of XML\n// output.\nstatic const char* const kReservedTestSuitesAttributes[] = {\n    \"disabled\",    \"errors\", \"failures\", \"name\",\n    \"random_seed\", \"tests\",  \"time\",     \"timestamp\"};\n\n// The list of reserved attributes used in the <testsuite> element of XML\n// output.\nstatic const char* const kReservedTestSuiteAttributes[] = {\n    \"disabled\", \"errors\", \"failures\",  \"name\",\n    \"tests\",    \"time\",   \"timestamp\", \"skipped\"};\n\n// The list of reserved attributes used in the <testcase> element of XML output.\nstatic const char* const kReservedTestCaseAttributes[] = {\n    \"classname\",  \"name\",        \"status\", \"time\",\n    \"type_param\", \"value_param\", \"file\",   \"line\"};\n\n// Use a slightly different set for allowed output to ensure existing tests can\n// still RecordProperty(\"result\") or \"RecordProperty(timestamp\")\nstatic const char* const kReservedOutputTestCaseAttributes[] = {\n    \"classname\",   \"name\", \"status\", \"time\",   \"type_param\",\n    \"value_param\", \"file\", \"line\",   \"result\", \"timestamp\"};\n\ntemplate <size_t kSize>\nstd::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {\n  return std::vector<std::string>(array, array + kSize);\n}\n\nstatic std::vector<std::string> GetReservedAttributesForElement(\n    const std::string& xml_element) {\n  if (xml_element == \"testsuites\") {\n    return ArrayAsVector(kReservedTestSuitesAttributes);\n  } else if (xml_element == \"testsuite\") {\n    return ArrayAsVector(kReservedTestSuiteAttributes);\n  } else if (xml_element == \"testcase\") {\n    return ArrayAsVector(kReservedTestCaseAttributes);\n  } else {\n    GTEST_CHECK_(false) << \"Unrecognized xml_element provided: \" << xml_element;\n  }\n  // This code is unreachable but some compilers may not realizes that.\n  return std::vector<std::string>();\n}\n\n// TODO(jdesprez): Merge the two getReserved attributes once skip is improved\nstatic std::vector<std::string> GetReservedOutputAttributesForElement(\n    const std::string& xml_element) {\n  if (xml_element == \"testsuites\") {\n    return ArrayAsVector(kReservedTestSuitesAttributes);\n  } else if (xml_element == \"testsuite\") {\n    return ArrayAsVector(kReservedTestSuiteAttributes);\n  } else if (xml_element == \"testcase\") {\n    return ArrayAsVector(kReservedOutputTestCaseAttributes);\n  } else {\n    GTEST_CHECK_(false) << \"Unrecognized xml_element provided: \" << xml_element;\n  }\n  // This code is unreachable but some compilers may not realizes that.\n  return std::vector<std::string>();\n}\n\nstatic std::string FormatWordList(const std::vector<std::string>& words) {\n  Message word_list;\n  for (size_t i = 0; i < words.size(); ++i) {\n    if (i > 0 && words.size() > 2) {\n      word_list << \", \";\n    }\n    if (i == words.size() - 1) {\n      word_list << \"and \";\n    }\n    word_list << \"'\" << words[i] << \"'\";\n  }\n  return word_list.GetString();\n}\n\nstatic bool ValidateTestPropertyName(\n    const std::string& property_name,\n    const std::vector<std::string>& reserved_names) {\n  if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=\n      reserved_names.end()) {\n    ADD_FAILURE() << \"Reserved key used in RecordProperty(): \" << property_name\n                  << \" (\" << FormatWordList(reserved_names)\n                  << \" are reserved by \" << GTEST_NAME_ << \")\";\n    return false;\n  }\n  return true;\n}\n\n// Adds a failure if the key is a reserved attribute of the element named\n// xml_element.  Returns true if the property is valid.\nbool TestResult::ValidateTestProperty(const std::string& xml_element,\n                                      const TestProperty& test_property) {\n  return ValidateTestPropertyName(test_property.key(),\n                                  GetReservedAttributesForElement(xml_element));\n}\n\n// Clears the object.\nvoid TestResult::Clear() {\n  test_part_results_.clear();\n  test_properties_.clear();\n  death_test_count_ = 0;\n  elapsed_time_ = 0;\n}\n\n// Returns true off the test part was skipped.\nstatic bool TestPartSkipped(const TestPartResult& result) {\n  return result.skipped();\n}\n\n// Returns true if and only if the test was skipped.\nbool TestResult::Skipped() const {\n  return !Failed() && CountIf(test_part_results_, TestPartSkipped) > 0;\n}\n\n// Returns true if and only if the test failed.\nbool TestResult::Failed() const {\n  for (int i = 0; i < total_part_count(); ++i) {\n    if (GetTestPartResult(i).failed()) return true;\n  }\n  return false;\n}\n\n// Returns true if and only if the test part fatally failed.\nstatic bool TestPartFatallyFailed(const TestPartResult& result) {\n  return result.fatally_failed();\n}\n\n// Returns true if and only if the test fatally failed.\nbool TestResult::HasFatalFailure() const {\n  return CountIf(test_part_results_, TestPartFatallyFailed) > 0;\n}\n\n// Returns true if and only if the test part non-fatally failed.\nstatic bool TestPartNonfatallyFailed(const TestPartResult& result) {\n  return result.nonfatally_failed();\n}\n\n// Returns true if and only if the test has a non-fatal failure.\nbool TestResult::HasNonfatalFailure() const {\n  return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;\n}\n\n// Gets the number of all test parts.  This is the sum of the number\n// of successful test parts and the number of failed test parts.\nint TestResult::total_part_count() const {\n  return static_cast<int>(test_part_results_.size());\n}\n\n// Returns the number of the test properties.\nint TestResult::test_property_count() const {\n  return static_cast<int>(test_properties_.size());\n}\n\n// class Test\n\n// Creates a Test object.\n\n// The c'tor saves the states of all flags.\nTest::Test() : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {}\n\n// The d'tor restores the states of all flags.  The actual work is\n// done by the d'tor of the gtest_flag_saver_ field, and thus not\n// visible here.\nTest::~Test() {}\n\n// Sets up the test fixture.\n//\n// A sub-class may override this.\nvoid Test::SetUp() {}\n\n// Tears down the test fixture.\n//\n// A sub-class may override this.\nvoid Test::TearDown() {}\n\n// Allows user supplied key value pairs to be recorded for later output.\nvoid Test::RecordProperty(const std::string& key, const std::string& value) {\n  UnitTest::GetInstance()->RecordProperty(key, value);\n}\n\n// Allows user supplied key value pairs to be recorded for later output.\nvoid Test::RecordProperty(const std::string& key, int value) {\n  Message value_message;\n  value_message << value;\n  RecordProperty(key, value_message.GetString().c_str());\n}\n\nnamespace internal {\n\nvoid ReportFailureInUnknownLocation(TestPartResult::Type result_type,\n                                    const std::string& message) {\n  // This function is a friend of UnitTest and as such has access to\n  // AddTestPartResult.\n  UnitTest::GetInstance()->AddTestPartResult(\n      result_type,\n      nullptr,  // No info about the source file where the exception occurred.\n      -1,       // We have no info on which line caused the exception.\n      message,\n      \"\");  // No stack trace, either.\n}\n\n}  // namespace internal\n\n// Google Test requires all tests in the same test suite to use the same test\n// fixture class.  This function checks if the current test has the\n// same fixture class as the first test in the current test suite.  If\n// yes, it returns true; otherwise it generates a Google Test failure and\n// returns false.\nbool Test::HasSameFixtureClass() {\n  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\n  const TestSuite* const test_suite = impl->current_test_suite();\n\n  // Info about the first test in the current test suite.\n  const TestInfo* const first_test_info = test_suite->test_info_list()[0];\n  const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;\n  const char* const first_test_name = first_test_info->name();\n\n  // Info about the current test.\n  const TestInfo* const this_test_info = impl->current_test_info();\n  const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;\n  const char* const this_test_name = this_test_info->name();\n\n  if (this_fixture_id != first_fixture_id) {\n    // Is the first test defined using TEST?\n    const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();\n    // Is this test defined using TEST?\n    const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();\n\n    if (first_is_TEST || this_is_TEST) {\n      // Both TEST and TEST_F appear in same test suite, which is incorrect.\n      // Tell the user how to fix this.\n\n      // Gets the name of the TEST and the name of the TEST_F.  Note\n      // that first_is_TEST and this_is_TEST cannot both be true, as\n      // the fixture IDs are different for the two tests.\n      const char* const TEST_name =\n          first_is_TEST ? first_test_name : this_test_name;\n      const char* const TEST_F_name =\n          first_is_TEST ? this_test_name : first_test_name;\n\n      ADD_FAILURE()\n          << \"All tests in the same test suite must use the same test fixture\\n\"\n          << \"class, so mixing TEST_F and TEST in the same test suite is\\n\"\n          << \"illegal.  In test suite \" << this_test_info->test_suite_name()\n          << \",\\n\"\n          << \"test \" << TEST_F_name << \" is defined using TEST_F but\\n\"\n          << \"test \" << TEST_name << \" is defined using TEST.  You probably\\n\"\n          << \"want to change the TEST to TEST_F or move it to another test\\n\"\n          << \"case.\";\n    } else {\n      // Two fixture classes with the same name appear in two different\n      // namespaces, which is not allowed. Tell the user how to fix this.\n      ADD_FAILURE()\n          << \"All tests in the same test suite must use the same test fixture\\n\"\n          << \"class.  However, in test suite \"\n          << this_test_info->test_suite_name() << \",\\n\"\n          << \"you defined test \" << first_test_name << \" and test \"\n          << this_test_name << \"\\n\"\n          << \"using two different test fixture classes.  This can happen if\\n\"\n          << \"the two classes are from different namespaces or translation\\n\"\n          << \"units and have the same name.  You should probably rename one\\n\"\n          << \"of the classes to put the tests into different test suites.\";\n    }\n    return false;\n  }\n\n  return true;\n}\n\n#if GTEST_HAS_SEH\n\n// Adds an \"exception thrown\" fatal failure to the current test.  This\n// function returns its result via an output parameter pointer because VC++\n// prohibits creation of objects with destructors on stack in functions\n// using __try (see error C2712).\nstatic std::string* FormatSehExceptionMessage(DWORD exception_code,\n                                              const char* location) {\n  Message message;\n  message << \"SEH exception with code 0x\" << std::setbase(16) << exception_code\n          << std::setbase(10) << \" thrown in \" << location << \".\";\n\n  return new std::string(message.GetString());\n}\n\n#endif  // GTEST_HAS_SEH\n\nnamespace internal {\n\n#if GTEST_HAS_EXCEPTIONS\n\n// Adds an \"exception thrown\" fatal failure to the current test.\nstatic std::string FormatCxxExceptionMessage(const char* description,\n                                             const char* location) {\n  Message message;\n  if (description != nullptr) {\n    message << \"C++ exception with description \\\"\" << description << \"\\\"\";\n  } else {\n    message << \"Unknown C++ exception\";\n  }\n  message << \" thrown in \" << location << \".\";\n\n  return message.GetString();\n}\n\nstatic std::string PrintTestPartResultToString(\n    const TestPartResult& test_part_result);\n\nGoogleTestFailureException::GoogleTestFailureException(\n    const TestPartResult& failure)\n    : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}\n\n#endif  // GTEST_HAS_EXCEPTIONS\n\n// We put these helper functions in the internal namespace as IBM's xlC\n// compiler rejects the code if they were declared static.\n\n// Runs the given method and handles SEH exceptions it throws, when\n// SEH is supported; returns the 0-value for type Result in case of an\n// SEH exception.  (Microsoft compilers cannot handle SEH and C++\n// exceptions in the same function.  Therefore, we provide a separate\n// wrapper function for handling SEH exceptions.)\ntemplate <class T, typename Result>\nResult HandleSehExceptionsInMethodIfSupported(T* object, Result (T::*method)(),\n                                              const char* location) {\n#if GTEST_HAS_SEH\n  __try {\n    return (object->*method)();\n  } __except (internal::UnitTestOptions::GTestShouldProcessSEH(  // NOLINT\n      GetExceptionCode())) {\n    // We create the exception message on the heap because VC++ prohibits\n    // creation of objects with destructors on stack in functions using __try\n    // (see error C2712).\n    std::string* exception_message =\n        FormatSehExceptionMessage(GetExceptionCode(), location);\n    internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,\n                                             *exception_message);\n    delete exception_message;\n    return static_cast<Result>(0);\n  }\n#else\n  (void)location;\n  return (object->*method)();\n#endif  // GTEST_HAS_SEH\n}\n\n// Runs the given method and catches and reports C++ and/or SEH-style\n// exceptions, if they are supported; returns the 0-value for type\n// Result in case of an SEH exception.\ntemplate <class T, typename Result>\nResult HandleExceptionsInMethodIfSupported(T* object, Result (T::*method)(),\n                                           const char* location) {\n  // NOTE: The user code can affect the way in which Google Test handles\n  // exceptions by setting GTEST_FLAG(catch_exceptions), but only before\n  // RUN_ALL_TESTS() starts. It is technically possible to check the flag\n  // after the exception is caught and either report or re-throw the\n  // exception based on the flag's value:\n  //\n  // try {\n  //   // Perform the test method.\n  // } catch (...) {\n  //   if (GTEST_FLAG_GET(catch_exceptions))\n  //     // Report the exception as failure.\n  //   else\n  //     throw;  // Re-throws the original exception.\n  // }\n  //\n  // However, the purpose of this flag is to allow the program to drop into\n  // the debugger when the exception is thrown. On most platforms, once the\n  // control enters the catch block, the exception origin information is\n  // lost and the debugger will stop the program at the point of the\n  // re-throw in this function -- instead of at the point of the original\n  // throw statement in the code under test.  For this reason, we perform\n  // the check early, sacrificing the ability to affect Google Test's\n  // exception handling in the method where the exception is thrown.\n  if (internal::GetUnitTestImpl()->catch_exceptions()) {\n#if GTEST_HAS_EXCEPTIONS\n    try {\n      return HandleSehExceptionsInMethodIfSupported(object, method, location);\n    } catch (const AssertionException&) {  // NOLINT\n      // This failure was reported already.\n    } catch (const internal::GoogleTestFailureException&) {  // NOLINT\n      // This exception type can only be thrown by a failed Google\n      // Test assertion with the intention of letting another testing\n      // framework catch it.  Therefore we just re-throw it.\n      throw;\n    } catch (const std::exception& e) {  // NOLINT\n      internal::ReportFailureInUnknownLocation(\n          TestPartResult::kFatalFailure,\n          FormatCxxExceptionMessage(e.what(), location));\n    } catch (...) {  // NOLINT\n      internal::ReportFailureInUnknownLocation(\n          TestPartResult::kFatalFailure,\n          FormatCxxExceptionMessage(nullptr, location));\n    }\n    return static_cast<Result>(0);\n#else\n    return HandleSehExceptionsInMethodIfSupported(object, method, location);\n#endif  // GTEST_HAS_EXCEPTIONS\n  } else {\n    return (object->*method)();\n  }\n}\n\n}  // namespace internal\n\n// Runs the test and updates the test result.\nvoid Test::Run() {\n  if (!HasSameFixtureClass()) return;\n\n  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\n  impl->os_stack_trace_getter()->UponLeavingGTest();\n  internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, \"SetUp()\");\n  // We will run the test only if SetUp() was successful and didn't call\n  // GTEST_SKIP().\n  if (!HasFatalFailure() && !IsSkipped()) {\n    impl->os_stack_trace_getter()->UponLeavingGTest();\n    internal::HandleExceptionsInMethodIfSupported(this, &Test::TestBody,\n                                                  \"the test body\");\n  }\n\n  // However, we want to clean up as much as possible.  Hence we will\n  // always call TearDown(), even if SetUp() or the test body has\n  // failed.\n  impl->os_stack_trace_getter()->UponLeavingGTest();\n  internal::HandleExceptionsInMethodIfSupported(this, &Test::TearDown,\n                                                \"TearDown()\");\n}\n\n// Returns true if and only if the current test has a fatal failure.\nbool Test::HasFatalFailure() {\n  return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();\n}\n\n// Returns true if and only if the current test has a non-fatal failure.\nbool Test::HasNonfatalFailure() {\n  return internal::GetUnitTestImpl()\n      ->current_test_result()\n      ->HasNonfatalFailure();\n}\n\n// Returns true if and only if the current test was skipped.\nbool Test::IsSkipped() {\n  return internal::GetUnitTestImpl()->current_test_result()->Skipped();\n}\n\n// class TestInfo\n\n// Constructs a TestInfo object. It assumes ownership of the test factory\n// object.\nTestInfo::TestInfo(const std::string& a_test_suite_name,\n                   const std::string& a_name, const char* a_type_param,\n                   const char* a_value_param,\n                   internal::CodeLocation a_code_location,\n                   internal::TypeId fixture_class_id,\n                   internal::TestFactoryBase* factory)\n    : test_suite_name_(a_test_suite_name),\n      name_(a_name),\n      type_param_(a_type_param ? new std::string(a_type_param) : nullptr),\n      value_param_(a_value_param ? new std::string(a_value_param) : nullptr),\n      location_(a_code_location),\n      fixture_class_id_(fixture_class_id),\n      should_run_(false),\n      is_disabled_(false),\n      matches_filter_(false),\n      is_in_another_shard_(false),\n      factory_(factory),\n      result_() {}\n\n// Destructs a TestInfo object.\nTestInfo::~TestInfo() { delete factory_; }\n\nnamespace internal {\n\n// Creates a new TestInfo object and registers it with Google Test;\n// returns the created object.\n//\n// Arguments:\n//\n//   test_suite_name:  name of the test suite\n//   name:             name of the test\n//   type_param:       the name of the test's type parameter, or NULL if\n//                     this is not a typed or a type-parameterized test.\n//   value_param:      text representation of the test's value parameter,\n//                     or NULL if this is not a value-parameterized test.\n//   code_location:    code location where the test is defined\n//   fixture_class_id: ID of the test fixture class\n//   set_up_tc:        pointer to the function that sets up the test suite\n//   tear_down_tc:     pointer to the function that tears down the test suite\n//   factory:          pointer to the factory that creates a test object.\n//                     The newly created TestInfo instance will assume\n//                     ownership of the factory object.\nTestInfo* MakeAndRegisterTestInfo(\n    const char* test_suite_name, const char* name, const char* type_param,\n    const char* value_param, CodeLocation code_location,\n    TypeId fixture_class_id, SetUpTestSuiteFunc set_up_tc,\n    TearDownTestSuiteFunc tear_down_tc, TestFactoryBase* factory) {\n  TestInfo* const test_info =\n      new TestInfo(test_suite_name, name, type_param, value_param,\n                   code_location, fixture_class_id, factory);\n  GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);\n  return test_info;\n}\n\nvoid ReportInvalidTestSuiteType(const char* test_suite_name,\n                                CodeLocation code_location) {\n  Message errors;\n  errors\n      << \"Attempted redefinition of test suite \" << test_suite_name << \".\\n\"\n      << \"All tests in the same test suite must use the same test fixture\\n\"\n      << \"class.  However, in test suite \" << test_suite_name << \", you tried\\n\"\n      << \"to define a test using a fixture class different from the one\\n\"\n      << \"used earlier. This can happen if the two fixture classes are\\n\"\n      << \"from different namespaces and have the same name. You should\\n\"\n      << \"probably rename one of the classes to put the tests into different\\n\"\n      << \"test suites.\";\n\n  GTEST_LOG_(ERROR) << FormatFileLocation(code_location.file.c_str(),\n                                          code_location.line)\n                    << \" \" << errors.GetString();\n}\n}  // namespace internal\n\nnamespace {\n\n// A predicate that checks the test name of a TestInfo against a known\n// value.\n//\n// This is used for implementation of the TestSuite class only.  We put\n// it in the anonymous namespace to prevent polluting the outer\n// namespace.\n//\n// TestNameIs is copyable.\nclass TestNameIs {\n public:\n  // Constructor.\n  //\n  // TestNameIs has NO default constructor.\n  explicit TestNameIs(const char* name) : name_(name) {}\n\n  // Returns true if and only if the test name of test_info matches name_.\n  bool operator()(const TestInfo* test_info) const {\n    return test_info && test_info->name() == name_;\n  }\n\n private:\n  std::string name_;\n};\n\n}  // namespace\n\nnamespace internal {\n\n// This method expands all parameterized tests registered with macros TEST_P\n// and INSTANTIATE_TEST_SUITE_P into regular tests and registers those.\n// This will be done just once during the program runtime.\nvoid UnitTestImpl::RegisterParameterizedTests() {\n  if (!parameterized_tests_registered_) {\n    parameterized_test_registry_.RegisterTests();\n    type_parameterized_test_registry_.CheckForInstantiations();\n    parameterized_tests_registered_ = true;\n  }\n}\n\n}  // namespace internal\n\n// Creates the test object, runs it, records its result, and then\n// deletes it.\nvoid TestInfo::Run() {\n  TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();\n  if (!should_run_) {\n    if (is_disabled_ && matches_filter_) repeater->OnTestDisabled(*this);\n    return;\n  }\n\n  // Tells UnitTest where to store test result.\n  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\n  impl->set_current_test_info(this);\n\n  // Notifies the unit test event listeners that a test is about to start.\n  repeater->OnTestStart(*this);\n  result_.set_start_timestamp(internal::GetTimeInMillis());\n  internal::Timer timer;\n  impl->os_stack_trace_getter()->UponLeavingGTest();\n\n  // Creates the test object.\n  Test* const test = internal::HandleExceptionsInMethodIfSupported(\n      factory_, &internal::TestFactoryBase::CreateTest,\n      \"the test fixture's constructor\");\n\n  // Runs the test if the constructor didn't generate a fatal failure or invoke\n  // GTEST_SKIP().\n  // Note that the object will not be null\n  if (!Test::HasFatalFailure() && !Test::IsSkipped()) {\n    // This doesn't throw as all user code that can throw are wrapped into\n    // exception handling code.\n    test->Run();\n  }\n\n  if (test != nullptr) {\n    // Deletes the test object.\n    impl->os_stack_trace_getter()->UponLeavingGTest();\n    internal::HandleExceptionsInMethodIfSupported(\n        test, &Test::DeleteSelf_, \"the test fixture's destructor\");\n  }\n\n  result_.set_elapsed_time(timer.Elapsed());\n\n  // Notifies the unit test event listener that a test has just finished.\n  repeater->OnTestEnd(*this);\n\n  // Tells UnitTest to stop associating assertion results to this\n  // test.\n  impl->set_current_test_info(nullptr);\n}\n\n// Skip and records a skipped test result for this object.\nvoid TestInfo::Skip() {\n  if (!should_run_) return;\n\n  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\n  impl->set_current_test_info(this);\n\n  TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();\n\n  // Notifies the unit test event listeners that a test is about to start.\n  repeater->OnTestStart(*this);\n\n  const TestPartResult test_part_result =\n      TestPartResult(TestPartResult::kSkip, this->file(), this->line(), \"\");\n  impl->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(\n      test_part_result);\n\n  // Notifies the unit test event listener that a test has just finished.\n  repeater->OnTestEnd(*this);\n  impl->set_current_test_info(nullptr);\n}\n\n// class TestSuite\n\n// Gets the number of successful tests in this test suite.\nint TestSuite::successful_test_count() const {\n  return CountIf(test_info_list_, TestPassed);\n}\n\n// Gets the number of successful tests in this test suite.\nint TestSuite::skipped_test_count() const {\n  return CountIf(test_info_list_, TestSkipped);\n}\n\n// Gets the number of failed tests in this test suite.\nint TestSuite::failed_test_count() const {\n  return CountIf(test_info_list_, TestFailed);\n}\n\n// Gets the number of disabled tests that will be reported in the XML report.\nint TestSuite::reportable_disabled_test_count() const {\n  return CountIf(test_info_list_, TestReportableDisabled);\n}\n\n// Gets the number of disabled tests in this test suite.\nint TestSuite::disabled_test_count() const {\n  return CountIf(test_info_list_, TestDisabled);\n}\n\n// Gets the number of tests to be printed in the XML report.\nint TestSuite::reportable_test_count() const {\n  return CountIf(test_info_list_, TestReportable);\n}\n\n// Get the number of tests in this test suite that should run.\nint TestSuite::test_to_run_count() const {\n  return CountIf(test_info_list_, ShouldRunTest);\n}\n\n// Gets the number of all tests.\nint TestSuite::total_test_count() const {\n  return static_cast<int>(test_info_list_.size());\n}\n\n// Creates a TestSuite with the given name.\n//\n// Arguments:\n//\n//   a_name:       name of the test suite\n//   a_type_param: the name of the test suite's type parameter, or NULL if\n//                 this is not a typed or a type-parameterized test suite.\n//   set_up_tc:    pointer to the function that sets up the test suite\n//   tear_down_tc: pointer to the function that tears down the test suite\nTestSuite::TestSuite(const char* a_name, const char* a_type_param,\n                     internal::SetUpTestSuiteFunc set_up_tc,\n                     internal::TearDownTestSuiteFunc tear_down_tc)\n    : name_(a_name),\n      type_param_(a_type_param ? new std::string(a_type_param) : nullptr),\n      set_up_tc_(set_up_tc),\n      tear_down_tc_(tear_down_tc),\n      should_run_(false),\n      start_timestamp_(0),\n      elapsed_time_(0) {}\n\n// Destructor of TestSuite.\nTestSuite::~TestSuite() {\n  // Deletes every Test in the collection.\n  ForEach(test_info_list_, internal::Delete<TestInfo>);\n}\n\n// Returns the i-th test among all the tests. i can range from 0 to\n// total_test_count() - 1. If i is not in that range, returns NULL.\nconst TestInfo* TestSuite::GetTestInfo(int i) const {\n  const int index = GetElementOr(test_indices_, i, -1);\n  return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];\n}\n\n// Returns the i-th test among all the tests. i can range from 0 to\n// total_test_count() - 1. If i is not in that range, returns NULL.\nTestInfo* TestSuite::GetMutableTestInfo(int i) {\n  const int index = GetElementOr(test_indices_, i, -1);\n  return index < 0 ? nullptr : test_info_list_[static_cast<size_t>(index)];\n}\n\n// Adds a test to this test suite.  Will delete the test upon\n// destruction of the TestSuite object.\nvoid TestSuite::AddTestInfo(TestInfo* test_info) {\n  test_info_list_.push_back(test_info);\n  test_indices_.push_back(static_cast<int>(test_indices_.size()));\n}\n\n// Runs every test in this TestSuite.\nvoid TestSuite::Run() {\n  if (!should_run_) return;\n\n  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\n  impl->set_current_test_suite(this);\n\n  TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();\n\n  // Call both legacy and the new API\n  repeater->OnTestSuiteStart(*this);\n//  Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  repeater->OnTestCaseStart(*this);\n#endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n  impl->os_stack_trace_getter()->UponLeavingGTest();\n  internal::HandleExceptionsInMethodIfSupported(\n      this, &TestSuite::RunSetUpTestSuite, \"SetUpTestSuite()\");\n\n  const bool skip_all = ad_hoc_test_result().Failed();\n\n  start_timestamp_ = internal::GetTimeInMillis();\n  internal::Timer timer;\n  for (int i = 0; i < total_test_count(); i++) {\n    if (skip_all) {\n      GetMutableTestInfo(i)->Skip();\n    } else {\n      GetMutableTestInfo(i)->Run();\n    }\n    if (GTEST_FLAG_GET(fail_fast) &&\n        GetMutableTestInfo(i)->result()->Failed()) {\n      for (int j = i + 1; j < total_test_count(); j++) {\n        GetMutableTestInfo(j)->Skip();\n      }\n      break;\n    }\n  }\n  elapsed_time_ = timer.Elapsed();\n\n  impl->os_stack_trace_getter()->UponLeavingGTest();\n  internal::HandleExceptionsInMethodIfSupported(\n      this, &TestSuite::RunTearDownTestSuite, \"TearDownTestSuite()\");\n\n  // Call both legacy and the new API\n  repeater->OnTestSuiteEnd(*this);\n//  Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  repeater->OnTestCaseEnd(*this);\n#endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n  impl->set_current_test_suite(nullptr);\n}\n\n// Skips all tests under this TestSuite.\nvoid TestSuite::Skip() {\n  if (!should_run_) return;\n\n  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\n  impl->set_current_test_suite(this);\n\n  TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();\n\n  // Call both legacy and the new API\n  repeater->OnTestSuiteStart(*this);\n//  Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  repeater->OnTestCaseStart(*this);\n#endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n  for (int i = 0; i < total_test_count(); i++) {\n    GetMutableTestInfo(i)->Skip();\n  }\n\n  // Call both legacy and the new API\n  repeater->OnTestSuiteEnd(*this);\n  // Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  repeater->OnTestCaseEnd(*this);\n#endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n  impl->set_current_test_suite(nullptr);\n}\n\n// Clears the results of all tests in this test suite.\nvoid TestSuite::ClearResult() {\n  ad_hoc_test_result_.Clear();\n  ForEach(test_info_list_, TestInfo::ClearTestResult);\n}\n\n// Shuffles the tests in this test suite.\nvoid TestSuite::ShuffleTests(internal::Random* random) {\n  Shuffle(random, &test_indices_);\n}\n\n// Restores the test order to before the first shuffle.\nvoid TestSuite::UnshuffleTests() {\n  for (size_t i = 0; i < test_indices_.size(); i++) {\n    test_indices_[i] = static_cast<int>(i);\n  }\n}\n\n// Formats a countable noun.  Depending on its quantity, either the\n// singular form or the plural form is used. e.g.\n//\n// FormatCountableNoun(1, \"formula\", \"formuli\") returns \"1 formula\".\n// FormatCountableNoun(5, \"book\", \"books\") returns \"5 books\".\nstatic std::string FormatCountableNoun(int count, const char* singular_form,\n                                       const char* plural_form) {\n  return internal::StreamableToString(count) + \" \" +\n         (count == 1 ? singular_form : plural_form);\n}\n\n// Formats the count of tests.\nstatic std::string FormatTestCount(int test_count) {\n  return FormatCountableNoun(test_count, \"test\", \"tests\");\n}\n\n// Formats the count of test suites.\nstatic std::string FormatTestSuiteCount(int test_suite_count) {\n  return FormatCountableNoun(test_suite_count, \"test suite\", \"test suites\");\n}\n\n// Converts a TestPartResult::Type enum to human-friendly string\n// representation.  Both kNonFatalFailure and kFatalFailure are translated\n// to \"Failure\", as the user usually doesn't care about the difference\n// between the two when viewing the test result.\nstatic const char* TestPartResultTypeToString(TestPartResult::Type type) {\n  switch (type) {\n    case TestPartResult::kSkip:\n      return \"Skipped\\n\";\n    case TestPartResult::kSuccess:\n      return \"Success\";\n\n    case TestPartResult::kNonFatalFailure:\n    case TestPartResult::kFatalFailure:\n#ifdef _MSC_VER\n      return \"error: \";\n#else\n      return \"Failure\\n\";\n#endif\n    default:\n      return \"Unknown result type\";\n  }\n}\n\nnamespace internal {\nnamespace {\nenum class GTestColor { kDefault, kRed, kGreen, kYellow };\n}  // namespace\n\n// Prints a TestPartResult to an std::string.\nstatic std::string PrintTestPartResultToString(\n    const TestPartResult& test_part_result) {\n  return (Message() << internal::FormatFileLocation(\n                           test_part_result.file_name(),\n                           test_part_result.line_number())\n                    << \" \"\n                    << TestPartResultTypeToString(test_part_result.type())\n                    << test_part_result.message())\n      .GetString();\n}\n\n// Prints a TestPartResult.\nstatic void PrintTestPartResult(const TestPartResult& test_part_result) {\n  const std::string& result = PrintTestPartResultToString(test_part_result);\n  printf(\"%s\\n\", result.c_str());\n  fflush(stdout);\n  // If the test program runs in Visual Studio or a debugger, the\n  // following statements add the test part result message to the Output\n  // window such that the user can double-click on it to jump to the\n  // corresponding source code location; otherwise they do nothing.\n#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE\n  // We don't call OutputDebugString*() on Windows Mobile, as printing\n  // to stdout is done by OutputDebugString() there already - we don't\n  // want the same message printed twice.\n  ::OutputDebugStringA(result.c_str());\n  ::OutputDebugStringA(\"\\n\");\n#endif\n}\n\n// class PrettyUnitTestResultPrinter\n#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \\\n    !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW\n\n// Returns the character attribute for the given color.\nstatic WORD GetColorAttribute(GTestColor color) {\n  switch (color) {\n    case GTestColor::kRed:\n      return FOREGROUND_RED;\n    case GTestColor::kGreen:\n      return FOREGROUND_GREEN;\n    case GTestColor::kYellow:\n      return FOREGROUND_RED | FOREGROUND_GREEN;\n    default:\n      return 0;\n  }\n}\n\nstatic int GetBitOffset(WORD color_mask) {\n  if (color_mask == 0) return 0;\n\n  int bitOffset = 0;\n  while ((color_mask & 1) == 0) {\n    color_mask >>= 1;\n    ++bitOffset;\n  }\n  return bitOffset;\n}\n\nstatic WORD GetNewColor(GTestColor color, WORD old_color_attrs) {\n  // Let's reuse the BG\n  static const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |\n                                      BACKGROUND_RED | BACKGROUND_INTENSITY;\n  static const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |\n                                      FOREGROUND_RED | FOREGROUND_INTENSITY;\n  const WORD existing_bg = old_color_attrs & background_mask;\n\n  WORD new_color =\n      GetColorAttribute(color) | existing_bg | FOREGROUND_INTENSITY;\n  static const int bg_bitOffset = GetBitOffset(background_mask);\n  static const int fg_bitOffset = GetBitOffset(foreground_mask);\n\n  if (((new_color & background_mask) >> bg_bitOffset) ==\n      ((new_color & foreground_mask) >> fg_bitOffset)) {\n    new_color ^= FOREGROUND_INTENSITY;  // invert intensity\n  }\n  return new_color;\n}\n\n#else\n\n// Returns the ANSI color code for the given color. GTestColor::kDefault is\n// an invalid input.\nstatic const char* GetAnsiColorCode(GTestColor color) {\n  switch (color) {\n    case GTestColor::kRed:\n      return \"1\";\n    case GTestColor::kGreen:\n      return \"2\";\n    case GTestColor::kYellow:\n      return \"3\";\n    default:\n      return nullptr;\n  }\n}\n\n#endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE\n\n// Returns true if and only if Google Test should use colors in the output.\nbool ShouldUseColor(bool stdout_is_tty) {\n  std::string c = GTEST_FLAG_GET(color);\n  const char* const gtest_color = c.c_str();\n\n  if (String::CaseInsensitiveCStringEquals(gtest_color, \"auto\")) {\n#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW\n    // On Windows the TERM variable is usually not set, but the\n    // console there does support colors.\n    return stdout_is_tty;\n#else\n    // On non-Windows platforms, we rely on the TERM variable.\n    const char* const term = posix::GetEnv(\"TERM\");\n    const bool term_supports_color =\n        String::CStringEquals(term, \"xterm\") ||\n        String::CStringEquals(term, \"xterm-color\") ||\n        String::CStringEquals(term, \"xterm-256color\") ||\n        String::CStringEquals(term, \"screen\") ||\n        String::CStringEquals(term, \"screen-256color\") ||\n        String::CStringEquals(term, \"tmux\") ||\n        String::CStringEquals(term, \"tmux-256color\") ||\n        String::CStringEquals(term, \"rxvt-unicode\") ||\n        String::CStringEquals(term, \"rxvt-unicode-256color\") ||\n        String::CStringEquals(term, \"linux\") ||\n        String::CStringEquals(term, \"cygwin\");\n    return stdout_is_tty && term_supports_color;\n#endif  // GTEST_OS_WINDOWS\n  }\n\n  return String::CaseInsensitiveCStringEquals(gtest_color, \"yes\") ||\n         String::CaseInsensitiveCStringEquals(gtest_color, \"true\") ||\n         String::CaseInsensitiveCStringEquals(gtest_color, \"t\") ||\n         String::CStringEquals(gtest_color, \"1\");\n  // We take \"yes\", \"true\", \"t\", and \"1\" as meaning \"yes\".  If the\n  // value is neither one of these nor \"auto\", we treat it as \"no\" to\n  // be conservative.\n}\n\n// Helpers for printing colored strings to stdout. Note that on Windows, we\n// cannot simply emit special characters and have the terminal change colors.\n// This routine must actually emit the characters rather than return a string\n// that would be colored when printed, as can be done on Linux.\n\nGTEST_ATTRIBUTE_PRINTF_(2, 3)\nstatic void ColoredPrintf(GTestColor color, const char* fmt, ...) {\n  va_list args;\n  va_start(args, fmt);\n\n  static const bool in_color_mode =\n      ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);\n  const bool use_color = in_color_mode && (color != GTestColor::kDefault);\n\n  if (!use_color) {\n    vprintf(fmt, args);\n    va_end(args);\n    return;\n  }\n\n#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && \\\n    !GTEST_OS_WINDOWS_RT && !GTEST_OS_WINDOWS_MINGW\n  const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);\n\n  // Gets the current text color.\n  CONSOLE_SCREEN_BUFFER_INFO buffer_info;\n  GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);\n  const WORD old_color_attrs = buffer_info.wAttributes;\n  const WORD new_color = GetNewColor(color, old_color_attrs);\n\n  // We need to flush the stream buffers into the console before each\n  // SetConsoleTextAttribute call lest it affect the text that is already\n  // printed but has not yet reached the console.\n  fflush(stdout);\n  SetConsoleTextAttribute(stdout_handle, new_color);\n\n  vprintf(fmt, args);\n\n  fflush(stdout);\n  // Restores the text color.\n  SetConsoleTextAttribute(stdout_handle, old_color_attrs);\n#else\n  printf(\"\\033[0;3%sm\", GetAnsiColorCode(color));\n  vprintf(fmt, args);\n  printf(\"\\033[m\");  // Resets the terminal to default.\n#endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE\n  va_end(args);\n}\n\n// Text printed in Google Test's text output and --gtest_list_tests\n// output to label the type parameter and value parameter for a test.\nstatic const char kTypeParamLabel[] = \"TypeParam\";\nstatic const char kValueParamLabel[] = \"GetParam()\";\n\nstatic void PrintFullTestCommentIfPresent(const TestInfo& test_info) {\n  const char* const type_param = test_info.type_param();\n  const char* const value_param = test_info.value_param();\n\n  if (type_param != nullptr || value_param != nullptr) {\n    printf(\", where \");\n    if (type_param != nullptr) {\n      printf(\"%s = %s\", kTypeParamLabel, type_param);\n      if (value_param != nullptr) printf(\" and \");\n    }\n    if (value_param != nullptr) {\n      printf(\"%s = %s\", kValueParamLabel, value_param);\n    }\n  }\n}\n\n// This class implements the TestEventListener interface.\n//\n// Class PrettyUnitTestResultPrinter is copyable.\nclass PrettyUnitTestResultPrinter : public TestEventListener {\n public:\n  PrettyUnitTestResultPrinter() {}\n  static void PrintTestName(const char* test_suite, const char* test) {\n    printf(\"%s.%s\", test_suite, test);\n  }\n\n  // The following methods override what's in the TestEventListener class.\n  void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}\n  void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;\n  void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;\n  void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  void OnTestCaseStart(const TestCase& test_case) override;\n#else\n  void OnTestSuiteStart(const TestSuite& test_suite) override;\n#endif  // OnTestCaseStart\n\n  void OnTestStart(const TestInfo& test_info) override;\n  void OnTestDisabled(const TestInfo& test_info) override;\n\n  void OnTestPartResult(const TestPartResult& result) override;\n  void OnTestEnd(const TestInfo& test_info) override;\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  void OnTestCaseEnd(const TestCase& test_case) override;\n#else\n  void OnTestSuiteEnd(const TestSuite& test_suite) override;\n#endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n  void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;\n  void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}\n  void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;\n  void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}\n\n private:\n  static void PrintFailedTests(const UnitTest& unit_test);\n  static void PrintFailedTestSuites(const UnitTest& unit_test);\n  static void PrintSkippedTests(const UnitTest& unit_test);\n};\n\n// Fired before each iteration of tests starts.\nvoid PrettyUnitTestResultPrinter::OnTestIterationStart(\n    const UnitTest& unit_test, int iteration) {\n  if (GTEST_FLAG_GET(repeat) != 1)\n    printf(\"\\nRepeating all tests (iteration %d) . . .\\n\\n\", iteration + 1);\n\n  std::string f = GTEST_FLAG_GET(filter);\n  const char* const filter = f.c_str();\n\n  // Prints the filter if it's not *.  This reminds the user that some\n  // tests may be skipped.\n  if (!String::CStringEquals(filter, kUniversalFilter)) {\n    ColoredPrintf(GTestColor::kYellow, \"Note: %s filter = %s\\n\", GTEST_NAME_,\n                  filter);\n  }\n\n  if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {\n    const int32_t shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);\n    ColoredPrintf(GTestColor::kYellow, \"Note: This is test shard %d of %s.\\n\",\n                  static_cast<int>(shard_index) + 1,\n                  internal::posix::GetEnv(kTestTotalShards));\n  }\n\n  if (GTEST_FLAG_GET(shuffle)) {\n    ColoredPrintf(GTestColor::kYellow,\n                  \"Note: Randomizing tests' orders with a seed of %d .\\n\",\n                  unit_test.random_seed());\n  }\n\n  ColoredPrintf(GTestColor::kGreen, \"[==========] \");\n  printf(\"Running %s from %s.\\n\",\n         FormatTestCount(unit_test.test_to_run_count()).c_str(),\n         FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());\n  fflush(stdout);\n}\n\nvoid PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(\n    const UnitTest& /*unit_test*/) {\n  ColoredPrintf(GTestColor::kGreen, \"[----------] \");\n  printf(\"Global test environment set-up.\\n\");\n  fflush(stdout);\n}\n\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\nvoid PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {\n  const std::string counts =\n      FormatCountableNoun(test_case.test_to_run_count(), \"test\", \"tests\");\n  ColoredPrintf(GTestColor::kGreen, \"[----------] \");\n  printf(\"%s from %s\", counts.c_str(), test_case.name());\n  if (test_case.type_param() == nullptr) {\n    printf(\"\\n\");\n  } else {\n    printf(\", where %s = %s\\n\", kTypeParamLabel, test_case.type_param());\n  }\n  fflush(stdout);\n}\n#else\nvoid PrettyUnitTestResultPrinter::OnTestSuiteStart(\n    const TestSuite& test_suite) {\n  const std::string counts =\n      FormatCountableNoun(test_suite.test_to_run_count(), \"test\", \"tests\");\n  ColoredPrintf(GTestColor::kGreen, \"[----------] \");\n  printf(\"%s from %s\", counts.c_str(), test_suite.name());\n  if (test_suite.type_param() == nullptr) {\n    printf(\"\\n\");\n  } else {\n    printf(\", where %s = %s\\n\", kTypeParamLabel, test_suite.type_param());\n  }\n  fflush(stdout);\n}\n#endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\nvoid PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {\n  ColoredPrintf(GTestColor::kGreen, \"[ RUN      ] \");\n  PrintTestName(test_info.test_suite_name(), test_info.name());\n  printf(\"\\n\");\n  fflush(stdout);\n}\n\nvoid PrettyUnitTestResultPrinter::OnTestDisabled(const TestInfo& test_info) {\n  ColoredPrintf(GTestColor::kYellow, \"[ DISABLED ] \");\n  PrintTestName(test_info.test_suite_name(), test_info.name());\n  printf(\"\\n\");\n  fflush(stdout);\n}\n\n// Called after an assertion failure.\nvoid PrettyUnitTestResultPrinter::OnTestPartResult(\n    const TestPartResult& result) {\n  switch (result.type()) {\n    // If the test part succeeded, we don't need to do anything.\n    case TestPartResult::kSuccess:\n      return;\n    default:\n      // Print failure message from the assertion\n      // (e.g. expected this and got that).\n      PrintTestPartResult(result);\n      fflush(stdout);\n  }\n}\n\nvoid PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {\n  if (test_info.result()->Passed()) {\n    ColoredPrintf(GTestColor::kGreen, \"[       OK ] \");\n  } else if (test_info.result()->Skipped()) {\n    ColoredPrintf(GTestColor::kGreen, \"[  SKIPPED ] \");\n  } else {\n    ColoredPrintf(GTestColor::kRed, \"[  FAILED  ] \");\n  }\n  PrintTestName(test_info.test_suite_name(), test_info.name());\n  if (test_info.result()->Failed()) PrintFullTestCommentIfPresent(test_info);\n\n  if (GTEST_FLAG_GET(print_time)) {\n    printf(\" (%s ms)\\n\",\n           internal::StreamableToString(test_info.result()->elapsed_time())\n               .c_str());\n  } else {\n    printf(\"\\n\");\n  }\n  fflush(stdout);\n}\n\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\nvoid PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {\n  if (!GTEST_FLAG_GET(print_time)) return;\n\n  const std::string counts =\n      FormatCountableNoun(test_case.test_to_run_count(), \"test\", \"tests\");\n  ColoredPrintf(GTestColor::kGreen, \"[----------] \");\n  printf(\"%s from %s (%s ms total)\\n\\n\", counts.c_str(), test_case.name(),\n         internal::StreamableToString(test_case.elapsed_time()).c_str());\n  fflush(stdout);\n}\n#else\nvoid PrettyUnitTestResultPrinter::OnTestSuiteEnd(const TestSuite& test_suite) {\n  if (!GTEST_FLAG_GET(print_time)) return;\n\n  const std::string counts =\n      FormatCountableNoun(test_suite.test_to_run_count(), \"test\", \"tests\");\n  ColoredPrintf(GTestColor::kGreen, \"[----------] \");\n  printf(\"%s from %s (%s ms total)\\n\\n\", counts.c_str(), test_suite.name(),\n         internal::StreamableToString(test_suite.elapsed_time()).c_str());\n  fflush(stdout);\n}\n#endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\nvoid PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(\n    const UnitTest& /*unit_test*/) {\n  ColoredPrintf(GTestColor::kGreen, \"[----------] \");\n  printf(\"Global test environment tear-down\\n\");\n  fflush(stdout);\n}\n\n// Internal helper for printing the list of failed tests.\nvoid PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {\n  const int failed_test_count = unit_test.failed_test_count();\n  ColoredPrintf(GTestColor::kRed, \"[  FAILED  ] \");\n  printf(\"%s, listed below:\\n\", FormatTestCount(failed_test_count).c_str());\n\n  for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {\n    const TestSuite& test_suite = *unit_test.GetTestSuite(i);\n    if (!test_suite.should_run() || (test_suite.failed_test_count() == 0)) {\n      continue;\n    }\n    for (int j = 0; j < test_suite.total_test_count(); ++j) {\n      const TestInfo& test_info = *test_suite.GetTestInfo(j);\n      if (!test_info.should_run() || !test_info.result()->Failed()) {\n        continue;\n      }\n      ColoredPrintf(GTestColor::kRed, \"[  FAILED  ] \");\n      printf(\"%s.%s\", test_suite.name(), test_info.name());\n      PrintFullTestCommentIfPresent(test_info);\n      printf(\"\\n\");\n    }\n  }\n  printf(\"\\n%2d FAILED %s\\n\", failed_test_count,\n         failed_test_count == 1 ? \"TEST\" : \"TESTS\");\n}\n\n// Internal helper for printing the list of test suite failures not covered by\n// PrintFailedTests.\nvoid PrettyUnitTestResultPrinter::PrintFailedTestSuites(\n    const UnitTest& unit_test) {\n  int suite_failure_count = 0;\n  for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {\n    const TestSuite& test_suite = *unit_test.GetTestSuite(i);\n    if (!test_suite.should_run()) {\n      continue;\n    }\n    if (test_suite.ad_hoc_test_result().Failed()) {\n      ColoredPrintf(GTestColor::kRed, \"[  FAILED  ] \");\n      printf(\"%s: SetUpTestSuite or TearDownTestSuite\\n\", test_suite.name());\n      ++suite_failure_count;\n    }\n  }\n  if (suite_failure_count > 0) {\n    printf(\"\\n%2d FAILED TEST %s\\n\", suite_failure_count,\n           suite_failure_count == 1 ? \"SUITE\" : \"SUITES\");\n  }\n}\n\n// Internal helper for printing the list of skipped tests.\nvoid PrettyUnitTestResultPrinter::PrintSkippedTests(const UnitTest& unit_test) {\n  const int skipped_test_count = unit_test.skipped_test_count();\n  if (skipped_test_count == 0) {\n    return;\n  }\n\n  for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {\n    const TestSuite& test_suite = *unit_test.GetTestSuite(i);\n    if (!test_suite.should_run() || (test_suite.skipped_test_count() == 0)) {\n      continue;\n    }\n    for (int j = 0; j < test_suite.total_test_count(); ++j) {\n      const TestInfo& test_info = *test_suite.GetTestInfo(j);\n      if (!test_info.should_run() || !test_info.result()->Skipped()) {\n        continue;\n      }\n      ColoredPrintf(GTestColor::kGreen, \"[  SKIPPED ] \");\n      printf(\"%s.%s\", test_suite.name(), test_info.name());\n      printf(\"\\n\");\n    }\n  }\n}\n\nvoid PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,\n                                                     int /*iteration*/) {\n  ColoredPrintf(GTestColor::kGreen, \"[==========] \");\n  printf(\"%s from %s ran.\",\n         FormatTestCount(unit_test.test_to_run_count()).c_str(),\n         FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());\n  if (GTEST_FLAG_GET(print_time)) {\n    printf(\" (%s ms total)\",\n           internal::StreamableToString(unit_test.elapsed_time()).c_str());\n  }\n  printf(\"\\n\");\n  ColoredPrintf(GTestColor::kGreen, \"[  PASSED  ] \");\n  printf(\"%s.\\n\", FormatTestCount(unit_test.successful_test_count()).c_str());\n\n  const int skipped_test_count = unit_test.skipped_test_count();\n  if (skipped_test_count > 0) {\n    ColoredPrintf(GTestColor::kGreen, \"[  SKIPPED ] \");\n    printf(\"%s, listed below:\\n\", FormatTestCount(skipped_test_count).c_str());\n    PrintSkippedTests(unit_test);\n  }\n\n  if (!unit_test.Passed()) {\n    PrintFailedTests(unit_test);\n    PrintFailedTestSuites(unit_test);\n  }\n\n  int num_disabled = unit_test.reportable_disabled_test_count();\n  if (num_disabled && !GTEST_FLAG_GET(also_run_disabled_tests)) {\n    if (unit_test.Passed()) {\n      printf(\"\\n\");  // Add a spacer if no FAILURE banner is displayed.\n    }\n    ColoredPrintf(GTestColor::kYellow, \"  YOU HAVE %d DISABLED %s\\n\\n\",\n                  num_disabled, num_disabled == 1 ? \"TEST\" : \"TESTS\");\n  }\n  // Ensure that Google Test output is printed before, e.g., heapchecker output.\n  fflush(stdout);\n}\n\n// End PrettyUnitTestResultPrinter\n\n// This class implements the TestEventListener interface.\n//\n// Class BriefUnitTestResultPrinter is copyable.\nclass BriefUnitTestResultPrinter : public TestEventListener {\n public:\n  BriefUnitTestResultPrinter() {}\n  static void PrintTestName(const char* test_suite, const char* test) {\n    printf(\"%s.%s\", test_suite, test);\n  }\n\n  // The following methods override what's in the TestEventListener class.\n  void OnTestProgramStart(const UnitTest& /*unit_test*/) override {}\n  void OnTestIterationStart(const UnitTest& /*unit_test*/,\n                            int /*iteration*/) override {}\n  void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {}\n  void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {}\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  void OnTestCaseStart(const TestCase& /*test_case*/) override {}\n#else\n  void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {}\n#endif  // OnTestCaseStart\n\n  void OnTestStart(const TestInfo& /*test_info*/) override {}\n  void OnTestDisabled(const TestInfo& /*test_info*/) override {}\n\n  void OnTestPartResult(const TestPartResult& result) override;\n  void OnTestEnd(const TestInfo& test_info) override;\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  void OnTestCaseEnd(const TestCase& /*test_case*/) override {}\n#else\n  void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {}\n#endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n  void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {}\n  void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {}\n  void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;\n  void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {}\n};\n\n// Called after an assertion failure.\nvoid BriefUnitTestResultPrinter::OnTestPartResult(\n    const TestPartResult& result) {\n  switch (result.type()) {\n    // If the test part succeeded, we don't need to do anything.\n    case TestPartResult::kSuccess:\n      return;\n    default:\n      // Print failure message from the assertion\n      // (e.g. expected this and got that).\n      PrintTestPartResult(result);\n      fflush(stdout);\n  }\n}\n\nvoid BriefUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {\n  if (test_info.result()->Failed()) {\n    ColoredPrintf(GTestColor::kRed, \"[  FAILED  ] \");\n    PrintTestName(test_info.test_suite_name(), test_info.name());\n    PrintFullTestCommentIfPresent(test_info);\n\n    if (GTEST_FLAG_GET(print_time)) {\n      printf(\" (%s ms)\\n\",\n             internal::StreamableToString(test_info.result()->elapsed_time())\n                 .c_str());\n    } else {\n      printf(\"\\n\");\n    }\n    fflush(stdout);\n  }\n}\n\nvoid BriefUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,\n                                                    int /*iteration*/) {\n  ColoredPrintf(GTestColor::kGreen, \"[==========] \");\n  printf(\"%s from %s ran.\",\n         FormatTestCount(unit_test.test_to_run_count()).c_str(),\n         FormatTestSuiteCount(unit_test.test_suite_to_run_count()).c_str());\n  if (GTEST_FLAG_GET(print_time)) {\n    printf(\" (%s ms total)\",\n           internal::StreamableToString(unit_test.elapsed_time()).c_str());\n  }\n  printf(\"\\n\");\n  ColoredPrintf(GTestColor::kGreen, \"[  PASSED  ] \");\n  printf(\"%s.\\n\", FormatTestCount(unit_test.successful_test_count()).c_str());\n\n  const int skipped_test_count = unit_test.skipped_test_count();\n  if (skipped_test_count > 0) {\n    ColoredPrintf(GTestColor::kGreen, \"[  SKIPPED ] \");\n    printf(\"%s.\\n\", FormatTestCount(skipped_test_count).c_str());\n  }\n\n  int num_disabled = unit_test.reportable_disabled_test_count();\n  if (num_disabled && !GTEST_FLAG_GET(also_run_disabled_tests)) {\n    if (unit_test.Passed()) {\n      printf(\"\\n\");  // Add a spacer if no FAILURE banner is displayed.\n    }\n    ColoredPrintf(GTestColor::kYellow, \"  YOU HAVE %d DISABLED %s\\n\\n\",\n                  num_disabled, num_disabled == 1 ? \"TEST\" : \"TESTS\");\n  }\n  // Ensure that Google Test output is printed before, e.g., heapchecker output.\n  fflush(stdout);\n}\n\n// End BriefUnitTestResultPrinter\n\n// class TestEventRepeater\n//\n// This class forwards events to other event listeners.\nclass TestEventRepeater : public TestEventListener {\n public:\n  TestEventRepeater() : forwarding_enabled_(true) {}\n  ~TestEventRepeater() override;\n  void Append(TestEventListener* listener);\n  TestEventListener* Release(TestEventListener* listener);\n\n  // Controls whether events will be forwarded to listeners_. Set to false\n  // in death test child processes.\n  bool forwarding_enabled() const { return forwarding_enabled_; }\n  void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }\n\n  void OnTestProgramStart(const UnitTest& unit_test) override;\n  void OnTestIterationStart(const UnitTest& unit_test, int iteration) override;\n  void OnEnvironmentsSetUpStart(const UnitTest& unit_test) override;\n  void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) override;\n//  Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  void OnTestCaseStart(const TestSuite& parameter) override;\n#endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  void OnTestSuiteStart(const TestSuite& parameter) override;\n  void OnTestStart(const TestInfo& test_info) override;\n  void OnTestDisabled(const TestInfo& test_info) override;\n  void OnTestPartResult(const TestPartResult& result) override;\n  void OnTestEnd(const TestInfo& test_info) override;\n//  Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  void OnTestCaseEnd(const TestCase& parameter) override;\n#endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  void OnTestSuiteEnd(const TestSuite& parameter) override;\n  void OnEnvironmentsTearDownStart(const UnitTest& unit_test) override;\n  void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) override;\n  void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;\n  void OnTestProgramEnd(const UnitTest& unit_test) override;\n\n private:\n  // Controls whether events will be forwarded to listeners_. Set to false\n  // in death test child processes.\n  bool forwarding_enabled_;\n  // The list of listeners that receive events.\n  std::vector<TestEventListener*> listeners_;\n\n  TestEventRepeater(const TestEventRepeater&) = delete;\n  TestEventRepeater& operator=(const TestEventRepeater&) = delete;\n};\n\nTestEventRepeater::~TestEventRepeater() {\n  ForEach(listeners_, Delete<TestEventListener>);\n}\n\nvoid TestEventRepeater::Append(TestEventListener* listener) {\n  listeners_.push_back(listener);\n}\n\nTestEventListener* TestEventRepeater::Release(TestEventListener* listener) {\n  for (size_t i = 0; i < listeners_.size(); ++i) {\n    if (listeners_[i] == listener) {\n      listeners_.erase(listeners_.begin() + static_cast<int>(i));\n      return listener;\n    }\n  }\n\n  return nullptr;\n}\n\n// Since most methods are very similar, use macros to reduce boilerplate.\n// This defines a member that forwards the call to all listeners.\n#define GTEST_REPEATER_METHOD_(Name, Type)              \\\n  void TestEventRepeater::Name(const Type& parameter) { \\\n    if (forwarding_enabled_) {                          \\\n      for (size_t i = 0; i < listeners_.size(); i++) {  \\\n        listeners_[i]->Name(parameter);                 \\\n      }                                                 \\\n    }                                                   \\\n  }\n// This defines a member that forwards the call to all listeners in reverse\n// order.\n#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type)      \\\n  void TestEventRepeater::Name(const Type& parameter) { \\\n    if (forwarding_enabled_) {                          \\\n      for (size_t i = listeners_.size(); i != 0; i--) { \\\n        listeners_[i - 1]->Name(parameter);             \\\n      }                                                 \\\n    }                                                   \\\n  }\n\nGTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)\nGTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)\n//  Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\nGTEST_REPEATER_METHOD_(OnTestCaseStart, TestSuite)\n#endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_\nGTEST_REPEATER_METHOD_(OnTestSuiteStart, TestSuite)\nGTEST_REPEATER_METHOD_(OnTestStart, TestInfo)\nGTEST_REPEATER_METHOD_(OnTestDisabled, TestInfo)\nGTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)\nGTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)\nGTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)\nGTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)\nGTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)\n//  Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\nGTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestSuite)\n#endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_\nGTEST_REVERSE_REPEATER_METHOD_(OnTestSuiteEnd, TestSuite)\nGTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)\n\n#undef GTEST_REPEATER_METHOD_\n#undef GTEST_REVERSE_REPEATER_METHOD_\n\nvoid TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,\n                                             int iteration) {\n  if (forwarding_enabled_) {\n    for (size_t i = 0; i < listeners_.size(); i++) {\n      listeners_[i]->OnTestIterationStart(unit_test, iteration);\n    }\n  }\n}\n\nvoid TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,\n                                           int iteration) {\n  if (forwarding_enabled_) {\n    for (size_t i = listeners_.size(); i > 0; i--) {\n      listeners_[i - 1]->OnTestIterationEnd(unit_test, iteration);\n    }\n  }\n}\n\n// End TestEventRepeater\n\n// This class generates an XML output file.\nclass XmlUnitTestResultPrinter : public EmptyTestEventListener {\n public:\n  explicit XmlUnitTestResultPrinter(const char* output_file);\n\n  void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;\n  void ListTestsMatchingFilter(const std::vector<TestSuite*>& test_suites);\n\n  // Prints an XML summary of all unit tests.\n  static void PrintXmlTestsList(std::ostream* stream,\n                                const std::vector<TestSuite*>& test_suites);\n\n private:\n  // Is c a whitespace character that is normalized to a space character\n  // when it appears in an XML attribute value?\n  static bool IsNormalizableWhitespace(unsigned char c) {\n    return c == '\\t' || c == '\\n' || c == '\\r';\n  }\n\n  // May c appear in a well-formed XML document?\n  // https://www.w3.org/TR/REC-xml/#charsets\n  static bool IsValidXmlCharacter(unsigned char c) {\n    return IsNormalizableWhitespace(c) || c >= 0x20;\n  }\n\n  // Returns an XML-escaped copy of the input string str.  If\n  // is_attribute is true, the text is meant to appear as an attribute\n  // value, and normalizable whitespace is preserved by replacing it\n  // with character references.\n  static std::string EscapeXml(const std::string& str, bool is_attribute);\n\n  // Returns the given string with all characters invalid in XML removed.\n  static std::string RemoveInvalidXmlCharacters(const std::string& str);\n\n  // Convenience wrapper around EscapeXml when str is an attribute value.\n  static std::string EscapeXmlAttribute(const std::string& str) {\n    return EscapeXml(str, true);\n  }\n\n  // Convenience wrapper around EscapeXml when str is not an attribute value.\n  static std::string EscapeXmlText(const char* str) {\n    return EscapeXml(str, false);\n  }\n\n  // Verifies that the given attribute belongs to the given element and\n  // streams the attribute as XML.\n  static void OutputXmlAttribute(std::ostream* stream,\n                                 const std::string& element_name,\n                                 const std::string& name,\n                                 const std::string& value);\n\n  // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.\n  static void OutputXmlCDataSection(::std::ostream* stream, const char* data);\n\n  // Streams a test suite XML stanza containing the given test result.\n  //\n  // Requires: result.Failed()\n  static void OutputXmlTestSuiteForTestResult(::std::ostream* stream,\n                                              const TestResult& result);\n\n  // Streams an XML representation of a TestResult object.\n  static void OutputXmlTestResult(::std::ostream* stream,\n                                  const TestResult& result);\n\n  // Streams an XML representation of a TestInfo object.\n  static void OutputXmlTestInfo(::std::ostream* stream,\n                                const char* test_suite_name,\n                                const TestInfo& test_info);\n\n  // Prints an XML representation of a TestSuite object\n  static void PrintXmlTestSuite(::std::ostream* stream,\n                                const TestSuite& test_suite);\n\n  // Prints an XML summary of unit_test to output stream out.\n  static void PrintXmlUnitTest(::std::ostream* stream,\n                               const UnitTest& unit_test);\n\n  // Produces a string representing the test properties in a result as space\n  // delimited XML attributes based on the property key=\"value\" pairs.\n  // When the std::string is not empty, it includes a space at the beginning,\n  // to delimit this attribute from prior attributes.\n  static std::string TestPropertiesAsXmlAttributes(const TestResult& result);\n\n  // Streams an XML representation of the test properties of a TestResult\n  // object.\n  static void OutputXmlTestProperties(std::ostream* stream,\n                                      const TestResult& result);\n\n  // The output file.\n  const std::string output_file_;\n\n  XmlUnitTestResultPrinter(const XmlUnitTestResultPrinter&) = delete;\n  XmlUnitTestResultPrinter& operator=(const XmlUnitTestResultPrinter&) = delete;\n};\n\n// Creates a new XmlUnitTestResultPrinter.\nXmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)\n    : output_file_(output_file) {\n  if (output_file_.empty()) {\n    GTEST_LOG_(FATAL) << \"XML output file may not be null\";\n  }\n}\n\n// Called after the unit test ends.\nvoid XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,\n                                                  int /*iteration*/) {\n  FILE* xmlout = OpenFileForWriting(output_file_);\n  std::stringstream stream;\n  PrintXmlUnitTest(&stream, unit_test);\n  fprintf(xmlout, \"%s\", StringStreamToString(&stream).c_str());\n  fclose(xmlout);\n}\n\nvoid XmlUnitTestResultPrinter::ListTestsMatchingFilter(\n    const std::vector<TestSuite*>& test_suites) {\n  FILE* xmlout = OpenFileForWriting(output_file_);\n  std::stringstream stream;\n  PrintXmlTestsList(&stream, test_suites);\n  fprintf(xmlout, \"%s\", StringStreamToString(&stream).c_str());\n  fclose(xmlout);\n}\n\n// Returns an XML-escaped copy of the input string str.  If is_attribute\n// is true, the text is meant to appear as an attribute value, and\n// normalizable whitespace is preserved by replacing it with character\n// references.\n//\n// Invalid XML characters in str, if any, are stripped from the output.\n// It is expected that most, if not all, of the text processed by this\n// module will consist of ordinary English text.\n// If this module is ever modified to produce version 1.1 XML output,\n// most invalid characters can be retained using character references.\nstd::string XmlUnitTestResultPrinter::EscapeXml(const std::string& str,\n                                                bool is_attribute) {\n  Message m;\n\n  for (size_t i = 0; i < str.size(); ++i) {\n    const char ch = str[i];\n    switch (ch) {\n      case '<':\n        m << \"&lt;\";\n        break;\n      case '>':\n        m << \"&gt;\";\n        break;\n      case '&':\n        m << \"&amp;\";\n        break;\n      case '\\'':\n        if (is_attribute)\n          m << \"&apos;\";\n        else\n          m << '\\'';\n        break;\n      case '\"':\n        if (is_attribute)\n          m << \"&quot;\";\n        else\n          m << '\"';\n        break;\n      default:\n        if (IsValidXmlCharacter(static_cast<unsigned char>(ch))) {\n          if (is_attribute &&\n              IsNormalizableWhitespace(static_cast<unsigned char>(ch)))\n            m << \"&#x\" << String::FormatByte(static_cast<unsigned char>(ch))\n              << \";\";\n          else\n            m << ch;\n        }\n        break;\n    }\n  }\n\n  return m.GetString();\n}\n\n// Returns the given string with all characters invalid in XML removed.\n// Currently invalid characters are dropped from the string. An\n// alternative is to replace them with certain characters such as . or ?.\nstd::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(\n    const std::string& str) {\n  std::string output;\n  output.reserve(str.size());\n  for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)\n    if (IsValidXmlCharacter(static_cast<unsigned char>(*it)))\n      output.push_back(*it);\n\n  return output;\n}\n\n// The following routines generate an XML representation of a UnitTest\n// object.\n//\n// This is how Google Test concepts map to the DTD:\n//\n// <testsuites name=\"AllTests\">        <-- corresponds to a UnitTest object\n//   <testsuite name=\"testcase-name\">  <-- corresponds to a TestSuite object\n//     <testcase name=\"test-name\">     <-- corresponds to a TestInfo object\n//       <failure message=\"...\">...</failure>\n//       <failure message=\"...\">...</failure>\n//       <failure message=\"...\">...</failure>\n//                                     <-- individual assertion failures\n//     </testcase>\n//   </testsuite>\n// </testsuites>\n\n// Formats the given time in milliseconds as seconds.\nstd::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {\n  ::std::stringstream ss;\n  ss << (static_cast<double>(ms) * 1e-3);\n  return ss.str();\n}\n\nstatic bool PortableLocaltime(time_t seconds, struct tm* out) {\n#if defined(_MSC_VER)\n  return localtime_s(out, &seconds) == 0;\n#elif defined(__MINGW32__) || defined(__MINGW64__)\n  // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses\n  // Windows' localtime(), which has a thread-local tm buffer.\n  struct tm* tm_ptr = localtime(&seconds);  // NOLINT\n  if (tm_ptr == nullptr) return false;\n  *out = *tm_ptr;\n  return true;\n#elif defined(__STDC_LIB_EXT1__)\n  // Uses localtime_s when available as localtime_r is only available from\n  // C23 standard.\n  return localtime_s(&seconds, out) != nullptr;\n#else\n  return localtime_r(&seconds, out) != nullptr;\n#endif\n}\n\n// Converts the given epoch time in milliseconds to a date string in the ISO\n// 8601 format, without the timezone information.\nstd::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {\n  struct tm time_struct;\n  if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))\n    return \"\";\n  // YYYY-MM-DDThh:mm:ss.sss\n  return StreamableToString(time_struct.tm_year + 1900) + \"-\" +\n         String::FormatIntWidth2(time_struct.tm_mon + 1) + \"-\" +\n         String::FormatIntWidth2(time_struct.tm_mday) + \"T\" +\n         String::FormatIntWidth2(time_struct.tm_hour) + \":\" +\n         String::FormatIntWidth2(time_struct.tm_min) + \":\" +\n         String::FormatIntWidth2(time_struct.tm_sec) + \".\" +\n         String::FormatIntWidthN(static_cast<int>(ms % 1000), 3);\n}\n\n// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.\nvoid XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,\n                                                     const char* data) {\n  const char* segment = data;\n  *stream << \"<![CDATA[\";\n  for (;;) {\n    const char* const next_segment = strstr(segment, \"]]>\");\n    if (next_segment != nullptr) {\n      stream->write(segment,\n                    static_cast<std::streamsize>(next_segment - segment));\n      *stream << \"]]>]]&gt;<![CDATA[\";\n      segment = next_segment + strlen(\"]]>\");\n    } else {\n      *stream << segment;\n      break;\n    }\n  }\n  *stream << \"]]>\";\n}\n\nvoid XmlUnitTestResultPrinter::OutputXmlAttribute(\n    std::ostream* stream, const std::string& element_name,\n    const std::string& name, const std::string& value) {\n  const std::vector<std::string>& allowed_names =\n      GetReservedOutputAttributesForElement(element_name);\n\n  GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=\n               allowed_names.end())\n      << \"Attribute \" << name << \" is not allowed for element <\" << element_name\n      << \">.\";\n\n  *stream << \" \" << name << \"=\\\"\" << EscapeXmlAttribute(value) << \"\\\"\";\n}\n\n// Streams a test suite XML stanza containing the given test result.\nvoid XmlUnitTestResultPrinter::OutputXmlTestSuiteForTestResult(\n    ::std::ostream* stream, const TestResult& result) {\n  // Output the boilerplate for a minimal test suite with one test.\n  *stream << \"  <testsuite\";\n  OutputXmlAttribute(stream, \"testsuite\", \"name\", \"NonTestSuiteFailure\");\n  OutputXmlAttribute(stream, \"testsuite\", \"tests\", \"1\");\n  OutputXmlAttribute(stream, \"testsuite\", \"failures\", \"1\");\n  OutputXmlAttribute(stream, \"testsuite\", \"disabled\", \"0\");\n  OutputXmlAttribute(stream, \"testsuite\", \"skipped\", \"0\");\n  OutputXmlAttribute(stream, \"testsuite\", \"errors\", \"0\");\n  OutputXmlAttribute(stream, \"testsuite\", \"time\",\n                     FormatTimeInMillisAsSeconds(result.elapsed_time()));\n  OutputXmlAttribute(\n      stream, \"testsuite\", \"timestamp\",\n      FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));\n  *stream << \">\";\n\n  // Output the boilerplate for a minimal test case with a single test.\n  *stream << \"    <testcase\";\n  OutputXmlAttribute(stream, \"testcase\", \"name\", \"\");\n  OutputXmlAttribute(stream, \"testcase\", \"status\", \"run\");\n  OutputXmlAttribute(stream, \"testcase\", \"result\", \"completed\");\n  OutputXmlAttribute(stream, \"testcase\", \"classname\", \"\");\n  OutputXmlAttribute(stream, \"testcase\", \"time\",\n                     FormatTimeInMillisAsSeconds(result.elapsed_time()));\n  OutputXmlAttribute(\n      stream, \"testcase\", \"timestamp\",\n      FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));\n\n  // Output the actual test result.\n  OutputXmlTestResult(stream, result);\n\n  // Complete the test suite.\n  *stream << \"  </testsuite>\\n\";\n}\n\n// Prints an XML representation of a TestInfo object.\nvoid XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,\n                                                 const char* test_suite_name,\n                                                 const TestInfo& test_info) {\n  const TestResult& result = *test_info.result();\n  const std::string kTestsuite = \"testcase\";\n\n  if (test_info.is_in_another_shard()) {\n    return;\n  }\n\n  *stream << \"    <testcase\";\n  OutputXmlAttribute(stream, kTestsuite, \"name\", test_info.name());\n\n  if (test_info.value_param() != nullptr) {\n    OutputXmlAttribute(stream, kTestsuite, \"value_param\",\n                       test_info.value_param());\n  }\n  if (test_info.type_param() != nullptr) {\n    OutputXmlAttribute(stream, kTestsuite, \"type_param\",\n                       test_info.type_param());\n  }\n\n  OutputXmlAttribute(stream, kTestsuite, \"file\", test_info.file());\n  OutputXmlAttribute(stream, kTestsuite, \"line\",\n                     StreamableToString(test_info.line()));\n  if (GTEST_FLAG_GET(list_tests)) {\n    *stream << \" />\\n\";\n    return;\n  }\n\n  OutputXmlAttribute(stream, kTestsuite, \"status\",\n                     test_info.should_run() ? \"run\" : \"notrun\");\n  OutputXmlAttribute(stream, kTestsuite, \"result\",\n                     test_info.should_run()\n                         ? (result.Skipped() ? \"skipped\" : \"completed\")\n                         : \"suppressed\");\n  OutputXmlAttribute(stream, kTestsuite, \"time\",\n                     FormatTimeInMillisAsSeconds(result.elapsed_time()));\n  OutputXmlAttribute(\n      stream, kTestsuite, \"timestamp\",\n      FormatEpochTimeInMillisAsIso8601(result.start_timestamp()));\n  OutputXmlAttribute(stream, kTestsuite, \"classname\", test_suite_name);\n\n  OutputXmlTestResult(stream, result);\n}\n\nvoid XmlUnitTestResultPrinter::OutputXmlTestResult(::std::ostream* stream,\n                                                   const TestResult& result) {\n  int failures = 0;\n  int skips = 0;\n  for (int i = 0; i < result.total_part_count(); ++i) {\n    const TestPartResult& part = result.GetTestPartResult(i);\n    if (part.failed()) {\n      if (++failures == 1 && skips == 0) {\n        *stream << \">\\n\";\n      }\n      const std::string location =\n          internal::FormatCompilerIndependentFileLocation(part.file_name(),\n                                                          part.line_number());\n      const std::string summary = location + \"\\n\" + part.summary();\n      *stream << \"      <failure message=\\\"\" << EscapeXmlAttribute(summary)\n              << \"\\\" type=\\\"\\\">\";\n      const std::string detail = location + \"\\n\" + part.message();\n      OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());\n      *stream << \"</failure>\\n\";\n    } else if (part.skipped()) {\n      if (++skips == 1 && failures == 0) {\n        *stream << \">\\n\";\n      }\n      const std::string location =\n          internal::FormatCompilerIndependentFileLocation(part.file_name(),\n                                                          part.line_number());\n      const std::string summary = location + \"\\n\" + part.summary();\n      *stream << \"      <skipped message=\\\"\"\n              << EscapeXmlAttribute(summary.c_str()) << \"\\\">\";\n      const std::string detail = location + \"\\n\" + part.message();\n      OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());\n      *stream << \"</skipped>\\n\";\n    }\n  }\n\n  if (failures == 0 && skips == 0 && result.test_property_count() == 0) {\n    *stream << \" />\\n\";\n  } else {\n    if (failures == 0 && skips == 0) {\n      *stream << \">\\n\";\n    }\n    OutputXmlTestProperties(stream, result);\n    *stream << \"    </testcase>\\n\";\n  }\n}\n\n// Prints an XML representation of a TestSuite object\nvoid XmlUnitTestResultPrinter::PrintXmlTestSuite(std::ostream* stream,\n                                                 const TestSuite& test_suite) {\n  const std::string kTestsuite = \"testsuite\";\n  *stream << \"  <\" << kTestsuite;\n  OutputXmlAttribute(stream, kTestsuite, \"name\", test_suite.name());\n  OutputXmlAttribute(stream, kTestsuite, \"tests\",\n                     StreamableToString(test_suite.reportable_test_count()));\n  if (!GTEST_FLAG_GET(list_tests)) {\n    OutputXmlAttribute(stream, kTestsuite, \"failures\",\n                       StreamableToString(test_suite.failed_test_count()));\n    OutputXmlAttribute(\n        stream, kTestsuite, \"disabled\",\n        StreamableToString(test_suite.reportable_disabled_test_count()));\n    OutputXmlAttribute(stream, kTestsuite, \"skipped\",\n                       StreamableToString(test_suite.skipped_test_count()));\n\n    OutputXmlAttribute(stream, kTestsuite, \"errors\", \"0\");\n\n    OutputXmlAttribute(stream, kTestsuite, \"time\",\n                       FormatTimeInMillisAsSeconds(test_suite.elapsed_time()));\n    OutputXmlAttribute(\n        stream, kTestsuite, \"timestamp\",\n        FormatEpochTimeInMillisAsIso8601(test_suite.start_timestamp()));\n    *stream << TestPropertiesAsXmlAttributes(test_suite.ad_hoc_test_result());\n  }\n  *stream << \">\\n\";\n  for (int i = 0; i < test_suite.total_test_count(); ++i) {\n    if (test_suite.GetTestInfo(i)->is_reportable())\n      OutputXmlTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));\n  }\n  *stream << \"  </\" << kTestsuite << \">\\n\";\n}\n\n// Prints an XML summary of unit_test to output stream out.\nvoid XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,\n                                                const UnitTest& unit_test) {\n  const std::string kTestsuites = \"testsuites\";\n\n  *stream << \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\";\n  *stream << \"<\" << kTestsuites;\n\n  OutputXmlAttribute(stream, kTestsuites, \"tests\",\n                     StreamableToString(unit_test.reportable_test_count()));\n  OutputXmlAttribute(stream, kTestsuites, \"failures\",\n                     StreamableToString(unit_test.failed_test_count()));\n  OutputXmlAttribute(\n      stream, kTestsuites, \"disabled\",\n      StreamableToString(unit_test.reportable_disabled_test_count()));\n  OutputXmlAttribute(stream, kTestsuites, \"errors\", \"0\");\n  OutputXmlAttribute(stream, kTestsuites, \"time\",\n                     FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));\n  OutputXmlAttribute(\n      stream, kTestsuites, \"timestamp\",\n      FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));\n\n  if (GTEST_FLAG_GET(shuffle)) {\n    OutputXmlAttribute(stream, kTestsuites, \"random_seed\",\n                       StreamableToString(unit_test.random_seed()));\n  }\n  *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());\n\n  OutputXmlAttribute(stream, kTestsuites, \"name\", \"AllTests\");\n  *stream << \">\\n\";\n\n  for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {\n    if (unit_test.GetTestSuite(i)->reportable_test_count() > 0)\n      PrintXmlTestSuite(stream, *unit_test.GetTestSuite(i));\n  }\n\n  // If there was a test failure outside of one of the test suites (like in a\n  // test environment) include that in the output.\n  if (unit_test.ad_hoc_test_result().Failed()) {\n    OutputXmlTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());\n  }\n\n  *stream << \"</\" << kTestsuites << \">\\n\";\n}\n\nvoid XmlUnitTestResultPrinter::PrintXmlTestsList(\n    std::ostream* stream, const std::vector<TestSuite*>& test_suites) {\n  const std::string kTestsuites = \"testsuites\";\n\n  *stream << \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\";\n  *stream << \"<\" << kTestsuites;\n\n  int total_tests = 0;\n  for (auto test_suite : test_suites) {\n    total_tests += test_suite->total_test_count();\n  }\n  OutputXmlAttribute(stream, kTestsuites, \"tests\",\n                     StreamableToString(total_tests));\n  OutputXmlAttribute(stream, kTestsuites, \"name\", \"AllTests\");\n  *stream << \">\\n\";\n\n  for (auto test_suite : test_suites) {\n    PrintXmlTestSuite(stream, *test_suite);\n  }\n  *stream << \"</\" << kTestsuites << \">\\n\";\n}\n\n// Produces a string representing the test properties in a result as space\n// delimited XML attributes based on the property key=\"value\" pairs.\nstd::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(\n    const TestResult& result) {\n  Message attributes;\n  for (int i = 0; i < result.test_property_count(); ++i) {\n    const TestProperty& property = result.GetTestProperty(i);\n    attributes << \" \" << property.key() << \"=\"\n               << \"\\\"\" << EscapeXmlAttribute(property.value()) << \"\\\"\";\n  }\n  return attributes.GetString();\n}\n\nvoid XmlUnitTestResultPrinter::OutputXmlTestProperties(\n    std::ostream* stream, const TestResult& result) {\n  const std::string kProperties = \"properties\";\n  const std::string kProperty = \"property\";\n\n  if (result.test_property_count() <= 0) {\n    return;\n  }\n\n  *stream << \"      <\" << kProperties << \">\\n\";\n  for (int i = 0; i < result.test_property_count(); ++i) {\n    const TestProperty& property = result.GetTestProperty(i);\n    *stream << \"        <\" << kProperty;\n    *stream << \" name=\\\"\" << EscapeXmlAttribute(property.key()) << \"\\\"\";\n    *stream << \" value=\\\"\" << EscapeXmlAttribute(property.value()) << \"\\\"\";\n    *stream << \"/>\\n\";\n  }\n  *stream << \"      </\" << kProperties << \">\\n\";\n}\n\n// End XmlUnitTestResultPrinter\n\n// This class generates an JSON output file.\nclass JsonUnitTestResultPrinter : public EmptyTestEventListener {\n public:\n  explicit JsonUnitTestResultPrinter(const char* output_file);\n\n  void OnTestIterationEnd(const UnitTest& unit_test, int iteration) override;\n\n  // Prints an JSON summary of all unit tests.\n  static void PrintJsonTestList(::std::ostream* stream,\n                                const std::vector<TestSuite*>& test_suites);\n\n private:\n  // Returns an JSON-escaped copy of the input string str.\n  static std::string EscapeJson(const std::string& str);\n\n  //// Verifies that the given attribute belongs to the given element and\n  //// streams the attribute as JSON.\n  static void OutputJsonKey(std::ostream* stream,\n                            const std::string& element_name,\n                            const std::string& name, const std::string& value,\n                            const std::string& indent, bool comma = true);\n  static void OutputJsonKey(std::ostream* stream,\n                            const std::string& element_name,\n                            const std::string& name, int value,\n                            const std::string& indent, bool comma = true);\n\n  // Streams a test suite JSON stanza containing the given test result.\n  //\n  // Requires: result.Failed()\n  static void OutputJsonTestSuiteForTestResult(::std::ostream* stream,\n                                               const TestResult& result);\n\n  // Streams a JSON representation of a TestResult object.\n  static void OutputJsonTestResult(::std::ostream* stream,\n                                   const TestResult& result);\n\n  // Streams a JSON representation of a TestInfo object.\n  static void OutputJsonTestInfo(::std::ostream* stream,\n                                 const char* test_suite_name,\n                                 const TestInfo& test_info);\n\n  // Prints a JSON representation of a TestSuite object\n  static void PrintJsonTestSuite(::std::ostream* stream,\n                                 const TestSuite& test_suite);\n\n  // Prints a JSON summary of unit_test to output stream out.\n  static void PrintJsonUnitTest(::std::ostream* stream,\n                                const UnitTest& unit_test);\n\n  // Produces a string representing the test properties in a result as\n  // a JSON dictionary.\n  static std::string TestPropertiesAsJson(const TestResult& result,\n                                          const std::string& indent);\n\n  // The output file.\n  const std::string output_file_;\n\n  JsonUnitTestResultPrinter(const JsonUnitTestResultPrinter&) = delete;\n  JsonUnitTestResultPrinter& operator=(const JsonUnitTestResultPrinter&) =\n      delete;\n};\n\n// Creates a new JsonUnitTestResultPrinter.\nJsonUnitTestResultPrinter::JsonUnitTestResultPrinter(const char* output_file)\n    : output_file_(output_file) {\n  if (output_file_.empty()) {\n    GTEST_LOG_(FATAL) << \"JSON output file may not be null\";\n  }\n}\n\nvoid JsonUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,\n                                                   int /*iteration*/) {\n  FILE* jsonout = OpenFileForWriting(output_file_);\n  std::stringstream stream;\n  PrintJsonUnitTest(&stream, unit_test);\n  fprintf(jsonout, \"%s\", StringStreamToString(&stream).c_str());\n  fclose(jsonout);\n}\n\n// Returns an JSON-escaped copy of the input string str.\nstd::string JsonUnitTestResultPrinter::EscapeJson(const std::string& str) {\n  Message m;\n\n  for (size_t i = 0; i < str.size(); ++i) {\n    const char ch = str[i];\n    switch (ch) {\n      case '\\\\':\n      case '\"':\n      case '/':\n        m << '\\\\' << ch;\n        break;\n      case '\\b':\n        m << \"\\\\b\";\n        break;\n      case '\\t':\n        m << \"\\\\t\";\n        break;\n      case '\\n':\n        m << \"\\\\n\";\n        break;\n      case '\\f':\n        m << \"\\\\f\";\n        break;\n      case '\\r':\n        m << \"\\\\r\";\n        break;\n      default:\n        if (ch < ' ') {\n          m << \"\\\\u00\" << String::FormatByte(static_cast<unsigned char>(ch));\n        } else {\n          m << ch;\n        }\n        break;\n    }\n  }\n\n  return m.GetString();\n}\n\n// The following routines generate an JSON representation of a UnitTest\n// object.\n\n// Formats the given time in milliseconds as seconds.\nstatic std::string FormatTimeInMillisAsDuration(TimeInMillis ms) {\n  ::std::stringstream ss;\n  ss << (static_cast<double>(ms) * 1e-3) << \"s\";\n  return ss.str();\n}\n\n// Converts the given epoch time in milliseconds to a date string in the\n// RFC3339 format, without the timezone information.\nstatic std::string FormatEpochTimeInMillisAsRFC3339(TimeInMillis ms) {\n  struct tm time_struct;\n  if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))\n    return \"\";\n  // YYYY-MM-DDThh:mm:ss\n  return StreamableToString(time_struct.tm_year + 1900) + \"-\" +\n         String::FormatIntWidth2(time_struct.tm_mon + 1) + \"-\" +\n         String::FormatIntWidth2(time_struct.tm_mday) + \"T\" +\n         String::FormatIntWidth2(time_struct.tm_hour) + \":\" +\n         String::FormatIntWidth2(time_struct.tm_min) + \":\" +\n         String::FormatIntWidth2(time_struct.tm_sec) + \"Z\";\n}\n\nstatic inline std::string Indent(size_t width) {\n  return std::string(width, ' ');\n}\n\nvoid JsonUnitTestResultPrinter::OutputJsonKey(std::ostream* stream,\n                                              const std::string& element_name,\n                                              const std::string& name,\n                                              const std::string& value,\n                                              const std::string& indent,\n                                              bool comma) {\n  const std::vector<std::string>& allowed_names =\n      GetReservedOutputAttributesForElement(element_name);\n\n  GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=\n               allowed_names.end())\n      << \"Key \\\"\" << name << \"\\\" is not allowed for value \\\"\" << element_name\n      << \"\\\".\";\n\n  *stream << indent << \"\\\"\" << name << \"\\\": \\\"\" << EscapeJson(value) << \"\\\"\";\n  if (comma) *stream << \",\\n\";\n}\n\nvoid JsonUnitTestResultPrinter::OutputJsonKey(\n    std::ostream* stream, const std::string& element_name,\n    const std::string& name, int value, const std::string& indent, bool comma) {\n  const std::vector<std::string>& allowed_names =\n      GetReservedOutputAttributesForElement(element_name);\n\n  GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=\n               allowed_names.end())\n      << \"Key \\\"\" << name << \"\\\" is not allowed for value \\\"\" << element_name\n      << \"\\\".\";\n\n  *stream << indent << \"\\\"\" << name << \"\\\": \" << StreamableToString(value);\n  if (comma) *stream << \",\\n\";\n}\n\n// Streams a test suite JSON stanza containing the given test result.\nvoid JsonUnitTestResultPrinter::OutputJsonTestSuiteForTestResult(\n    ::std::ostream* stream, const TestResult& result) {\n  // Output the boilerplate for a new test suite.\n  *stream << Indent(4) << \"{\\n\";\n  OutputJsonKey(stream, \"testsuite\", \"name\", \"NonTestSuiteFailure\", Indent(6));\n  OutputJsonKey(stream, \"testsuite\", \"tests\", 1, Indent(6));\n  if (!GTEST_FLAG_GET(list_tests)) {\n    OutputJsonKey(stream, \"testsuite\", \"failures\", 1, Indent(6));\n    OutputJsonKey(stream, \"testsuite\", \"disabled\", 0, Indent(6));\n    OutputJsonKey(stream, \"testsuite\", \"skipped\", 0, Indent(6));\n    OutputJsonKey(stream, \"testsuite\", \"errors\", 0, Indent(6));\n    OutputJsonKey(stream, \"testsuite\", \"time\",\n                  FormatTimeInMillisAsDuration(result.elapsed_time()),\n                  Indent(6));\n    OutputJsonKey(stream, \"testsuite\", \"timestamp\",\n                  FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),\n                  Indent(6));\n  }\n  *stream << Indent(6) << \"\\\"testsuite\\\": [\\n\";\n\n  // Output the boilerplate for a new test case.\n  *stream << Indent(8) << \"{\\n\";\n  OutputJsonKey(stream, \"testcase\", \"name\", \"\", Indent(10));\n  OutputJsonKey(stream, \"testcase\", \"status\", \"RUN\", Indent(10));\n  OutputJsonKey(stream, \"testcase\", \"result\", \"COMPLETED\", Indent(10));\n  OutputJsonKey(stream, \"testcase\", \"timestamp\",\n                FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),\n                Indent(10));\n  OutputJsonKey(stream, \"testcase\", \"time\",\n                FormatTimeInMillisAsDuration(result.elapsed_time()),\n                Indent(10));\n  OutputJsonKey(stream, \"testcase\", \"classname\", \"\", Indent(10), false);\n  *stream << TestPropertiesAsJson(result, Indent(10));\n\n  // Output the actual test result.\n  OutputJsonTestResult(stream, result);\n\n  // Finish the test suite.\n  *stream << \"\\n\" << Indent(6) << \"]\\n\" << Indent(4) << \"}\";\n}\n\n// Prints a JSON representation of a TestInfo object.\nvoid JsonUnitTestResultPrinter::OutputJsonTestInfo(::std::ostream* stream,\n                                                   const char* test_suite_name,\n                                                   const TestInfo& test_info) {\n  const TestResult& result = *test_info.result();\n  const std::string kTestsuite = \"testcase\";\n  const std::string kIndent = Indent(10);\n\n  *stream << Indent(8) << \"{\\n\";\n  OutputJsonKey(stream, kTestsuite, \"name\", test_info.name(), kIndent);\n\n  if (test_info.value_param() != nullptr) {\n    OutputJsonKey(stream, kTestsuite, \"value_param\", test_info.value_param(),\n                  kIndent);\n  }\n  if (test_info.type_param() != nullptr) {\n    OutputJsonKey(stream, kTestsuite, \"type_param\", test_info.type_param(),\n                  kIndent);\n  }\n\n  OutputJsonKey(stream, kTestsuite, \"file\", test_info.file(), kIndent);\n  OutputJsonKey(stream, kTestsuite, \"line\", test_info.line(), kIndent, false);\n  if (GTEST_FLAG_GET(list_tests)) {\n    *stream << \"\\n\" << Indent(8) << \"}\";\n    return;\n  } else {\n    *stream << \",\\n\";\n  }\n\n  OutputJsonKey(stream, kTestsuite, \"status\",\n                test_info.should_run() ? \"RUN\" : \"NOTRUN\", kIndent);\n  OutputJsonKey(stream, kTestsuite, \"result\",\n                test_info.should_run()\n                    ? (result.Skipped() ? \"SKIPPED\" : \"COMPLETED\")\n                    : \"SUPPRESSED\",\n                kIndent);\n  OutputJsonKey(stream, kTestsuite, \"timestamp\",\n                FormatEpochTimeInMillisAsRFC3339(result.start_timestamp()),\n                kIndent);\n  OutputJsonKey(stream, kTestsuite, \"time\",\n                FormatTimeInMillisAsDuration(result.elapsed_time()), kIndent);\n  OutputJsonKey(stream, kTestsuite, \"classname\", test_suite_name, kIndent,\n                false);\n  *stream << TestPropertiesAsJson(result, kIndent);\n\n  OutputJsonTestResult(stream, result);\n}\n\nvoid JsonUnitTestResultPrinter::OutputJsonTestResult(::std::ostream* stream,\n                                                     const TestResult& result) {\n  const std::string kIndent = Indent(10);\n\n  int failures = 0;\n  for (int i = 0; i < result.total_part_count(); ++i) {\n    const TestPartResult& part = result.GetTestPartResult(i);\n    if (part.failed()) {\n      *stream << \",\\n\";\n      if (++failures == 1) {\n        *stream << kIndent << \"\\\"\"\n                << \"failures\"\n                << \"\\\": [\\n\";\n      }\n      const std::string location =\n          internal::FormatCompilerIndependentFileLocation(part.file_name(),\n                                                          part.line_number());\n      const std::string message = EscapeJson(location + \"\\n\" + part.message());\n      *stream << kIndent << \"  {\\n\"\n              << kIndent << \"    \\\"failure\\\": \\\"\" << message << \"\\\",\\n\"\n              << kIndent << \"    \\\"type\\\": \\\"\\\"\\n\"\n              << kIndent << \"  }\";\n    }\n  }\n\n  if (failures > 0) *stream << \"\\n\" << kIndent << \"]\";\n  *stream << \"\\n\" << Indent(8) << \"}\";\n}\n\n// Prints an JSON representation of a TestSuite object\nvoid JsonUnitTestResultPrinter::PrintJsonTestSuite(\n    std::ostream* stream, const TestSuite& test_suite) {\n  const std::string kTestsuite = \"testsuite\";\n  const std::string kIndent = Indent(6);\n\n  *stream << Indent(4) << \"{\\n\";\n  OutputJsonKey(stream, kTestsuite, \"name\", test_suite.name(), kIndent);\n  OutputJsonKey(stream, kTestsuite, \"tests\", test_suite.reportable_test_count(),\n                kIndent);\n  if (!GTEST_FLAG_GET(list_tests)) {\n    OutputJsonKey(stream, kTestsuite, \"failures\",\n                  test_suite.failed_test_count(), kIndent);\n    OutputJsonKey(stream, kTestsuite, \"disabled\",\n                  test_suite.reportable_disabled_test_count(), kIndent);\n    OutputJsonKey(stream, kTestsuite, \"errors\", 0, kIndent);\n    OutputJsonKey(\n        stream, kTestsuite, \"timestamp\",\n        FormatEpochTimeInMillisAsRFC3339(test_suite.start_timestamp()),\n        kIndent);\n    OutputJsonKey(stream, kTestsuite, \"time\",\n                  FormatTimeInMillisAsDuration(test_suite.elapsed_time()),\n                  kIndent, false);\n    *stream << TestPropertiesAsJson(test_suite.ad_hoc_test_result(), kIndent)\n            << \",\\n\";\n  }\n\n  *stream << kIndent << \"\\\"\" << kTestsuite << \"\\\": [\\n\";\n\n  bool comma = false;\n  for (int i = 0; i < test_suite.total_test_count(); ++i) {\n    if (test_suite.GetTestInfo(i)->is_reportable()) {\n      if (comma) {\n        *stream << \",\\n\";\n      } else {\n        comma = true;\n      }\n      OutputJsonTestInfo(stream, test_suite.name(), *test_suite.GetTestInfo(i));\n    }\n  }\n  *stream << \"\\n\" << kIndent << \"]\\n\" << Indent(4) << \"}\";\n}\n\n// Prints a JSON summary of unit_test to output stream out.\nvoid JsonUnitTestResultPrinter::PrintJsonUnitTest(std::ostream* stream,\n                                                  const UnitTest& unit_test) {\n  const std::string kTestsuites = \"testsuites\";\n  const std::string kIndent = Indent(2);\n  *stream << \"{\\n\";\n\n  OutputJsonKey(stream, kTestsuites, \"tests\", unit_test.reportable_test_count(),\n                kIndent);\n  OutputJsonKey(stream, kTestsuites, \"failures\", unit_test.failed_test_count(),\n                kIndent);\n  OutputJsonKey(stream, kTestsuites, \"disabled\",\n                unit_test.reportable_disabled_test_count(), kIndent);\n  OutputJsonKey(stream, kTestsuites, \"errors\", 0, kIndent);\n  if (GTEST_FLAG_GET(shuffle)) {\n    OutputJsonKey(stream, kTestsuites, \"random_seed\", unit_test.random_seed(),\n                  kIndent);\n  }\n  OutputJsonKey(stream, kTestsuites, \"timestamp\",\n                FormatEpochTimeInMillisAsRFC3339(unit_test.start_timestamp()),\n                kIndent);\n  OutputJsonKey(stream, kTestsuites, \"time\",\n                FormatTimeInMillisAsDuration(unit_test.elapsed_time()), kIndent,\n                false);\n\n  *stream << TestPropertiesAsJson(unit_test.ad_hoc_test_result(), kIndent)\n          << \",\\n\";\n\n  OutputJsonKey(stream, kTestsuites, \"name\", \"AllTests\", kIndent);\n  *stream << kIndent << \"\\\"\" << kTestsuites << \"\\\": [\\n\";\n\n  bool comma = false;\n  for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {\n    if (unit_test.GetTestSuite(i)->reportable_test_count() > 0) {\n      if (comma) {\n        *stream << \",\\n\";\n      } else {\n        comma = true;\n      }\n      PrintJsonTestSuite(stream, *unit_test.GetTestSuite(i));\n    }\n  }\n\n  // If there was a test failure outside of one of the test suites (like in a\n  // test environment) include that in the output.\n  if (unit_test.ad_hoc_test_result().Failed()) {\n    OutputJsonTestSuiteForTestResult(stream, unit_test.ad_hoc_test_result());\n  }\n\n  *stream << \"\\n\"\n          << kIndent << \"]\\n\"\n          << \"}\\n\";\n}\n\nvoid JsonUnitTestResultPrinter::PrintJsonTestList(\n    std::ostream* stream, const std::vector<TestSuite*>& test_suites) {\n  const std::string kTestsuites = \"testsuites\";\n  const std::string kIndent = Indent(2);\n  *stream << \"{\\n\";\n  int total_tests = 0;\n  for (auto test_suite : test_suites) {\n    total_tests += test_suite->total_test_count();\n  }\n  OutputJsonKey(stream, kTestsuites, \"tests\", total_tests, kIndent);\n\n  OutputJsonKey(stream, kTestsuites, \"name\", \"AllTests\", kIndent);\n  *stream << kIndent << \"\\\"\" << kTestsuites << \"\\\": [\\n\";\n\n  for (size_t i = 0; i < test_suites.size(); ++i) {\n    if (i != 0) {\n      *stream << \",\\n\";\n    }\n    PrintJsonTestSuite(stream, *test_suites[i]);\n  }\n\n  *stream << \"\\n\"\n          << kIndent << \"]\\n\"\n          << \"}\\n\";\n}\n// Produces a string representing the test properties in a result as\n// a JSON dictionary.\nstd::string JsonUnitTestResultPrinter::TestPropertiesAsJson(\n    const TestResult& result, const std::string& indent) {\n  Message attributes;\n  for (int i = 0; i < result.test_property_count(); ++i) {\n    const TestProperty& property = result.GetTestProperty(i);\n    attributes << \",\\n\"\n               << indent << \"\\\"\" << property.key() << \"\\\": \"\n               << \"\\\"\" << EscapeJson(property.value()) << \"\\\"\";\n  }\n  return attributes.GetString();\n}\n\n// End JsonUnitTestResultPrinter\n\n#if GTEST_CAN_STREAM_RESULTS_\n\n// Checks if str contains '=', '&', '%' or '\\n' characters. If yes,\n// replaces them by \"%xx\" where xx is their hexadecimal value. For\n// example, replaces \"=\" with \"%3D\".  This algorithm is O(strlen(str))\n// in both time and space -- important as the input str may contain an\n// arbitrarily long test failure message and stack trace.\nstd::string StreamingListener::UrlEncode(const char* str) {\n  std::string result;\n  result.reserve(strlen(str) + 1);\n  for (char ch = *str; ch != '\\0'; ch = *++str) {\n    switch (ch) {\n      case '%':\n      case '=':\n      case '&':\n      case '\\n':\n        result.append(\"%\" + String::FormatByte(static_cast<unsigned char>(ch)));\n        break;\n      default:\n        result.push_back(ch);\n        break;\n    }\n  }\n  return result;\n}\n\nvoid StreamingListener::SocketWriter::MakeConnection() {\n  GTEST_CHECK_(sockfd_ == -1)\n      << \"MakeConnection() can't be called when there is already a connection.\";\n\n  addrinfo hints;\n  memset(&hints, 0, sizeof(hints));\n  hints.ai_family = AF_UNSPEC;  // To allow both IPv4 and IPv6 addresses.\n  hints.ai_socktype = SOCK_STREAM;\n  addrinfo* servinfo = nullptr;\n\n  // Use the getaddrinfo() to get a linked list of IP addresses for\n  // the given host name.\n  const int error_num =\n      getaddrinfo(host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);\n  if (error_num != 0) {\n    GTEST_LOG_(WARNING) << \"stream_result_to: getaddrinfo() failed: \"\n                        << gai_strerror(error_num);\n  }\n\n  // Loop through all the results and connect to the first we can.\n  for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != nullptr;\n       cur_addr = cur_addr->ai_next) {\n    sockfd_ = socket(cur_addr->ai_family, cur_addr->ai_socktype,\n                     cur_addr->ai_protocol);\n    if (sockfd_ != -1) {\n      // Connect the client socket to the server socket.\n      if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {\n        close(sockfd_);\n        sockfd_ = -1;\n      }\n    }\n  }\n\n  freeaddrinfo(servinfo);  // all done with this structure\n\n  if (sockfd_ == -1) {\n    GTEST_LOG_(WARNING) << \"stream_result_to: failed to connect to \"\n                        << host_name_ << \":\" << port_num_;\n  }\n}\n\n// End of class Streaming Listener\n#endif  // GTEST_CAN_STREAM_RESULTS__\n\n// class OsStackTraceGetter\n\nconst char* const OsStackTraceGetterInterface::kElidedFramesMarker =\n    \"... \" GTEST_NAME_ \" internal frames ...\";\n\nstd::string OsStackTraceGetter::CurrentStackTrace(int max_depth, int skip_count)\n    GTEST_LOCK_EXCLUDED_(mutex_) {\n#if GTEST_HAS_ABSL\n  std::string result;\n\n  if (max_depth <= 0) {\n    return result;\n  }\n\n  max_depth = std::min(max_depth, kMaxStackTraceDepth);\n\n  std::vector<void*> raw_stack(max_depth);\n  // Skips the frames requested by the caller, plus this function.\n  const int raw_stack_size =\n      absl::GetStackTrace(&raw_stack[0], max_depth, skip_count + 1);\n\n  void* caller_frame = nullptr;\n  {\n    MutexLock lock(&mutex_);\n    caller_frame = caller_frame_;\n  }\n\n  for (int i = 0; i < raw_stack_size; ++i) {\n    if (raw_stack[i] == caller_frame &&\n        !GTEST_FLAG_GET(show_internal_stack_frames)) {\n      // Add a marker to the trace and stop adding frames.\n      absl::StrAppend(&result, kElidedFramesMarker, \"\\n\");\n      break;\n    }\n\n    char tmp[1024];\n    const char* symbol = \"(unknown)\";\n    if (absl::Symbolize(raw_stack[i], tmp, sizeof(tmp))) {\n      symbol = tmp;\n    }\n\n    char line[1024];\n    snprintf(line, sizeof(line), \"  %p: %s\\n\", raw_stack[i], symbol);\n    result += line;\n  }\n\n  return result;\n\n#else   // !GTEST_HAS_ABSL\n  static_cast<void>(max_depth);\n  static_cast<void>(skip_count);\n  return \"\";\n#endif  // GTEST_HAS_ABSL\n}\n\nvoid OsStackTraceGetter::UponLeavingGTest() GTEST_LOCK_EXCLUDED_(mutex_) {\n#if GTEST_HAS_ABSL\n  void* caller_frame = nullptr;\n  if (absl::GetStackTrace(&caller_frame, 1, 3) <= 0) {\n    caller_frame = nullptr;\n  }\n\n  MutexLock lock(&mutex_);\n  caller_frame_ = caller_frame;\n#endif  // GTEST_HAS_ABSL\n}\n\n// A helper class that creates the premature-exit file in its\n// constructor and deletes the file in its destructor.\nclass ScopedPrematureExitFile {\n public:\n  explicit ScopedPrematureExitFile(const char* premature_exit_filepath)\n      : premature_exit_filepath_(\n            premature_exit_filepath ? premature_exit_filepath : \"\") {\n    // If a path to the premature-exit file is specified...\n    if (!premature_exit_filepath_.empty()) {\n      // create the file with a single \"0\" character in it.  I/O\n      // errors are ignored as there's nothing better we can do and we\n      // don't want to fail the test because of this.\n      FILE* pfile = posix::FOpen(premature_exit_filepath_.c_str(), \"w\");\n      fwrite(\"0\", 1, 1, pfile);\n      fclose(pfile);\n    }\n  }\n\n  ~ScopedPrematureExitFile() {\n#if !defined GTEST_OS_ESP8266\n    if (!premature_exit_filepath_.empty()) {\n      int retval = remove(premature_exit_filepath_.c_str());\n      if (retval) {\n        GTEST_LOG_(ERROR) << \"Failed to remove premature exit filepath \\\"\"\n                          << premature_exit_filepath_ << \"\\\" with error \"\n                          << retval;\n      }\n    }\n#endif\n  }\n\n private:\n  const std::string premature_exit_filepath_;\n\n  ScopedPrematureExitFile(const ScopedPrematureExitFile&) = delete;\n  ScopedPrematureExitFile& operator=(const ScopedPrematureExitFile&) = delete;\n};\n\n}  // namespace internal\n\n// class TestEventListeners\n\nTestEventListeners::TestEventListeners()\n    : repeater_(new internal::TestEventRepeater()),\n      default_result_printer_(nullptr),\n      default_xml_generator_(nullptr) {}\n\nTestEventListeners::~TestEventListeners() { delete repeater_; }\n\n// Returns the standard listener responsible for the default console\n// output.  Can be removed from the listeners list to shut down default\n// console output.  Note that removing this object from the listener list\n// with Release transfers its ownership to the user.\nvoid TestEventListeners::Append(TestEventListener* listener) {\n  repeater_->Append(listener);\n}\n\n// Removes the given event listener from the list and returns it.  It then\n// becomes the caller's responsibility to delete the listener. Returns\n// NULL if the listener is not found in the list.\nTestEventListener* TestEventListeners::Release(TestEventListener* listener) {\n  if (listener == default_result_printer_)\n    default_result_printer_ = nullptr;\n  else if (listener == default_xml_generator_)\n    default_xml_generator_ = nullptr;\n  return repeater_->Release(listener);\n}\n\n// Returns repeater that broadcasts the TestEventListener events to all\n// subscribers.\nTestEventListener* TestEventListeners::repeater() { return repeater_; }\n\n// Sets the default_result_printer attribute to the provided listener.\n// The listener is also added to the listener list and previous\n// default_result_printer is removed from it and deleted. The listener can\n// also be NULL in which case it will not be added to the list. Does\n// nothing if the previous and the current listener objects are the same.\nvoid TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {\n  if (default_result_printer_ != listener) {\n    // It is an error to pass this method a listener that is already in the\n    // list.\n    delete Release(default_result_printer_);\n    default_result_printer_ = listener;\n    if (listener != nullptr) Append(listener);\n  }\n}\n\n// Sets the default_xml_generator attribute to the provided listener.  The\n// listener is also added to the listener list and previous\n// default_xml_generator is removed from it and deleted. The listener can\n// also be NULL in which case it will not be added to the list. Does\n// nothing if the previous and the current listener objects are the same.\nvoid TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {\n  if (default_xml_generator_ != listener) {\n    // It is an error to pass this method a listener that is already in the\n    // list.\n    delete Release(default_xml_generator_);\n    default_xml_generator_ = listener;\n    if (listener != nullptr) Append(listener);\n  }\n}\n\n// Controls whether events will be forwarded by the repeater to the\n// listeners in the list.\nbool TestEventListeners::EventForwardingEnabled() const {\n  return repeater_->forwarding_enabled();\n}\n\nvoid TestEventListeners::SuppressEventForwarding() {\n  repeater_->set_forwarding_enabled(false);\n}\n\n// class UnitTest\n\n// Gets the singleton UnitTest object.  The first time this method is\n// called, a UnitTest object is constructed and returned.  Consecutive\n// calls will return the same object.\n//\n// We don't protect this under mutex_ as a user is not supposed to\n// call this before main() starts, from which point on the return\n// value will never change.\nUnitTest* UnitTest::GetInstance() {\n  // CodeGear C++Builder insists on a public destructor for the\n  // default implementation.  Use this implementation to keep good OO\n  // design with private destructor.\n\n#if defined(__BORLANDC__)\n  static UnitTest* const instance = new UnitTest;\n  return instance;\n#else\n  static UnitTest instance;\n  return &instance;\n#endif  // defined(__BORLANDC__)\n}\n\n// Gets the number of successful test suites.\nint UnitTest::successful_test_suite_count() const {\n  return impl()->successful_test_suite_count();\n}\n\n// Gets the number of failed test suites.\nint UnitTest::failed_test_suite_count() const {\n  return impl()->failed_test_suite_count();\n}\n\n// Gets the number of all test suites.\nint UnitTest::total_test_suite_count() const {\n  return impl()->total_test_suite_count();\n}\n\n// Gets the number of all test suites that contain at least one test\n// that should run.\nint UnitTest::test_suite_to_run_count() const {\n  return impl()->test_suite_to_run_count();\n}\n\n//  Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\nint UnitTest::successful_test_case_count() const {\n  return impl()->successful_test_suite_count();\n}\nint UnitTest::failed_test_case_count() const {\n  return impl()->failed_test_suite_count();\n}\nint UnitTest::total_test_case_count() const {\n  return impl()->total_test_suite_count();\n}\nint UnitTest::test_case_to_run_count() const {\n  return impl()->test_suite_to_run_count();\n}\n#endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n// Gets the number of successful tests.\nint UnitTest::successful_test_count() const {\n  return impl()->successful_test_count();\n}\n\n// Gets the number of skipped tests.\nint UnitTest::skipped_test_count() const {\n  return impl()->skipped_test_count();\n}\n\n// Gets the number of failed tests.\nint UnitTest::failed_test_count() const { return impl()->failed_test_count(); }\n\n// Gets the number of disabled tests that will be reported in the XML report.\nint UnitTest::reportable_disabled_test_count() const {\n  return impl()->reportable_disabled_test_count();\n}\n\n// Gets the number of disabled tests.\nint UnitTest::disabled_test_count() const {\n  return impl()->disabled_test_count();\n}\n\n// Gets the number of tests to be printed in the XML report.\nint UnitTest::reportable_test_count() const {\n  return impl()->reportable_test_count();\n}\n\n// Gets the number of all tests.\nint UnitTest::total_test_count() const { return impl()->total_test_count(); }\n\n// Gets the number of tests that should run.\nint UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }\n\n// Gets the time of the test program start, in ms from the start of the\n// UNIX epoch.\ninternal::TimeInMillis UnitTest::start_timestamp() const {\n  return impl()->start_timestamp();\n}\n\n// Gets the elapsed time, in milliseconds.\ninternal::TimeInMillis UnitTest::elapsed_time() const {\n  return impl()->elapsed_time();\n}\n\n// Returns true if and only if the unit test passed (i.e. all test suites\n// passed).\nbool UnitTest::Passed() const { return impl()->Passed(); }\n\n// Returns true if and only if the unit test failed (i.e. some test suite\n// failed or something outside of all tests failed).\nbool UnitTest::Failed() const { return impl()->Failed(); }\n\n// Gets the i-th test suite among all the test suites. i can range from 0 to\n// total_test_suite_count() - 1. If i is not in that range, returns NULL.\nconst TestSuite* UnitTest::GetTestSuite(int i) const {\n  return impl()->GetTestSuite(i);\n}\n\n//  Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\nconst TestCase* UnitTest::GetTestCase(int i) const {\n  return impl()->GetTestCase(i);\n}\n#endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n// Returns the TestResult containing information on test failures and\n// properties logged outside of individual test suites.\nconst TestResult& UnitTest::ad_hoc_test_result() const {\n  return *impl()->ad_hoc_test_result();\n}\n\n// Gets the i-th test suite among all the test suites. i can range from 0 to\n// total_test_suite_count() - 1. If i is not in that range, returns NULL.\nTestSuite* UnitTest::GetMutableTestSuite(int i) {\n  return impl()->GetMutableSuiteCase(i);\n}\n\n// Returns the list of event listeners that can be used to track events\n// inside Google Test.\nTestEventListeners& UnitTest::listeners() { return *impl()->listeners(); }\n\n// Registers and returns a global test environment.  When a test\n// program is run, all global test environments will be set-up in the\n// order they were registered.  After all tests in the program have\n// finished, all global test environments will be torn-down in the\n// *reverse* order they were registered.\n//\n// The UnitTest object takes ownership of the given environment.\n//\n// We don't protect this under mutex_, as we only support calling it\n// from the main thread.\nEnvironment* UnitTest::AddEnvironment(Environment* env) {\n  if (env == nullptr) {\n    return nullptr;\n  }\n\n  impl_->environments().push_back(env);\n  return env;\n}\n\n// Adds a TestPartResult to the current TestResult object.  All Google Test\n// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call\n// this to report their results.  The user code should use the\n// assertion macros instead of calling this directly.\nvoid UnitTest::AddTestPartResult(TestPartResult::Type result_type,\n                                 const char* file_name, int line_number,\n                                 const std::string& message,\n                                 const std::string& os_stack_trace)\n    GTEST_LOCK_EXCLUDED_(mutex_) {\n  Message msg;\n  msg << message;\n\n  internal::MutexLock lock(&mutex_);\n  if (impl_->gtest_trace_stack().size() > 0) {\n    msg << \"\\n\" << GTEST_NAME_ << \" trace:\";\n\n    for (size_t i = impl_->gtest_trace_stack().size(); i > 0; --i) {\n      const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];\n      msg << \"\\n\"\n          << internal::FormatFileLocation(trace.file, trace.line) << \" \"\n          << trace.message;\n    }\n  }\n\n  if (os_stack_trace.c_str() != nullptr && !os_stack_trace.empty()) {\n    msg << internal::kStackTraceMarker << os_stack_trace;\n  }\n\n  const TestPartResult result = TestPartResult(\n      result_type, file_name, line_number, msg.GetString().c_str());\n  impl_->GetTestPartResultReporterForCurrentThread()->ReportTestPartResult(\n      result);\n\n  if (result_type != TestPartResult::kSuccess &&\n      result_type != TestPartResult::kSkip) {\n    // gtest_break_on_failure takes precedence over\n    // gtest_throw_on_failure.  This allows a user to set the latter\n    // in the code (perhaps in order to use Google Test assertions\n    // with another testing framework) and specify the former on the\n    // command line for debugging.\n    if (GTEST_FLAG_GET(break_on_failure)) {\n#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT\n      // Using DebugBreak on Windows allows gtest to still break into a debugger\n      // when a failure happens and both the --gtest_break_on_failure and\n      // the --gtest_catch_exceptions flags are specified.\n      DebugBreak();\n#elif (!defined(__native_client__)) &&            \\\n    ((defined(__clang__) || defined(__GNUC__)) && \\\n     (defined(__x86_64__) || defined(__i386__)))\n      // with clang/gcc we can achieve the same effect on x86 by invoking int3\n      asm(\"int3\");\n#else\n      // Dereference nullptr through a volatile pointer to prevent the compiler\n      // from removing. We use this rather than abort() or __builtin_trap() for\n      // portability: some debuggers don't correctly trap abort().\n      *static_cast<volatile int*>(nullptr) = 1;\n#endif  // GTEST_OS_WINDOWS\n    } else if (GTEST_FLAG_GET(throw_on_failure)) {\n#if GTEST_HAS_EXCEPTIONS\n      throw internal::GoogleTestFailureException(result);\n#else\n      // We cannot call abort() as it generates a pop-up in debug mode\n      // that cannot be suppressed in VC 7.1 or below.\n      exit(1);\n#endif\n    }\n  }\n}\n\n// Adds a TestProperty to the current TestResult object when invoked from\n// inside a test, to current TestSuite's ad_hoc_test_result_ when invoked\n// from SetUpTestSuite or TearDownTestSuite, or to the global property set\n// when invoked elsewhere.  If the result already contains a property with\n// the same key, the value will be updated.\nvoid UnitTest::RecordProperty(const std::string& key,\n                              const std::string& value) {\n  impl_->RecordProperty(TestProperty(key, value));\n}\n\n// Runs all tests in this UnitTest object and prints the result.\n// Returns 0 if successful, or 1 otherwise.\n//\n// We don't protect this under mutex_, as we only support calling it\n// from the main thread.\nint UnitTest::Run() {\n  const bool in_death_test_child_process =\n      GTEST_FLAG_GET(internal_run_death_test).length() > 0;\n\n  // Google Test implements this protocol for catching that a test\n  // program exits before returning control to Google Test:\n  //\n  //   1. Upon start, Google Test creates a file whose absolute path\n  //      is specified by the environment variable\n  //      TEST_PREMATURE_EXIT_FILE.\n  //   2. When Google Test has finished its work, it deletes the file.\n  //\n  // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before\n  // running a Google-Test-based test program and check the existence\n  // of the file at the end of the test execution to see if it has\n  // exited prematurely.\n\n  // If we are in the child process of a death test, don't\n  // create/delete the premature exit file, as doing so is unnecessary\n  // and will confuse the parent process.  Otherwise, create/delete\n  // the file upon entering/leaving this function.  If the program\n  // somehow exits before this function has a chance to return, the\n  // premature-exit file will be left undeleted, causing a test runner\n  // that understands the premature-exit-file protocol to report the\n  // test as having failed.\n  const internal::ScopedPrematureExitFile premature_exit_file(\n      in_death_test_child_process\n          ? nullptr\n          : internal::posix::GetEnv(\"TEST_PREMATURE_EXIT_FILE\"));\n\n  // Captures the value of GTEST_FLAG(catch_exceptions).  This value will be\n  // used for the duration of the program.\n  impl()->set_catch_exceptions(GTEST_FLAG_GET(catch_exceptions));\n\n#if GTEST_OS_WINDOWS\n  // Either the user wants Google Test to catch exceptions thrown by the\n  // tests or this is executing in the context of death test child\n  // process. In either case the user does not want to see pop-up dialogs\n  // about crashes - they are expected.\n  if (impl()->catch_exceptions() || in_death_test_child_process) {\n#if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT\n    // SetErrorMode doesn't exist on CE.\n    SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |\n                 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);\n#endif  // !GTEST_OS_WINDOWS_MOBILE\n\n#if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE\n    // Death test children can be terminated with _abort().  On Windows,\n    // _abort() can show a dialog with a warning message.  This forces the\n    // abort message to go to stderr instead.\n    _set_error_mode(_OUT_TO_STDERR);\n#endif\n\n#if defined(_MSC_VER) && !GTEST_OS_WINDOWS_MOBILE\n    // In the debug version, Visual Studio pops up a separate dialog\n    // offering a choice to debug the aborted program. We need to suppress\n    // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement\n    // executed. Google Test will notify the user of any unexpected\n    // failure via stderr.\n    if (!GTEST_FLAG_GET(break_on_failure))\n      _set_abort_behavior(\n          0x0,                                    // Clear the following flags:\n          _WRITE_ABORT_MSG | _CALL_REPORTFAULT);  // pop-up window, core dump.\n\n    // In debug mode, the Windows CRT can crash with an assertion over invalid\n    // input (e.g. passing an invalid file descriptor).  The default handling\n    // for these assertions is to pop up a dialog and wait for user input.\n    // Instead ask the CRT to dump such assertions to stderr non-interactively.\n    if (!IsDebuggerPresent()) {\n      (void)_CrtSetReportMode(_CRT_ASSERT,\n                              _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);\n      (void)_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);\n    }\n#endif\n  }\n#endif  // GTEST_OS_WINDOWS\n\n  return internal::HandleExceptionsInMethodIfSupported(\n             impl(), &internal::UnitTestImpl::RunAllTests,\n             \"auxiliary test code (environments or event listeners)\")\n             ? 0\n             : 1;\n}\n\n// Returns the working directory when the first TEST() or TEST_F() was\n// executed.\nconst char* UnitTest::original_working_dir() const {\n  return impl_->original_working_dir_.c_str();\n}\n\n// Returns the TestSuite object for the test that's currently running,\n// or NULL if no test is running.\nconst TestSuite* UnitTest::current_test_suite() const\n    GTEST_LOCK_EXCLUDED_(mutex_) {\n  internal::MutexLock lock(&mutex_);\n  return impl_->current_test_suite();\n}\n\n// Legacy API is still available but deprecated\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\nconst TestCase* UnitTest::current_test_case() const\n    GTEST_LOCK_EXCLUDED_(mutex_) {\n  internal::MutexLock lock(&mutex_);\n  return impl_->current_test_suite();\n}\n#endif\n\n// Returns the TestInfo object for the test that's currently running,\n// or NULL if no test is running.\nconst TestInfo* UnitTest::current_test_info() const\n    GTEST_LOCK_EXCLUDED_(mutex_) {\n  internal::MutexLock lock(&mutex_);\n  return impl_->current_test_info();\n}\n\n// Returns the random seed used at the start of the current test run.\nint UnitTest::random_seed() const { return impl_->random_seed(); }\n\n// Returns ParameterizedTestSuiteRegistry object used to keep track of\n// value-parameterized tests and instantiate and register them.\ninternal::ParameterizedTestSuiteRegistry&\nUnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) {\n  return impl_->parameterized_test_registry();\n}\n\n// Creates an empty UnitTest.\nUnitTest::UnitTest() { impl_ = new internal::UnitTestImpl(this); }\n\n// Destructor of UnitTest.\nUnitTest::~UnitTest() { delete impl_; }\n\n// Pushes a trace defined by SCOPED_TRACE() on to the per-thread\n// Google Test trace stack.\nvoid UnitTest::PushGTestTrace(const internal::TraceInfo& trace)\n    GTEST_LOCK_EXCLUDED_(mutex_) {\n  internal::MutexLock lock(&mutex_);\n  impl_->gtest_trace_stack().push_back(trace);\n}\n\n// Pops a trace from the per-thread Google Test trace stack.\nvoid UnitTest::PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_) {\n  internal::MutexLock lock(&mutex_);\n  impl_->gtest_trace_stack().pop_back();\n}\n\nnamespace internal {\n\nUnitTestImpl::UnitTestImpl(UnitTest* parent)\n    : parent_(parent),\n      GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)\n          default_global_test_part_result_reporter_(this),\n      default_per_thread_test_part_result_reporter_(this),\n      GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_repoter_(\n          &default_global_test_part_result_reporter_),\n      per_thread_test_part_result_reporter_(\n          &default_per_thread_test_part_result_reporter_),\n      parameterized_test_registry_(),\n      parameterized_tests_registered_(false),\n      last_death_test_suite_(-1),\n      current_test_suite_(nullptr),\n      current_test_info_(nullptr),\n      ad_hoc_test_result_(),\n      os_stack_trace_getter_(nullptr),\n      post_flag_parse_init_performed_(false),\n      random_seed_(0),  // Will be overridden by the flag before first use.\n      random_(0),       // Will be reseeded before first use.\n      start_timestamp_(0),\n      elapsed_time_(0),\n#if GTEST_HAS_DEATH_TEST\n      death_test_factory_(new DefaultDeathTestFactory),\n#endif\n      // Will be overridden by the flag before first use.\n      catch_exceptions_(false) {\n  listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);\n}\n\nUnitTestImpl::~UnitTestImpl() {\n  // Deletes every TestSuite.\n  ForEach(test_suites_, internal::Delete<TestSuite>);\n\n  // Deletes every Environment.\n  ForEach(environments_, internal::Delete<Environment>);\n\n  delete os_stack_trace_getter_;\n}\n\n// Adds a TestProperty to the current TestResult object when invoked in a\n// context of a test, to current test suite's ad_hoc_test_result when invoke\n// from SetUpTestSuite/TearDownTestSuite, or to the global property set\n// otherwise.  If the result already contains a property with the same key,\n// the value will be updated.\nvoid UnitTestImpl::RecordProperty(const TestProperty& test_property) {\n  std::string xml_element;\n  TestResult* test_result;  // TestResult appropriate for property recording.\n\n  if (current_test_info_ != nullptr) {\n    xml_element = \"testcase\";\n    test_result = &(current_test_info_->result_);\n  } else if (current_test_suite_ != nullptr) {\n    xml_element = \"testsuite\";\n    test_result = &(current_test_suite_->ad_hoc_test_result_);\n  } else {\n    xml_element = \"testsuites\";\n    test_result = &ad_hoc_test_result_;\n  }\n  test_result->RecordProperty(xml_element, test_property);\n}\n\n#if GTEST_HAS_DEATH_TEST\n// Disables event forwarding if the control is currently in a death test\n// subprocess. Must not be called before InitGoogleTest.\nvoid UnitTestImpl::SuppressTestEventsIfInSubprocess() {\n  if (internal_run_death_test_flag_.get() != nullptr)\n    listeners()->SuppressEventForwarding();\n}\n#endif  // GTEST_HAS_DEATH_TEST\n\n// Initializes event listeners performing XML output as specified by\n// UnitTestOptions. Must not be called before InitGoogleTest.\nvoid UnitTestImpl::ConfigureXmlOutput() {\n  const std::string& output_format = UnitTestOptions::GetOutputFormat();\n  if (output_format == \"xml\") {\n    listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(\n        UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));\n  } else if (output_format == \"json\") {\n    listeners()->SetDefaultXmlGenerator(new JsonUnitTestResultPrinter(\n        UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));\n  } else if (output_format != \"\") {\n    GTEST_LOG_(WARNING) << \"WARNING: unrecognized output format \\\"\"\n                        << output_format << \"\\\" ignored.\";\n  }\n}\n\n#if GTEST_CAN_STREAM_RESULTS_\n// Initializes event listeners for streaming test results in string form.\n// Must not be called before InitGoogleTest.\nvoid UnitTestImpl::ConfigureStreamingOutput() {\n  const std::string& target = GTEST_FLAG_GET(stream_result_to);\n  if (!target.empty()) {\n    const size_t pos = target.find(':');\n    if (pos != std::string::npos) {\n      listeners()->Append(\n          new StreamingListener(target.substr(0, pos), target.substr(pos + 1)));\n    } else {\n      GTEST_LOG_(WARNING) << \"unrecognized streaming target \\\"\" << target\n                          << \"\\\" ignored.\";\n    }\n  }\n}\n#endif  // GTEST_CAN_STREAM_RESULTS_\n\n// Performs initialization dependent upon flag values obtained in\n// ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to\n// ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest\n// this function is also called from RunAllTests.  Since this function can be\n// called more than once, it has to be idempotent.\nvoid UnitTestImpl::PostFlagParsingInit() {\n  // Ensures that this function does not execute more than once.\n  if (!post_flag_parse_init_performed_) {\n    post_flag_parse_init_performed_ = true;\n\n#if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)\n    // Register to send notifications about key process state changes.\n    listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());\n#endif  // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)\n\n#if GTEST_HAS_DEATH_TEST\n    InitDeathTestSubprocessControlInfo();\n    SuppressTestEventsIfInSubprocess();\n#endif  // GTEST_HAS_DEATH_TEST\n\n    // Registers parameterized tests. This makes parameterized tests\n    // available to the UnitTest reflection API without running\n    // RUN_ALL_TESTS.\n    RegisterParameterizedTests();\n\n    // Configures listeners for XML output. This makes it possible for users\n    // to shut down the default XML output before invoking RUN_ALL_TESTS.\n    ConfigureXmlOutput();\n\n    if (GTEST_FLAG_GET(brief)) {\n      listeners()->SetDefaultResultPrinter(new BriefUnitTestResultPrinter);\n    }\n\n#if GTEST_CAN_STREAM_RESULTS_\n    // Configures listeners for streaming test results to the specified server.\n    ConfigureStreamingOutput();\n#endif  // GTEST_CAN_STREAM_RESULTS_\n\n#if GTEST_HAS_ABSL\n    if (GTEST_FLAG_GET(install_failure_signal_handler)) {\n      absl::FailureSignalHandlerOptions options;\n      absl::InstallFailureSignalHandler(options);\n    }\n#endif  // GTEST_HAS_ABSL\n  }\n}\n\n// A predicate that checks the name of a TestSuite against a known\n// value.\n//\n// This is used for implementation of the UnitTest class only.  We put\n// it in the anonymous namespace to prevent polluting the outer\n// namespace.\n//\n// TestSuiteNameIs is copyable.\nclass TestSuiteNameIs {\n public:\n  // Constructor.\n  explicit TestSuiteNameIs(const std::string& name) : name_(name) {}\n\n  // Returns true if and only if the name of test_suite matches name_.\n  bool operator()(const TestSuite* test_suite) const {\n    return test_suite != nullptr &&\n           strcmp(test_suite->name(), name_.c_str()) == 0;\n  }\n\n private:\n  std::string name_;\n};\n\n// Finds and returns a TestSuite with the given name.  If one doesn't\n// exist, creates one and returns it.  It's the CALLER'S\n// RESPONSIBILITY to ensure that this function is only called WHEN THE\n// TESTS ARE NOT SHUFFLED.\n//\n// Arguments:\n//\n//   test_suite_name: name of the test suite\n//   type_param:      the name of the test suite's type parameter, or NULL if\n//                    this is not a typed or a type-parameterized test suite.\n//   set_up_tc:       pointer to the function that sets up the test suite\n//   tear_down_tc:    pointer to the function that tears down the test suite\nTestSuite* UnitTestImpl::GetTestSuite(\n    const char* test_suite_name, const char* type_param,\n    internal::SetUpTestSuiteFunc set_up_tc,\n    internal::TearDownTestSuiteFunc tear_down_tc) {\n  // Can we find a TestSuite with the given name?\n  const auto test_suite =\n      std::find_if(test_suites_.rbegin(), test_suites_.rend(),\n                   TestSuiteNameIs(test_suite_name));\n\n  if (test_suite != test_suites_.rend()) return *test_suite;\n\n  // No.  Let's create one.\n  auto* const new_test_suite =\n      new TestSuite(test_suite_name, type_param, set_up_tc, tear_down_tc);\n\n  const UnitTestFilter death_test_suite_filter(kDeathTestSuiteFilter);\n  // Is this a death test suite?\n  if (death_test_suite_filter.MatchesName(test_suite_name)) {\n    // Yes.  Inserts the test suite after the last death test suite\n    // defined so far.  This only works when the test suites haven't\n    // been shuffled.  Otherwise we may end up running a death test\n    // after a non-death test.\n    ++last_death_test_suite_;\n    test_suites_.insert(test_suites_.begin() + last_death_test_suite_,\n                        new_test_suite);\n  } else {\n    // No.  Appends to the end of the list.\n    test_suites_.push_back(new_test_suite);\n  }\n\n  test_suite_indices_.push_back(static_cast<int>(test_suite_indices_.size()));\n  return new_test_suite;\n}\n\n// Helpers for setting up / tearing down the given environment.  They\n// are for use in the ForEach() function.\nstatic void SetUpEnvironment(Environment* env) { env->SetUp(); }\nstatic void TearDownEnvironment(Environment* env) { env->TearDown(); }\n\n// Runs all tests in this UnitTest object, prints the result, and\n// returns true if all tests are successful.  If any exception is\n// thrown during a test, the test is considered to be failed, but the\n// rest of the tests will still be run.\n//\n// When parameterized tests are enabled, it expands and registers\n// parameterized tests first in RegisterParameterizedTests().\n// All other functions called from RunAllTests() may safely assume that\n// parameterized tests are ready to be counted and run.\nbool UnitTestImpl::RunAllTests() {\n  // True if and only if Google Test is initialized before RUN_ALL_TESTS() is\n  // called.\n  const bool gtest_is_initialized_before_run_all_tests = GTestIsInitialized();\n\n  // Do not run any test if the --help flag was specified.\n  if (g_help_flag) return true;\n\n  // Repeats the call to the post-flag parsing initialization in case the\n  // user didn't call InitGoogleTest.\n  PostFlagParsingInit();\n\n  // Even if sharding is not on, test runners may want to use the\n  // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding\n  // protocol.\n  internal::WriteToShardStatusFileIfNeeded();\n\n  // True if and only if we are in a subprocess for running a thread-safe-style\n  // death test.\n  bool in_subprocess_for_death_test = false;\n\n#if GTEST_HAS_DEATH_TEST\n  in_subprocess_for_death_test =\n      (internal_run_death_test_flag_.get() != nullptr);\n#if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)\n  if (in_subprocess_for_death_test) {\n    GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();\n  }\n#endif  // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)\n#endif  // GTEST_HAS_DEATH_TEST\n\n  const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,\n                                        in_subprocess_for_death_test);\n\n  // Compares the full test names with the filter to decide which\n  // tests to run.\n  const bool has_tests_to_run =\n      FilterTests(should_shard ? HONOR_SHARDING_PROTOCOL\n                               : IGNORE_SHARDING_PROTOCOL) > 0;\n\n  // Lists the tests and exits if the --gtest_list_tests flag was specified.\n  if (GTEST_FLAG_GET(list_tests)) {\n    // This must be called *after* FilterTests() has been called.\n    ListTestsMatchingFilter();\n    return true;\n  }\n\n  random_seed_ = GetRandomSeedFromFlag(GTEST_FLAG_GET(random_seed));\n\n  // True if and only if at least one test has failed.\n  bool failed = false;\n\n  TestEventListener* repeater = listeners()->repeater();\n\n  start_timestamp_ = GetTimeInMillis();\n  repeater->OnTestProgramStart(*parent_);\n\n  // How many times to repeat the tests?  We don't want to repeat them\n  // when we are inside the subprocess of a death test.\n  const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG_GET(repeat);\n\n  // Repeats forever if the repeat count is negative.\n  const bool gtest_repeat_forever = repeat < 0;\n\n  // Should test environments be set up and torn down for each repeat, or only\n  // set up on the first and torn down on the last iteration? If there is no\n  // \"last\" iteration because the tests will repeat forever, always recreate the\n  // environments to avoid leaks in case one of the environments is using\n  // resources that are external to this process. Without this check there would\n  // be no way to clean up those external resources automatically.\n  const bool recreate_environments_when_repeating =\n      GTEST_FLAG_GET(recreate_environments_when_repeating) ||\n      gtest_repeat_forever;\n\n  for (int i = 0; gtest_repeat_forever || i != repeat; i++) {\n    // We want to preserve failures generated by ad-hoc test\n    // assertions executed before RUN_ALL_TESTS().\n    ClearNonAdHocTestResult();\n\n    Timer timer;\n\n    // Shuffles test suites and tests if requested.\n    if (has_tests_to_run && GTEST_FLAG_GET(shuffle)) {\n      random()->Reseed(static_cast<uint32_t>(random_seed_));\n      // This should be done before calling OnTestIterationStart(),\n      // such that a test event listener can see the actual test order\n      // in the event.\n      ShuffleTests();\n    }\n\n    // Tells the unit test event listeners that the tests are about to start.\n    repeater->OnTestIterationStart(*parent_, i);\n\n    // Runs each test suite if there is at least one test to run.\n    if (has_tests_to_run) {\n      // Sets up all environments beforehand. If test environments aren't\n      // recreated for each iteration, only do so on the first iteration.\n      if (i == 0 || recreate_environments_when_repeating) {\n        repeater->OnEnvironmentsSetUpStart(*parent_);\n        ForEach(environments_, SetUpEnvironment);\n        repeater->OnEnvironmentsSetUpEnd(*parent_);\n      }\n\n      // Runs the tests only if there was no fatal failure or skip triggered\n      // during global set-up.\n      if (Test::IsSkipped()) {\n        // Emit diagnostics when global set-up calls skip, as it will not be\n        // emitted by default.\n        TestResult& test_result =\n            *internal::GetUnitTestImpl()->current_test_result();\n        for (int j = 0; j < test_result.total_part_count(); ++j) {\n          const TestPartResult& test_part_result =\n              test_result.GetTestPartResult(j);\n          if (test_part_result.type() == TestPartResult::kSkip) {\n            const std::string& result = test_part_result.message();\n            printf(\"%s\\n\", result.c_str());\n          }\n        }\n        fflush(stdout);\n      } else if (!Test::HasFatalFailure()) {\n        for (int test_index = 0; test_index < total_test_suite_count();\n             test_index++) {\n          GetMutableSuiteCase(test_index)->Run();\n          if (GTEST_FLAG_GET(fail_fast) &&\n              GetMutableSuiteCase(test_index)->Failed()) {\n            for (int j = test_index + 1; j < total_test_suite_count(); j++) {\n              GetMutableSuiteCase(j)->Skip();\n            }\n            break;\n          }\n        }\n      } else if (Test::HasFatalFailure()) {\n        // If there was a fatal failure during the global setup then we know we\n        // aren't going to run any tests. Explicitly mark all of the tests as\n        // skipped to make this obvious in the output.\n        for (int test_index = 0; test_index < total_test_suite_count();\n             test_index++) {\n          GetMutableSuiteCase(test_index)->Skip();\n        }\n      }\n\n      // Tears down all environments in reverse order afterwards. If test\n      // environments aren't recreated for each iteration, only do so on the\n      // last iteration.\n      if (i == repeat - 1 || recreate_environments_when_repeating) {\n        repeater->OnEnvironmentsTearDownStart(*parent_);\n        std::for_each(environments_.rbegin(), environments_.rend(),\n                      TearDownEnvironment);\n        repeater->OnEnvironmentsTearDownEnd(*parent_);\n      }\n    }\n\n    elapsed_time_ = timer.Elapsed();\n\n    // Tells the unit test event listener that the tests have just finished.\n    repeater->OnTestIterationEnd(*parent_, i);\n\n    // Gets the result and clears it.\n    if (!Passed()) {\n      failed = true;\n    }\n\n    // Restores the original test order after the iteration.  This\n    // allows the user to quickly repro a failure that happens in the\n    // N-th iteration without repeating the first (N - 1) iterations.\n    // This is not enclosed in \"if (GTEST_FLAG(shuffle)) { ... }\", in\n    // case the user somehow changes the value of the flag somewhere\n    // (it's always safe to unshuffle the tests).\n    UnshuffleTests();\n\n    if (GTEST_FLAG_GET(shuffle)) {\n      // Picks a new random seed for each iteration.\n      random_seed_ = GetNextRandomSeed(random_seed_);\n    }\n  }\n\n  repeater->OnTestProgramEnd(*parent_);\n\n  if (!gtest_is_initialized_before_run_all_tests) {\n    ColoredPrintf(\n        GTestColor::kRed,\n        \"\\nIMPORTANT NOTICE - DO NOT IGNORE:\\n\"\n        \"This test program did NOT call \" GTEST_INIT_GOOGLE_TEST_NAME_\n        \"() before calling RUN_ALL_TESTS(). This is INVALID. Soon \" GTEST_NAME_\n        \" will start to enforce the valid usage. \"\n        \"Please fix it ASAP, or IT WILL START TO FAIL.\\n\");  // NOLINT\n#if GTEST_FOR_GOOGLE_\n    ColoredPrintf(GTestColor::kRed,\n                  \"For more details, see http://wiki/Main/ValidGUnitMain.\\n\");\n#endif  // GTEST_FOR_GOOGLE_\n  }\n\n  return !failed;\n}\n\n// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file\n// if the variable is present. If a file already exists at this location, this\n// function will write over it. If the variable is present, but the file cannot\n// be created, prints an error and exits.\nvoid WriteToShardStatusFileIfNeeded() {\n  const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);\n  if (test_shard_file != nullptr) {\n    FILE* const file = posix::FOpen(test_shard_file, \"w\");\n    if (file == nullptr) {\n      ColoredPrintf(GTestColor::kRed,\n                    \"Could not write to the test shard status file \\\"%s\\\" \"\n                    \"specified by the %s environment variable.\\n\",\n                    test_shard_file, kTestShardStatusFile);\n      fflush(stdout);\n      exit(EXIT_FAILURE);\n    }\n    fclose(file);\n  }\n}\n\n// Checks whether sharding is enabled by examining the relevant\n// environment variable values. If the variables are present,\n// but inconsistent (i.e., shard_index >= total_shards), prints\n// an error and exits. If in_subprocess_for_death_test, sharding is\n// disabled because it must only be applied to the original test\n// process. Otherwise, we could filter out death tests we intended to execute.\nbool ShouldShard(const char* total_shards_env, const char* shard_index_env,\n                 bool in_subprocess_for_death_test) {\n  if (in_subprocess_for_death_test) {\n    return false;\n  }\n\n  const int32_t total_shards = Int32FromEnvOrDie(total_shards_env, -1);\n  const int32_t shard_index = Int32FromEnvOrDie(shard_index_env, -1);\n\n  if (total_shards == -1 && shard_index == -1) {\n    return false;\n  } else if (total_shards == -1 && shard_index != -1) {\n    const Message msg = Message() << \"Invalid environment variables: you have \"\n                                  << kTestShardIndex << \" = \" << shard_index\n                                  << \", but have left \" << kTestTotalShards\n                                  << \" unset.\\n\";\n    ColoredPrintf(GTestColor::kRed, \"%s\", msg.GetString().c_str());\n    fflush(stdout);\n    exit(EXIT_FAILURE);\n  } else if (total_shards != -1 && shard_index == -1) {\n    const Message msg = Message()\n                        << \"Invalid environment variables: you have \"\n                        << kTestTotalShards << \" = \" << total_shards\n                        << \", but have left \" << kTestShardIndex << \" unset.\\n\";\n    ColoredPrintf(GTestColor::kRed, \"%s\", msg.GetString().c_str());\n    fflush(stdout);\n    exit(EXIT_FAILURE);\n  } else if (shard_index < 0 || shard_index >= total_shards) {\n    const Message msg =\n        Message() << \"Invalid environment variables: we require 0 <= \"\n                  << kTestShardIndex << \" < \" << kTestTotalShards\n                  << \", but you have \" << kTestShardIndex << \"=\" << shard_index\n                  << \", \" << kTestTotalShards << \"=\" << total_shards << \".\\n\";\n    ColoredPrintf(GTestColor::kRed, \"%s\", msg.GetString().c_str());\n    fflush(stdout);\n    exit(EXIT_FAILURE);\n  }\n\n  return total_shards > 1;\n}\n\n// Parses the environment variable var as an Int32. If it is unset,\n// returns default_val. If it is not an Int32, prints an error\n// and aborts.\nint32_t Int32FromEnvOrDie(const char* var, int32_t default_val) {\n  const char* str_val = posix::GetEnv(var);\n  if (str_val == nullptr) {\n    return default_val;\n  }\n\n  int32_t result;\n  if (!ParseInt32(Message() << \"The value of environment variable \" << var,\n                  str_val, &result)) {\n    exit(EXIT_FAILURE);\n  }\n  return result;\n}\n\n// Given the total number of shards, the shard index, and the test id,\n// returns true if and only if the test should be run on this shard. The test id\n// is some arbitrary but unique non-negative integer assigned to each test\n// method. Assumes that 0 <= shard_index < total_shards.\nbool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {\n  return (test_id % total_shards) == shard_index;\n}\n\n// Compares the name of each test with the user-specified filter to\n// decide whether the test should be run, then records the result in\n// each TestSuite and TestInfo object.\n// If shard_tests == true, further filters tests based on sharding\n// variables in the environment - see\n// https://github.com/google/googletest/blob/master/googletest/docs/advanced.md\n// . Returns the number of tests that should run.\nint UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {\n  const int32_t total_shards = shard_tests == HONOR_SHARDING_PROTOCOL\n                                   ? Int32FromEnvOrDie(kTestTotalShards, -1)\n                                   : -1;\n  const int32_t shard_index = shard_tests == HONOR_SHARDING_PROTOCOL\n                                  ? Int32FromEnvOrDie(kTestShardIndex, -1)\n                                  : -1;\n\n  const PositiveAndNegativeUnitTestFilter gtest_flag_filter(\n      GTEST_FLAG_GET(filter));\n  const UnitTestFilter disable_test_filter(kDisableTestFilter);\n  // num_runnable_tests are the number of tests that will\n  // run across all shards (i.e., match filter and are not disabled).\n  // num_selected_tests are the number of tests to be run on\n  // this shard.\n  int num_runnable_tests = 0;\n  int num_selected_tests = 0;\n  for (auto* test_suite : test_suites_) {\n    const std::string& test_suite_name = test_suite->name();\n    test_suite->set_should_run(false);\n\n    for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {\n      TestInfo* const test_info = test_suite->test_info_list()[j];\n      const std::string test_name(test_info->name());\n      // A test is disabled if test suite name or test name matches\n      // kDisableTestFilter.\n      const bool is_disabled =\n          disable_test_filter.MatchesName(test_suite_name) ||\n          disable_test_filter.MatchesName(test_name);\n      test_info->is_disabled_ = is_disabled;\n\n      const bool matches_filter =\n          gtest_flag_filter.MatchesTest(test_suite_name, test_name);\n      test_info->matches_filter_ = matches_filter;\n\n      const bool is_runnable =\n          (GTEST_FLAG_GET(also_run_disabled_tests) || !is_disabled) &&\n          matches_filter;\n\n      const bool is_in_another_shard =\n          shard_tests != IGNORE_SHARDING_PROTOCOL &&\n          !ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests);\n      test_info->is_in_another_shard_ = is_in_another_shard;\n      const bool is_selected = is_runnable && !is_in_another_shard;\n\n      num_runnable_tests += is_runnable;\n      num_selected_tests += is_selected;\n\n      test_info->should_run_ = is_selected;\n      test_suite->set_should_run(test_suite->should_run() || is_selected);\n    }\n  }\n  return num_selected_tests;\n}\n\n// Prints the given C-string on a single line by replacing all '\\n'\n// characters with string \"\\\\n\".  If the output takes more than\n// max_length characters, only prints the first max_length characters\n// and \"...\".\nstatic void PrintOnOneLine(const char* str, int max_length) {\n  if (str != nullptr) {\n    for (int i = 0; *str != '\\0'; ++str) {\n      if (i >= max_length) {\n        printf(\"...\");\n        break;\n      }\n      if (*str == '\\n') {\n        printf(\"\\\\n\");\n        i += 2;\n      } else {\n        printf(\"%c\", *str);\n        ++i;\n      }\n    }\n  }\n}\n\n// Prints the names of the tests matching the user-specified filter flag.\nvoid UnitTestImpl::ListTestsMatchingFilter() {\n  // Print at most this many characters for each type/value parameter.\n  const int kMaxParamLength = 250;\n\n  for (auto* test_suite : test_suites_) {\n    bool printed_test_suite_name = false;\n\n    for (size_t j = 0; j < test_suite->test_info_list().size(); j++) {\n      const TestInfo* const test_info = test_suite->test_info_list()[j];\n      if (test_info->matches_filter_) {\n        if (!printed_test_suite_name) {\n          printed_test_suite_name = true;\n          printf(\"%s.\", test_suite->name());\n          if (test_suite->type_param() != nullptr) {\n            printf(\"  # %s = \", kTypeParamLabel);\n            // We print the type parameter on a single line to make\n            // the output easy to parse by a program.\n            PrintOnOneLine(test_suite->type_param(), kMaxParamLength);\n          }\n          printf(\"\\n\");\n        }\n        printf(\"  %s\", test_info->name());\n        if (test_info->value_param() != nullptr) {\n          printf(\"  # %s = \", kValueParamLabel);\n          // We print the value parameter on a single line to make the\n          // output easy to parse by a program.\n          PrintOnOneLine(test_info->value_param(), kMaxParamLength);\n        }\n        printf(\"\\n\");\n      }\n    }\n  }\n  fflush(stdout);\n  const std::string& output_format = UnitTestOptions::GetOutputFormat();\n  if (output_format == \"xml\" || output_format == \"json\") {\n    FILE* fileout = OpenFileForWriting(\n        UnitTestOptions::GetAbsolutePathToOutputFile().c_str());\n    std::stringstream stream;\n    if (output_format == \"xml\") {\n      XmlUnitTestResultPrinter(\n          UnitTestOptions::GetAbsolutePathToOutputFile().c_str())\n          .PrintXmlTestsList(&stream, test_suites_);\n    } else if (output_format == \"json\") {\n      JsonUnitTestResultPrinter(\n          UnitTestOptions::GetAbsolutePathToOutputFile().c_str())\n          .PrintJsonTestList(&stream, test_suites_);\n    }\n    fprintf(fileout, \"%s\", StringStreamToString(&stream).c_str());\n    fclose(fileout);\n  }\n}\n\n// Sets the OS stack trace getter.\n//\n// Does nothing if the input and the current OS stack trace getter are\n// the same; otherwise, deletes the old getter and makes the input the\n// current getter.\nvoid UnitTestImpl::set_os_stack_trace_getter(\n    OsStackTraceGetterInterface* getter) {\n  if (os_stack_trace_getter_ != getter) {\n    delete os_stack_trace_getter_;\n    os_stack_trace_getter_ = getter;\n  }\n}\n\n// Returns the current OS stack trace getter if it is not NULL;\n// otherwise, creates an OsStackTraceGetter, makes it the current\n// getter, and returns it.\nOsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {\n  if (os_stack_trace_getter_ == nullptr) {\n#ifdef GTEST_OS_STACK_TRACE_GETTER_\n    os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;\n#else\n    os_stack_trace_getter_ = new OsStackTraceGetter;\n#endif  // GTEST_OS_STACK_TRACE_GETTER_\n  }\n\n  return os_stack_trace_getter_;\n}\n\n// Returns the most specific TestResult currently running.\nTestResult* UnitTestImpl::current_test_result() {\n  if (current_test_info_ != nullptr) {\n    return &current_test_info_->result_;\n  }\n  if (current_test_suite_ != nullptr) {\n    return &current_test_suite_->ad_hoc_test_result_;\n  }\n  return &ad_hoc_test_result_;\n}\n\n// Shuffles all test suites, and the tests within each test suite,\n// making sure that death tests are still run first.\nvoid UnitTestImpl::ShuffleTests() {\n  // Shuffles the death test suites.\n  ShuffleRange(random(), 0, last_death_test_suite_ + 1, &test_suite_indices_);\n\n  // Shuffles the non-death test suites.\n  ShuffleRange(random(), last_death_test_suite_ + 1,\n               static_cast<int>(test_suites_.size()), &test_suite_indices_);\n\n  // Shuffles the tests inside each test suite.\n  for (auto& test_suite : test_suites_) {\n    test_suite->ShuffleTests(random());\n  }\n}\n\n// Restores the test suites and tests to their order before the first shuffle.\nvoid UnitTestImpl::UnshuffleTests() {\n  for (size_t i = 0; i < test_suites_.size(); i++) {\n    // Unshuffles the tests in each test suite.\n    test_suites_[i]->UnshuffleTests();\n    // Resets the index of each test suite.\n    test_suite_indices_[i] = static_cast<int>(i);\n  }\n}\n\n// Returns the current OS stack trace as an std::string.\n//\n// The maximum number of stack frames to be included is specified by\n// the gtest_stack_trace_depth flag.  The skip_count parameter\n// specifies the number of top frames to be skipped, which doesn't\n// count against the number of frames to be included.\n//\n// For example, if Foo() calls Bar(), which in turn calls\n// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in\n// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.\nGTEST_NO_INLINE_ GTEST_NO_TAIL_CALL_ std::string\nGetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, int skip_count) {\n  // We pass skip_count + 1 to skip this wrapper function in addition\n  // to what the user really wants to skip.\n  return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);\n}\n\n// Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to\n// suppress unreachable code warnings.\nnamespace {\nclass ClassUniqueToAlwaysTrue {};\n}  // namespace\n\nbool IsTrue(bool condition) { return condition; }\n\nbool AlwaysTrue() {\n#if GTEST_HAS_EXCEPTIONS\n  // This condition is always false so AlwaysTrue() never actually throws,\n  // but it makes the compiler think that it may throw.\n  if (IsTrue(false)) throw ClassUniqueToAlwaysTrue();\n#endif  // GTEST_HAS_EXCEPTIONS\n  return true;\n}\n\n// If *pstr starts with the given prefix, modifies *pstr to be right\n// past the prefix and returns true; otherwise leaves *pstr unchanged\n// and returns false.  None of pstr, *pstr, and prefix can be NULL.\nbool SkipPrefix(const char* prefix, const char** pstr) {\n  const size_t prefix_len = strlen(prefix);\n  if (strncmp(*pstr, prefix, prefix_len) == 0) {\n    *pstr += prefix_len;\n    return true;\n  }\n  return false;\n}\n\n// Parses a string as a command line flag.  The string should have\n// the format \"--flag=value\".  When def_optional is true, the \"=value\"\n// part can be omitted.\n//\n// Returns the value of the flag, or NULL if the parsing failed.\nstatic const char* ParseFlagValue(const char* str, const char* flag_name,\n                                  bool def_optional) {\n  // str and flag must not be NULL.\n  if (str == nullptr || flag_name == nullptr) return nullptr;\n\n  // The flag must start with \"--\" followed by GTEST_FLAG_PREFIX_.\n  const std::string flag_str =\n      std::string(\"--\") + GTEST_FLAG_PREFIX_ + flag_name;\n  const size_t flag_len = flag_str.length();\n  if (strncmp(str, flag_str.c_str(), flag_len) != 0) return nullptr;\n\n  // Skips the flag name.\n  const char* flag_end = str + flag_len;\n\n  // When def_optional is true, it's OK to not have a \"=value\" part.\n  if (def_optional && (flag_end[0] == '\\0')) {\n    return flag_end;\n  }\n\n  // If def_optional is true and there are more characters after the\n  // flag name, or if def_optional is false, there must be a '=' after\n  // the flag name.\n  if (flag_end[0] != '=') return nullptr;\n\n  // Returns the string after \"=\".\n  return flag_end + 1;\n}\n\n// Parses a string for a bool flag, in the form of either\n// \"--flag=value\" or \"--flag\".\n//\n// In the former case, the value is taken as true as long as it does\n// not start with '0', 'f', or 'F'.\n//\n// In the latter case, the value is taken as true.\n//\n// On success, stores the value of the flag in *value, and returns\n// true.  On failure, returns false without changing *value.\nstatic bool ParseFlag(const char* str, const char* flag_name, bool* value) {\n  // Gets the value of the flag as a string.\n  const char* const value_str = ParseFlagValue(str, flag_name, true);\n\n  // Aborts if the parsing failed.\n  if (value_str == nullptr) return false;\n\n  // Converts the string value to a bool.\n  *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');\n  return true;\n}\n\n// Parses a string for an int32_t flag, in the form of \"--flag=value\".\n//\n// On success, stores the value of the flag in *value, and returns\n// true.  On failure, returns false without changing *value.\nbool ParseFlag(const char* str, const char* flag_name, int32_t* value) {\n  // Gets the value of the flag as a string.\n  const char* const value_str = ParseFlagValue(str, flag_name, false);\n\n  // Aborts if the parsing failed.\n  if (value_str == nullptr) return false;\n\n  // Sets *value to the value of the flag.\n  return ParseInt32(Message() << \"The value of flag --\" << flag_name, value_str,\n                    value);\n}\n\n// Parses a string for a string flag, in the form of \"--flag=value\".\n//\n// On success, stores the value of the flag in *value, and returns\n// true.  On failure, returns false without changing *value.\ntemplate <typename String>\nstatic bool ParseFlag(const char* str, const char* flag_name, String* value) {\n  // Gets the value of the flag as a string.\n  const char* const value_str = ParseFlagValue(str, flag_name, false);\n\n  // Aborts if the parsing failed.\n  if (value_str == nullptr) return false;\n\n  // Sets *value to the value of the flag.\n  *value = value_str;\n  return true;\n}\n\n// Determines whether a string has a prefix that Google Test uses for its\n// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.\n// If Google Test detects that a command line flag has its prefix but is not\n// recognized, it will print its help message. Flags starting with\n// GTEST_INTERNAL_PREFIX_ followed by \"internal_\" are considered Google Test\n// internal flags and do not trigger the help message.\nstatic bool HasGoogleTestFlagPrefix(const char* str) {\n  return (SkipPrefix(\"--\", &str) || SkipPrefix(\"-\", &str) ||\n          SkipPrefix(\"/\", &str)) &&\n         !SkipPrefix(GTEST_FLAG_PREFIX_ \"internal_\", &str) &&\n         (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||\n          SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));\n}\n\n// Prints a string containing code-encoded text.  The following escape\n// sequences can be used in the string to control the text color:\n//\n//   @@    prints a single '@' character.\n//   @R    changes the color to red.\n//   @G    changes the color to green.\n//   @Y    changes the color to yellow.\n//   @D    changes to the default terminal text color.\n//\nstatic void PrintColorEncoded(const char* str) {\n  GTestColor color = GTestColor::kDefault;  // The current color.\n\n  // Conceptually, we split the string into segments divided by escape\n  // sequences.  Then we print one segment at a time.  At the end of\n  // each iteration, the str pointer advances to the beginning of the\n  // next segment.\n  for (;;) {\n    const char* p = strchr(str, '@');\n    if (p == nullptr) {\n      ColoredPrintf(color, \"%s\", str);\n      return;\n    }\n\n    ColoredPrintf(color, \"%s\", std::string(str, p).c_str());\n\n    const char ch = p[1];\n    str = p + 2;\n    if (ch == '@') {\n      ColoredPrintf(color, \"@\");\n    } else if (ch == 'D') {\n      color = GTestColor::kDefault;\n    } else if (ch == 'R') {\n      color = GTestColor::kRed;\n    } else if (ch == 'G') {\n      color = GTestColor::kGreen;\n    } else if (ch == 'Y') {\n      color = GTestColor::kYellow;\n    } else {\n      --str;\n    }\n  }\n}\n\nstatic const char kColorEncodedHelpMessage[] =\n    \"This program contains tests written using \" GTEST_NAME_\n    \". You can use the\\n\"\n    \"following command line flags to control its behavior:\\n\"\n    \"\\n\"\n    \"Test Selection:\\n\"\n    \"  @G--\" GTEST_FLAG_PREFIX_\n    \"list_tests@D\\n\"\n    \"      List the names of all tests instead of running them. The name of\\n\"\n    \"      TEST(Foo, Bar) is \\\"Foo.Bar\\\".\\n\"\n    \"  @G--\" GTEST_FLAG_PREFIX_\n    \"filter=@YPOSITIVE_PATTERNS\"\n    \"[@G-@YNEGATIVE_PATTERNS]@D\\n\"\n    \"      Run only the tests whose name matches one of the positive patterns \"\n    \"but\\n\"\n    \"      none of the negative patterns. '?' matches any single character; \"\n    \"'*'\\n\"\n    \"      matches any substring; ':' separates two patterns.\\n\"\n    \"  @G--\" GTEST_FLAG_PREFIX_\n    \"also_run_disabled_tests@D\\n\"\n    \"      Run all disabled tests too.\\n\"\n    \"\\n\"\n    \"Test Execution:\\n\"\n    \"  @G--\" GTEST_FLAG_PREFIX_\n    \"repeat=@Y[COUNT]@D\\n\"\n    \"      Run the tests repeatedly; use a negative count to repeat forever.\\n\"\n    \"  @G--\" GTEST_FLAG_PREFIX_\n    \"shuffle@D\\n\"\n    \"      Randomize tests' orders on every iteration.\\n\"\n    \"  @G--\" GTEST_FLAG_PREFIX_\n    \"random_seed=@Y[NUMBER]@D\\n\"\n    \"      Random number seed to use for shuffling test orders (between 1 and\\n\"\n    \"      99999, or 0 to use a seed based on the current time).\\n\"\n    \"  @G--\" GTEST_FLAG_PREFIX_\n    \"recreate_environments_when_repeating@D\\n\"\n    \"      Sets up and tears down the global test environment on each repeat\\n\"\n    \"      of the test.\\n\"\n    \"\\n\"\n    \"Test Output:\\n\"\n    \"  @G--\" GTEST_FLAG_PREFIX_\n    \"color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\\n\"\n    \"      Enable/disable colored output. The default is @Gauto@D.\\n\"\n    \"  @G--\" GTEST_FLAG_PREFIX_\n    \"brief=1@D\\n\"\n    \"      Only print test failures.\\n\"\n    \"  @G--\" GTEST_FLAG_PREFIX_\n    \"print_time=0@D\\n\"\n    \"      Don't print the elapsed time of each test.\\n\"\n    \"  @G--\" GTEST_FLAG_PREFIX_\n    \"output=@Y(@Gjson@Y|@Gxml@Y)[@G:@YDIRECTORY_PATH@G\" GTEST_PATH_SEP_\n    \"@Y|@G:@YFILE_PATH]@D\\n\"\n    \"      Generate a JSON or XML report in the given directory or with the \"\n    \"given\\n\"\n    \"      file name. @YFILE_PATH@D defaults to @Gtest_detail.xml@D.\\n\"\n#if GTEST_CAN_STREAM_RESULTS_\n    \"  @G--\" GTEST_FLAG_PREFIX_\n    \"stream_result_to=@YHOST@G:@YPORT@D\\n\"\n    \"      Stream test results to the given server.\\n\"\n#endif  // GTEST_CAN_STREAM_RESULTS_\n    \"\\n\"\n    \"Assertion Behavior:\\n\"\n#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS\n    \"  @G--\" GTEST_FLAG_PREFIX_\n    \"death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\\n\"\n    \"      Set the default death test style.\\n\"\n#endif  // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS\n    \"  @G--\" GTEST_FLAG_PREFIX_\n    \"break_on_failure@D\\n\"\n    \"      Turn assertion failures into debugger break-points.\\n\"\n    \"  @G--\" GTEST_FLAG_PREFIX_\n    \"throw_on_failure@D\\n\"\n    \"      Turn assertion failures into C++ exceptions for use by an external\\n\"\n    \"      test framework.\\n\"\n    \"  @G--\" GTEST_FLAG_PREFIX_\n    \"catch_exceptions=0@D\\n\"\n    \"      Do not report exceptions as test failures. Instead, allow them\\n\"\n    \"      to crash the program or throw a pop-up (on Windows).\\n\"\n    \"\\n\"\n    \"Except for @G--\" GTEST_FLAG_PREFIX_\n    \"list_tests@D, you can alternatively set \"\n    \"the corresponding\\n\"\n    \"environment variable of a flag (all letters in upper-case). For example, \"\n    \"to\\n\"\n    \"disable colored text output, you can either specify \"\n    \"@G--\" GTEST_FLAG_PREFIX_\n    \"color=no@D or set\\n\"\n    \"the @G\" GTEST_FLAG_PREFIX_UPPER_\n    \"COLOR@D environment variable to @Gno@D.\\n\"\n    \"\\n\"\n    \"For more information, please read the \" GTEST_NAME_\n    \" documentation at\\n\"\n    \"@G\" GTEST_PROJECT_URL_ \"@D. If you find a bug in \" GTEST_NAME_\n    \"\\n\"\n    \"(not one in your own code or tests), please report it to\\n\"\n    \"@G<\" GTEST_DEV_EMAIL_ \">@D.\\n\";\n\nstatic bool ParseGoogleTestFlag(const char* const arg) {\n#define GTEST_INTERNAL_PARSE_FLAG(flag_name)  \\\n  do {                                        \\\n    auto value = GTEST_FLAG_GET(flag_name);   \\\n    if (ParseFlag(arg, #flag_name, &value)) { \\\n      GTEST_FLAG_SET(flag_name, value);       \\\n      return true;                            \\\n    }                                         \\\n  } while (false)\n\n  GTEST_INTERNAL_PARSE_FLAG(also_run_disabled_tests);\n  GTEST_INTERNAL_PARSE_FLAG(break_on_failure);\n  GTEST_INTERNAL_PARSE_FLAG(catch_exceptions);\n  GTEST_INTERNAL_PARSE_FLAG(color);\n  GTEST_INTERNAL_PARSE_FLAG(death_test_style);\n  GTEST_INTERNAL_PARSE_FLAG(death_test_use_fork);\n  GTEST_INTERNAL_PARSE_FLAG(fail_fast);\n  GTEST_INTERNAL_PARSE_FLAG(filter);\n  GTEST_INTERNAL_PARSE_FLAG(internal_run_death_test);\n  GTEST_INTERNAL_PARSE_FLAG(list_tests);\n  GTEST_INTERNAL_PARSE_FLAG(output);\n  GTEST_INTERNAL_PARSE_FLAG(brief);\n  GTEST_INTERNAL_PARSE_FLAG(print_time);\n  GTEST_INTERNAL_PARSE_FLAG(print_utf8);\n  GTEST_INTERNAL_PARSE_FLAG(random_seed);\n  GTEST_INTERNAL_PARSE_FLAG(repeat);\n  GTEST_INTERNAL_PARSE_FLAG(recreate_environments_when_repeating);\n  GTEST_INTERNAL_PARSE_FLAG(shuffle);\n  GTEST_INTERNAL_PARSE_FLAG(stack_trace_depth);\n  GTEST_INTERNAL_PARSE_FLAG(stream_result_to);\n  GTEST_INTERNAL_PARSE_FLAG(throw_on_failure);\n  return false;\n}\n\n#if GTEST_USE_OWN_FLAGFILE_FLAG_\nstatic void LoadFlagsFromFile(const std::string& path) {\n  FILE* flagfile = posix::FOpen(path.c_str(), \"r\");\n  if (!flagfile) {\n    GTEST_LOG_(FATAL) << \"Unable to open file \\\"\" << GTEST_FLAG_GET(flagfile)\n                      << \"\\\"\";\n  }\n  std::string contents(ReadEntireFile(flagfile));\n  posix::FClose(flagfile);\n  std::vector<std::string> lines;\n  SplitString(contents, '\\n', &lines);\n  for (size_t i = 0; i < lines.size(); ++i) {\n    if (lines[i].empty()) continue;\n    if (!ParseGoogleTestFlag(lines[i].c_str())) g_help_flag = true;\n  }\n}\n#endif  // GTEST_USE_OWN_FLAGFILE_FLAG_\n\n// Parses the command line for Google Test flags, without initializing\n// other parts of Google Test.  The type parameter CharType can be\n// instantiated to either char or wchar_t.\ntemplate <typename CharType>\nvoid ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {\n  std::string flagfile_value;\n  for (int i = 1; i < *argc; i++) {\n    const std::string arg_string = StreamableToString(argv[i]);\n    const char* const arg = arg_string.c_str();\n\n    using internal::ParseFlag;\n\n    bool remove_flag = false;\n    if (ParseGoogleTestFlag(arg)) {\n      remove_flag = true;\n#if GTEST_USE_OWN_FLAGFILE_FLAG_\n    } else if (ParseFlag(arg, \"flagfile\", &flagfile_value)) {\n      GTEST_FLAG_SET(flagfile, flagfile_value);\n      LoadFlagsFromFile(flagfile_value);\n      remove_flag = true;\n#endif  // GTEST_USE_OWN_FLAGFILE_FLAG_\n    } else if (arg_string == \"--help\" || HasGoogleTestFlagPrefix(arg)) {\n      // Both help flag and unrecognized Google Test flags (excluding\n      // internal ones) trigger help display.\n      g_help_flag = true;\n    }\n\n    if (remove_flag) {\n      // Shift the remainder of the argv list left by one.  Note\n      // that argv has (*argc + 1) elements, the last one always being\n      // NULL.  The following loop moves the trailing NULL element as\n      // well.\n      for (int j = i; j != *argc; j++) {\n        argv[j] = argv[j + 1];\n      }\n\n      // Decrements the argument count.\n      (*argc)--;\n\n      // We also need to decrement the iterator as we just removed\n      // an element.\n      i--;\n    }\n  }\n\n  if (g_help_flag) {\n    // We print the help here instead of in RUN_ALL_TESTS(), as the\n    // latter may not be called at all if the user is using Google\n    // Test with another testing framework.\n    PrintColorEncoded(kColorEncodedHelpMessage);\n  }\n}\n\n// Parses the command line for Google Test flags, without initializing\n// other parts of Google Test.\nvoid ParseGoogleTestFlagsOnly(int* argc, char** argv) {\n#if GTEST_HAS_ABSL\n  if (*argc > 0) {\n    // absl::ParseCommandLine() requires *argc > 0.\n    auto positional_args = absl::flags_internal::ParseCommandLineImpl(\n        *argc, argv, absl::flags_internal::ArgvListAction::kRemoveParsedArgs,\n        absl::flags_internal::UsageFlagsAction::kHandleUsage,\n        absl::flags_internal::OnUndefinedFlag::kReportUndefined);\n    // Any command-line positional arguments not part of any command-line flag\n    // (or arguments to a flag) are copied back out to argv, with the program\n    // invocation name at position 0, and argc is resized. This includes\n    // positional arguments after the flag-terminating delimiter '--'.\n    // See https://abseil.io/docs/cpp/guides/flags.\n    std::copy(positional_args.begin(), positional_args.end(), argv);\n    if (static_cast<int>(positional_args.size()) < *argc) {\n      argv[positional_args.size()] = nullptr;\n      *argc = static_cast<int>(positional_args.size());\n    }\n  }\n#else\n  ParseGoogleTestFlagsOnlyImpl(argc, argv);\n#endif\n\n  // Fix the value of *_NSGetArgc() on macOS, but if and only if\n  // *_NSGetArgv() == argv\n  // Only applicable to char** version of argv\n#if GTEST_OS_MAC\n#ifndef GTEST_OS_IOS\n  if (*_NSGetArgv() == argv) {\n    *_NSGetArgc() = *argc;\n  }\n#endif\n#endif\n}\nvoid ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {\n  ParseGoogleTestFlagsOnlyImpl(argc, argv);\n}\n\n// The internal implementation of InitGoogleTest().\n//\n// The type parameter CharType can be instantiated to either char or\n// wchar_t.\ntemplate <typename CharType>\nvoid InitGoogleTestImpl(int* argc, CharType** argv) {\n  // We don't want to run the initialization code twice.\n  if (GTestIsInitialized()) return;\n\n  if (*argc <= 0) return;\n\n  g_argvs.clear();\n  for (int i = 0; i != *argc; i++) {\n    g_argvs.push_back(StreamableToString(argv[i]));\n  }\n\n#if GTEST_HAS_ABSL\n  absl::InitializeSymbolizer(g_argvs[0].c_str());\n\n  // When using the Abseil Flags library, set the program usage message to the\n  // help message, but remove the color-encoding from the message first.\n  absl::SetProgramUsageMessage(absl::StrReplaceAll(\n      kColorEncodedHelpMessage,\n      {{\"@D\", \"\"}, {\"@R\", \"\"}, {\"@G\", \"\"}, {\"@Y\", \"\"}, {\"@@\", \"@\"}}));\n#endif  // GTEST_HAS_ABSL\n\n  ParseGoogleTestFlagsOnly(argc, argv);\n  GetUnitTestImpl()->PostFlagParsingInit();\n}\n\n}  // namespace internal\n\n// Initializes Google Test.  This must be called before calling\n// RUN_ALL_TESTS().  In particular, it parses a command line for the\n// flags that Google Test recognizes.  Whenever a Google Test flag is\n// seen, it is removed from argv, and *argc is decremented.\n//\n// No value is returned.  Instead, the Google Test flag variables are\n// updated.\n//\n// Calling the function for the second time has no user-visible effect.\nvoid InitGoogleTest(int* argc, char** argv) {\n#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n  GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);\n#else   // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n  internal::InitGoogleTestImpl(argc, argv);\n#endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n}\n\n// This overloaded version can be used in Windows programs compiled in\n// UNICODE mode.\nvoid InitGoogleTest(int* argc, wchar_t** argv) {\n#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n  GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);\n#else   // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n  internal::InitGoogleTestImpl(argc, argv);\n#endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n}\n\n// This overloaded version can be used on Arduino/embedded platforms where\n// there is no argc/argv.\nvoid InitGoogleTest() {\n  // Since Arduino doesn't have a command line, fake out the argc/argv arguments\n  int argc = 1;\n  const auto arg0 = \"dummy\";\n  char* argv0 = const_cast<char*>(arg0);\n  char** argv = &argv0;\n\n#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n  GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(&argc, argv);\n#else   // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n  internal::InitGoogleTestImpl(&argc, argv);\n#endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n}\n\n#if !defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)\n// Return value of first environment variable that is set and contains\n// a non-empty string. If there are none, return the \"fallback\" string.\n// Since we like the temporary directory to have a directory separator suffix,\n// add it if not provided in the environment variable value.\nstatic std::string GetTempDirFromEnv(\n    std::initializer_list<const char*> environment_variables,\n    const char* fallback, char separator) {\n  for (const char* variable_name : environment_variables) {\n    const char* value = internal::posix::GetEnv(variable_name);\n    if (value != nullptr && value[0] != '\\0') {\n      if (value[strlen(value) - 1] != separator) {\n        return std::string(value).append(1, separator);\n      }\n      return value;\n    }\n  }\n  return fallback;\n}\n#endif\n\nstd::string TempDir() {\n#if defined(GTEST_CUSTOM_TEMPDIR_FUNCTION_)\n  return GTEST_CUSTOM_TEMPDIR_FUNCTION_();\n#elif GTEST_OS_WINDOWS || GTEST_OS_WINDOWS_MOBILE\n  return GetTempDirFromEnv({\"TEST_TMPDIR\", \"TEMP\"}, \"\\\\temp\\\\\", '\\\\');\n#elif GTEST_OS_LINUX_ANDROID\n  return GetTempDirFromEnv({\"TEST_TMPDIR\", \"TMPDIR\"}, \"/data/local/tmp/\", '/');\n#else\n  return GetTempDirFromEnv({\"TEST_TMPDIR\", \"TMPDIR\"}, \"/tmp/\", '/');\n#endif\n}\n\n// Class ScopedTrace\n\n// Pushes the given source file location and message onto a per-thread\n// trace stack maintained by Google Test.\nvoid ScopedTrace::PushTrace(const char* file, int line, std::string message) {\n  internal::TraceInfo trace;\n  trace.file = file;\n  trace.line = line;\n  trace.message.swap(message);\n\n  UnitTest::GetInstance()->PushGTestTrace(trace);\n}\n\n// Pops the info pushed by the c'tor.\nScopedTrace::~ScopedTrace() GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {\n  UnitTest::GetInstance()->PopGTestTrace();\n}\n\n}  // namespace testing\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/src/gtest_main.cc",
    "content": "// Copyright 2006, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include <cstdio>\n\n#include \"gtest/gtest.h\"\n\n#if GTEST_OS_ESP8266 || GTEST_OS_ESP32\n#if GTEST_OS_ESP8266\nextern \"C\" {\n#endif\nvoid setup() { testing::InitGoogleTest(); }\n\nvoid loop() { RUN_ALL_TESTS(); }\n\n#if GTEST_OS_ESP8266\n}\n#endif\n\n#else\n\nGTEST_API_ int main(int argc, char **argv) {\n  printf(\"Running main() from %s\\n\", __FILE__);\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n#endif\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/BUILD.bazel",
    "content": "# Copyright 2017 Google Inc.\n# All Rights Reserved.\n#\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n# Bazel BUILD for The Google C++ Testing Framework (Google Test)\n\nload(\"@rules_python//python:defs.bzl\", \"py_library\", \"py_test\")\n\nlicenses([\"notice\"])\n\npackage(default_visibility = [\"//:__subpackages__\"])\n\n#on windows exclude gtest-tuple.h\ncc_test(\n    name = \"gtest_all_test\",\n    size = \"small\",\n    srcs = glob(\n        include = [\n            \"gtest-*.cc\",\n            \"googletest-*.cc\",\n            \"*.h\",\n            \"googletest/include/gtest/**/*.h\",\n        ],\n        exclude = [\n            \"gtest-unittest-api_test.cc\",\n            \"googletest/src/gtest-all.cc\",\n            \"gtest_all_test.cc\",\n            \"gtest-death-test_ex_test.cc\",\n            \"gtest-listener_test.cc\",\n            \"gtest-unittest-api_test.cc\",\n            \"googletest-param-test-test.cc\",\n            \"googletest-param-test2-test.cc\",\n            \"googletest-catch-exceptions-test_.cc\",\n            \"googletest-color-test_.cc\",\n            \"googletest-env-var-test_.cc\",\n            \"googletest-failfast-unittest_.cc\",\n            \"googletest-filter-unittest_.cc\",\n            \"googletest-global-environment-unittest_.cc\",\n            \"googletest-break-on-failure-unittest_.cc\",\n            \"googletest-listener-test.cc\",\n            \"googletest-output-test_.cc\",\n            \"googletest-list-tests-unittest_.cc\",\n            \"googletest-shuffle-test_.cc\",\n            \"googletest-setuptestsuite-test_.cc\",\n            \"googletest-uninitialized-test_.cc\",\n            \"googletest-death-test_ex_test.cc\",\n            \"googletest-param-test-test\",\n            \"googletest-throw-on-failure-test_.cc\",\n            \"googletest-param-test-invalid-name1-test_.cc\",\n            \"googletest-param-test-invalid-name2-test_.cc\",\n        ],\n    ) + select({\n        \"//:windows\": [],\n        \"//conditions:default\": [],\n    }),\n    copts = select({\n        \"//:windows\": [\"-DGTEST_USE_OWN_TR1_TUPLE=0\"],\n        \"//conditions:default\": [\"-DGTEST_USE_OWN_TR1_TUPLE=1\"],\n    }) + select({\n        # Ensure MSVC treats source files as UTF-8 encoded.\n        \"//:msvc_compiler\": [\"-utf-8\"],\n        \"//conditions:default\": [],\n    }),\n    includes = [\n        \"googletest\",\n        \"googletest/include\",\n        \"googletest/include/internal\",\n        \"googletest/test\",\n    ],\n    linkopts = select({\n        \"//:qnx\": [],\n        \"//:windows\": [],\n        \"//conditions:default\": [\"-pthread\"],\n    }),\n    deps = [\"//:gtest_main\"],\n)\n\n# Tests death tests.\ncc_test(\n    name = \"googletest-death-test-test\",\n    size = \"medium\",\n    srcs = [\"googletest-death-test-test.cc\"],\n    deps = [\"//:gtest_main\"],\n)\n\ncc_test(\n    name = \"gtest_test_macro_stack_footprint_test\",\n    size = \"small\",\n    srcs = [\"gtest_test_macro_stack_footprint_test.cc\"],\n    deps = [\"//:gtest\"],\n)\n\n#These googletest tests have their own main()\ncc_test(\n    name = \"googletest-listener-test\",\n    size = \"small\",\n    srcs = [\"googletest-listener-test.cc\"],\n    deps = [\"//:gtest_main\"],\n)\n\ncc_test(\n    name = \"gtest-unittest-api_test\",\n    size = \"small\",\n    srcs = [\n        \"gtest-unittest-api_test.cc\",\n    ],\n    deps = [\n        \"//:gtest\",\n    ],\n)\n\ncc_test(\n    name = \"googletest-param-test-test\",\n    size = \"small\",\n    srcs = [\n        \"googletest-param-test-test.cc\",\n        \"googletest-param-test-test.h\",\n        \"googletest-param-test2-test.cc\",\n    ],\n    deps = [\"//:gtest\"],\n)\n\ncc_test(\n    name = \"gtest_unittest\",\n    size = \"small\",\n    srcs = [\"gtest_unittest.cc\"],\n    shard_count = 2,\n    deps = [\"//:gtest_main\"],\n)\n\n#  Py tests\n\npy_library(\n    name = \"gtest_test_utils\",\n    testonly = 1,\n    srcs = [\"gtest_test_utils.py\"],\n    imports = [\".\"],\n)\n\ncc_binary(\n    name = \"gtest_help_test_\",\n    testonly = 1,\n    srcs = [\"gtest_help_test_.cc\"],\n    deps = [\"//:gtest_main\"],\n)\n\npy_test(\n    name = \"gtest_help_test\",\n    size = \"small\",\n    srcs = [\"gtest_help_test.py\"],\n    args = select({\n        \"//:has_absl\": [\"--has_absl_flags\"],\n        \"//conditions:default\": [],\n    }),\n    data = [\":gtest_help_test_\"],\n    deps = [\":gtest_test_utils\"],\n)\n\ncc_binary(\n    name = \"googletest-output-test_\",\n    testonly = 1,\n    srcs = [\"googletest-output-test_.cc\"],\n    deps = [\"//:gtest\"],\n)\n\npy_test(\n    name = \"googletest-output-test\",\n    size = \"small\",\n    srcs = [\"googletest-output-test.py\"],\n    args = select({\n        \"//:has_absl\": [],\n        \"//conditions:default\": [\"--no_stacktrace_support\"],\n    }),\n    data = [\n        \"googletest-output-test-golden-lin.txt\",\n        \":googletest-output-test_\",\n    ],\n    deps = [\":gtest_test_utils\"],\n)\n\ncc_binary(\n    name = \"googletest-color-test_\",\n    testonly = 1,\n    srcs = [\"googletest-color-test_.cc\"],\n    deps = [\"//:gtest\"],\n)\n\npy_test(\n    name = \"googletest-color-test\",\n    size = \"small\",\n    srcs = [\"googletest-color-test.py\"],\n    data = [\":googletest-color-test_\"],\n    deps = [\":gtest_test_utils\"],\n)\n\ncc_binary(\n    name = \"googletest-env-var-test_\",\n    testonly = 1,\n    srcs = [\"googletest-env-var-test_.cc\"],\n    deps = [\"//:gtest\"],\n)\n\npy_test(\n    name = \"googletest-env-var-test\",\n    size = \"medium\",\n    srcs = [\"googletest-env-var-test.py\"],\n    data = [\":googletest-env-var-test_\"],\n    deps = [\":gtest_test_utils\"],\n)\n\ncc_binary(\n    name = \"googletest-failfast-unittest_\",\n    testonly = 1,\n    srcs = [\"googletest-failfast-unittest_.cc\"],\n    deps = [\"//:gtest\"],\n)\n\npy_test(\n    name = \"googletest-failfast-unittest\",\n    size = \"medium\",\n    srcs = [\"googletest-failfast-unittest.py\"],\n    data = [\":googletest-failfast-unittest_\"],\n    deps = [\":gtest_test_utils\"],\n)\n\ncc_binary(\n    name = \"googletest-filter-unittest_\",\n    testonly = 1,\n    srcs = [\"googletest-filter-unittest_.cc\"],\n    deps = [\"//:gtest\"],\n)\n\npy_test(\n    name = \"googletest-filter-unittest\",\n    size = \"medium\",\n    srcs = [\"googletest-filter-unittest.py\"],\n    data = [\":googletest-filter-unittest_\"],\n    deps = [\":gtest_test_utils\"],\n)\n\ncc_binary(\n    name = \"googletest-global-environment-unittest_\",\n    testonly = 1,\n    srcs = [\"googletest-global-environment-unittest_.cc\"],\n    deps = [\"//:gtest\"],\n)\n\npy_test(\n    name = \"googletest-global-environment-unittest\",\n    size = \"medium\",\n    srcs = [\"googletest-global-environment-unittest.py\"],\n    data = [\":googletest-global-environment-unittest_\"],\n    deps = [\":gtest_test_utils\"],\n)\n\ncc_binary(\n    name = \"googletest-break-on-failure-unittest_\",\n    testonly = 1,\n    srcs = [\"googletest-break-on-failure-unittest_.cc\"],\n    deps = [\"//:gtest\"],\n)\n\npy_test(\n    name = \"googletest-break-on-failure-unittest\",\n    size = \"small\",\n    srcs = [\"googletest-break-on-failure-unittest.py\"],\n    data = [\":googletest-break-on-failure-unittest_\"],\n    deps = [\":gtest_test_utils\"],\n)\n\ncc_test(\n    name = \"gtest_assert_by_exception_test\",\n    size = \"small\",\n    srcs = [\"gtest_assert_by_exception_test.cc\"],\n    deps = [\"//:gtest\"],\n)\n\ncc_binary(\n    name = \"googletest-throw-on-failure-test_\",\n    testonly = 1,\n    srcs = [\"googletest-throw-on-failure-test_.cc\"],\n    deps = [\"//:gtest\"],\n)\n\npy_test(\n    name = \"googletest-throw-on-failure-test\",\n    size = \"small\",\n    srcs = [\"googletest-throw-on-failure-test.py\"],\n    data = [\":googletest-throw-on-failure-test_\"],\n    deps = [\":gtest_test_utils\"],\n)\n\ncc_binary(\n    name = \"googletest-list-tests-unittest_\",\n    testonly = 1,\n    srcs = [\"googletest-list-tests-unittest_.cc\"],\n    deps = [\"//:gtest\"],\n)\n\ncc_test(\n    name = \"gtest_skip_test\",\n    size = \"small\",\n    srcs = [\"gtest_skip_test.cc\"],\n    deps = [\"//:gtest_main\"],\n)\n\ncc_test(\n    name = \"gtest_skip_in_environment_setup_test\",\n    size = \"small\",\n    srcs = [\"gtest_skip_in_environment_setup_test.cc\"],\n    deps = [\"//:gtest_main\"],\n)\n\npy_test(\n    name = \"gtest_skip_check_output_test\",\n    size = \"small\",\n    srcs = [\"gtest_skip_check_output_test.py\"],\n    data = [\":gtest_skip_test\"],\n    deps = [\":gtest_test_utils\"],\n)\n\npy_test(\n    name = \"gtest_skip_environment_check_output_test\",\n    size = \"small\",\n    srcs = [\"gtest_skip_environment_check_output_test.py\"],\n    data = [\n        \":gtest_skip_in_environment_setup_test\",\n    ],\n    deps = [\":gtest_test_utils\"],\n)\n\npy_test(\n    name = \"googletest-list-tests-unittest\",\n    size = \"small\",\n    srcs = [\"googletest-list-tests-unittest.py\"],\n    data = [\":googletest-list-tests-unittest_\"],\n    deps = [\":gtest_test_utils\"],\n)\n\ncc_binary(\n    name = \"googletest-shuffle-test_\",\n    srcs = [\"googletest-shuffle-test_.cc\"],\n    deps = [\"//:gtest\"],\n)\n\npy_test(\n    name = \"googletest-shuffle-test\",\n    size = \"small\",\n    srcs = [\"googletest-shuffle-test.py\"],\n    data = [\":googletest-shuffle-test_\"],\n    deps = [\":gtest_test_utils\"],\n)\n\ncc_binary(\n    name = \"googletest-catch-exceptions-no-ex-test_\",\n    testonly = 1,\n    srcs = [\"googletest-catch-exceptions-test_.cc\"],\n    deps = [\"//:gtest_main\"],\n)\n\ncc_binary(\n    name = \"googletest-catch-exceptions-ex-test_\",\n    testonly = 1,\n    srcs = [\"googletest-catch-exceptions-test_.cc\"],\n    copts = [\"-fexceptions\"],\n    deps = [\"//:gtest_main\"],\n)\n\npy_test(\n    name = \"googletest-catch-exceptions-test\",\n    size = \"small\",\n    srcs = [\"googletest-catch-exceptions-test.py\"],\n    data = [\n        \":googletest-catch-exceptions-ex-test_\",\n        \":googletest-catch-exceptions-no-ex-test_\",\n    ],\n    deps = [\":gtest_test_utils\"],\n)\n\ncc_binary(\n    name = \"gtest_xml_output_unittest_\",\n    testonly = 1,\n    srcs = [\"gtest_xml_output_unittest_.cc\"],\n    deps = [\"//:gtest\"],\n)\n\ncc_test(\n    name = \"gtest_no_test_unittest\",\n    size = \"small\",\n    srcs = [\"gtest_no_test_unittest.cc\"],\n    deps = [\"//:gtest\"],\n)\n\npy_test(\n    name = \"gtest_xml_output_unittest\",\n    size = \"small\",\n    srcs = [\n        \"gtest_xml_output_unittest.py\",\n        \"gtest_xml_test_utils.py\",\n    ],\n    args = select({\n        \"//:has_absl\": [],\n        \"//conditions:default\": [\"--no_stacktrace_support\"],\n    }),\n    data = [\n        # We invoke gtest_no_test_unittest to verify the XML output\n        # when the test program contains no test definition.\n        \":gtest_no_test_unittest\",\n        \":gtest_xml_output_unittest_\",\n    ],\n    deps = [\":gtest_test_utils\"],\n)\n\ncc_binary(\n    name = \"gtest_xml_outfile1_test_\",\n    testonly = 1,\n    srcs = [\"gtest_xml_outfile1_test_.cc\"],\n    deps = [\"//:gtest_main\"],\n)\n\ncc_binary(\n    name = \"gtest_xml_outfile2_test_\",\n    testonly = 1,\n    srcs = [\"gtest_xml_outfile2_test_.cc\"],\n    deps = [\"//:gtest_main\"],\n)\n\npy_test(\n    name = \"gtest_xml_outfiles_test\",\n    size = \"small\",\n    srcs = [\n        \"gtest_xml_outfiles_test.py\",\n        \"gtest_xml_test_utils.py\",\n    ],\n    data = [\n        \":gtest_xml_outfile1_test_\",\n        \":gtest_xml_outfile2_test_\",\n    ],\n    deps = [\":gtest_test_utils\"],\n)\n\ncc_binary(\n    name = \"googletest-setuptestsuite-test_\",\n    testonly = 1,\n    srcs = [\"googletest-setuptestsuite-test_.cc\"],\n    deps = [\"//:gtest_main\"],\n)\n\npy_test(\n    name = \"googletest-setuptestsuite-test\",\n    size = \"medium\",\n    srcs = [\"googletest-setuptestsuite-test.py\"],\n    data = [\":googletest-setuptestsuite-test_\"],\n    deps = [\":gtest_test_utils\"],\n)\n\ncc_binary(\n    name = \"googletest-uninitialized-test_\",\n    testonly = 1,\n    srcs = [\"googletest-uninitialized-test_.cc\"],\n    deps = [\"//:gtest\"],\n)\n\npy_test(\n    name = \"googletest-uninitialized-test\",\n    size = \"medium\",\n    srcs = [\"googletest-uninitialized-test.py\"],\n    data = [\"googletest-uninitialized-test_\"],\n    deps = [\":gtest_test_utils\"],\n)\n\ncc_binary(\n    name = \"gtest_testbridge_test_\",\n    testonly = 1,\n    srcs = [\"gtest_testbridge_test_.cc\"],\n    deps = [\"//:gtest_main\"],\n)\n\n# Tests that filtering via testbridge works\npy_test(\n    name = \"gtest_testbridge_test\",\n    size = \"small\",\n    srcs = [\"gtest_testbridge_test.py\"],\n    data = [\":gtest_testbridge_test_\"],\n    deps = [\":gtest_test_utils\"],\n)\n\npy_test(\n    name = \"googletest-json-outfiles-test\",\n    size = \"small\",\n    srcs = [\n        \"googletest-json-outfiles-test.py\",\n        \"gtest_json_test_utils.py\",\n    ],\n    data = [\n        \":gtest_xml_outfile1_test_\",\n        \":gtest_xml_outfile2_test_\",\n    ],\n    deps = [\":gtest_test_utils\"],\n)\n\npy_test(\n    name = \"googletest-json-output-unittest\",\n    size = \"medium\",\n    srcs = [\n        \"googletest-json-output-unittest.py\",\n        \"gtest_json_test_utils.py\",\n    ],\n    args = select({\n        \"//:has_absl\": [],\n        \"//conditions:default\": [\"--no_stacktrace_support\"],\n    }),\n    data = [\n        # We invoke gtest_no_test_unittest to verify the JSON output\n        # when the test program contains no test definition.\n        \":gtest_no_test_unittest\",\n        \":gtest_xml_output_unittest_\",\n    ],\n    deps = [\":gtest_test_utils\"],\n)\n\n# Verifies interaction of death tests and exceptions.\ncc_test(\n    name = \"googletest-death-test_ex_catch_test\",\n    size = \"medium\",\n    srcs = [\"googletest-death-test_ex_test.cc\"],\n    copts = [\"-fexceptions\"],\n    defines = [\"GTEST_ENABLE_CATCH_EXCEPTIONS_=1\"],\n    deps = [\"//:gtest\"],\n)\n\ncc_binary(\n    name = \"googletest-param-test-invalid-name1-test_\",\n    testonly = 1,\n    srcs = [\"googletest-param-test-invalid-name1-test_.cc\"],\n    deps = [\"//:gtest\"],\n)\n\ncc_binary(\n    name = \"googletest-param-test-invalid-name2-test_\",\n    testonly = 1,\n    srcs = [\"googletest-param-test-invalid-name2-test_.cc\"],\n    deps = [\"//:gtest\"],\n)\n\npy_test(\n    name = \"googletest-param-test-invalid-name1-test\",\n    size = \"small\",\n    srcs = [\"googletest-param-test-invalid-name1-test.py\"],\n    data = [\":googletest-param-test-invalid-name1-test_\"],\n    tags = [\n        \"no_test_msvc2015\",\n        \"no_test_msvc2017\",\n    ],\n    deps = [\":gtest_test_utils\"],\n)\n\npy_test(\n    name = \"googletest-param-test-invalid-name2-test\",\n    size = \"small\",\n    srcs = [\"googletest-param-test-invalid-name2-test.py\"],\n    data = [\":googletest-param-test-invalid-name2-test_\"],\n    tags = [\n        \"no_test_msvc2015\",\n        \"no_test_msvc2017\",\n    ],\n    deps = [\":gtest_test_utils\"],\n)\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-break-on-failure-unittest.py",
    "content": "#!/usr/bin/env python\n#\n# Copyright 2006, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Unit test for Google Test's break-on-failure mode.\n\nA user can ask Google Test to seg-fault when an assertion fails, using\neither the GTEST_BREAK_ON_FAILURE environment variable or the\n--gtest_break_on_failure flag.  This script tests such functionality\nby invoking googletest-break-on-failure-unittest_ (a program written with\nGoogle Test) with different environments and command line flags.\n\"\"\"\n\nimport os\nfrom googletest.test import gtest_test_utils\n\n# Constants.\n\nIS_WINDOWS = os.name == 'nt'\n\n# The environment variable for enabling/disabling the break-on-failure mode.\nBREAK_ON_FAILURE_ENV_VAR = 'GTEST_BREAK_ON_FAILURE'\n\n# The command line flag for enabling/disabling the break-on-failure mode.\nBREAK_ON_FAILURE_FLAG = 'gtest_break_on_failure'\n\n# The environment variable for enabling/disabling the throw-on-failure mode.\nTHROW_ON_FAILURE_ENV_VAR = 'GTEST_THROW_ON_FAILURE'\n\n# The environment variable for enabling/disabling the catch-exceptions mode.\nCATCH_EXCEPTIONS_ENV_VAR = 'GTEST_CATCH_EXCEPTIONS'\n\n# Path to the googletest-break-on-failure-unittest_ program.\nEXE_PATH = gtest_test_utils.GetTestExecutablePath(\n    'googletest-break-on-failure-unittest_')\n\n\nenviron = gtest_test_utils.environ\nSetEnvVar = gtest_test_utils.SetEnvVar\n\n# Tests in this file run a Google-Test-based test program and expect it\n# to terminate prematurely.  Therefore they are incompatible with\n# the premature-exit-file protocol by design.  Unset the\n# premature-exit filepath to prevent Google Test from creating\n# the file.\nSetEnvVar(gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR, None)\n\n\ndef Run(command):\n  \"\"\"Runs a command; returns 1 if it was killed by a signal, or 0 otherwise.\"\"\"\n\n  p = gtest_test_utils.Subprocess(command, env=environ)\n  if p.terminated_by_signal:\n    return 1\n  else:\n    return 0\n\n\n# The tests.\n\n\nclass GTestBreakOnFailureUnitTest(gtest_test_utils.TestCase):\n  \"\"\"Tests using the GTEST_BREAK_ON_FAILURE environment variable or\n  the --gtest_break_on_failure flag to turn assertion failures into\n  segmentation faults.\n  \"\"\"\n\n  def RunAndVerify(self, env_var_value, flag_value, expect_seg_fault):\n    \"\"\"Runs googletest-break-on-failure-unittest_ and verifies that it does\n    (or does not) have a seg-fault.\n\n    Args:\n      env_var_value:    value of the GTEST_BREAK_ON_FAILURE environment\n                        variable; None if the variable should be unset.\n      flag_value:       value of the --gtest_break_on_failure flag;\n                        None if the flag should not be present.\n      expect_seg_fault: 1 if the program is expected to generate a seg-fault;\n                        0 otherwise.\n    \"\"\"\n\n    SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, env_var_value)\n\n    if env_var_value is None:\n      env_var_value_msg = ' is not set'\n    else:\n      env_var_value_msg = '=' + env_var_value\n\n    if flag_value is None:\n      flag = ''\n    elif flag_value == '0':\n      flag = '--%s=0' % BREAK_ON_FAILURE_FLAG\n    else:\n      flag = '--%s' % BREAK_ON_FAILURE_FLAG\n\n    command = [EXE_PATH]\n    if flag:\n      command.append(flag)\n\n    if expect_seg_fault:\n      should_or_not = 'should'\n    else:\n      should_or_not = 'should not'\n\n    has_seg_fault = Run(command)\n\n    SetEnvVar(BREAK_ON_FAILURE_ENV_VAR, None)\n\n    msg = ('when %s%s, an assertion failure in \"%s\" %s cause a seg-fault.' %\n           (BREAK_ON_FAILURE_ENV_VAR, env_var_value_msg, ' '.join(command),\n            should_or_not))\n    self.assert_(has_seg_fault == expect_seg_fault, msg)\n\n  def testDefaultBehavior(self):\n    \"\"\"Tests the behavior of the default mode.\"\"\"\n\n    self.RunAndVerify(env_var_value=None,\n                      flag_value=None,\n                      expect_seg_fault=0)\n\n  def testEnvVar(self):\n    \"\"\"Tests using the GTEST_BREAK_ON_FAILURE environment variable.\"\"\"\n\n    self.RunAndVerify(env_var_value='0',\n                      flag_value=None,\n                      expect_seg_fault=0)\n    self.RunAndVerify(env_var_value='1',\n                      flag_value=None,\n                      expect_seg_fault=1)\n\n  def testFlag(self):\n    \"\"\"Tests using the --gtest_break_on_failure flag.\"\"\"\n\n    self.RunAndVerify(env_var_value=None,\n                      flag_value='0',\n                      expect_seg_fault=0)\n    self.RunAndVerify(env_var_value=None,\n                      flag_value='1',\n                      expect_seg_fault=1)\n\n  def testFlagOverridesEnvVar(self):\n    \"\"\"Tests that the flag overrides the environment variable.\"\"\"\n\n    self.RunAndVerify(env_var_value='0',\n                      flag_value='0',\n                      expect_seg_fault=0)\n    self.RunAndVerify(env_var_value='0',\n                      flag_value='1',\n                      expect_seg_fault=1)\n    self.RunAndVerify(env_var_value='1',\n                      flag_value='0',\n                      expect_seg_fault=0)\n    self.RunAndVerify(env_var_value='1',\n                      flag_value='1',\n                      expect_seg_fault=1)\n\n  def testBreakOnFailureOverridesThrowOnFailure(self):\n    \"\"\"Tests that gtest_break_on_failure overrides gtest_throw_on_failure.\"\"\"\n\n    SetEnvVar(THROW_ON_FAILURE_ENV_VAR, '1')\n    try:\n      self.RunAndVerify(env_var_value=None,\n                        flag_value='1',\n                        expect_seg_fault=1)\n    finally:\n      SetEnvVar(THROW_ON_FAILURE_ENV_VAR, None)\n\n  if IS_WINDOWS:\n    def testCatchExceptionsDoesNotInterfere(self):\n      \"\"\"Tests that gtest_catch_exceptions doesn't interfere.\"\"\"\n\n      SetEnvVar(CATCH_EXCEPTIONS_ENV_VAR, '1')\n      try:\n        self.RunAndVerify(env_var_value='1',\n                          flag_value='1',\n                          expect_seg_fault=1)\n      finally:\n        SetEnvVar(CATCH_EXCEPTIONS_ENV_VAR, None)\n\n\nif __name__ == '__main__':\n  gtest_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-break-on-failure-unittest_.cc",
    "content": "// Copyright 2006, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Unit test for Google Test's break-on-failure mode.\n//\n// A user can ask Google Test to seg-fault when an assertion fails, using\n// either the GTEST_BREAK_ON_FAILURE environment variable or the\n// --gtest_break_on_failure flag.  This file is used for testing such\n// functionality.\n//\n// This program will be invoked from a Python unit test.  It is\n// expected to fail.  Don't run it directly.\n\n#include \"gtest/gtest.h\"\n\n#if GTEST_OS_WINDOWS\n#include <stdlib.h>\n#include <windows.h>\n#endif\n\nnamespace {\n\n// A test that's expected to fail.\nTEST(Foo, Bar) { EXPECT_EQ(2, 3); }\n\n#if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE\n// On Windows Mobile global exception handlers are not supported.\nLONG WINAPI\nExitWithExceptionCode(struct _EXCEPTION_POINTERS* exception_pointers) {\n  exit(exception_pointers->ExceptionRecord->ExceptionCode);\n}\n#endif\n\n}  // namespace\n\nint main(int argc, char** argv) {\n#if GTEST_OS_WINDOWS\n  // Suppresses display of the Windows error dialog upon encountering\n  // a general protection fault (segment violation).\n  SetErrorMode(SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS);\n\n#if GTEST_HAS_SEH && !GTEST_OS_WINDOWS_MOBILE\n\n  // The default unhandled exception filter does not always exit\n  // with the exception code as exit code - for example it exits with\n  // 0 for EXCEPTION_ACCESS_VIOLATION and 1 for EXCEPTION_BREAKPOINT\n  // if the application is compiled in debug mode. Thus we use our own\n  // filter which always exits with the exception code for unhandled\n  // exceptions.\n  SetUnhandledExceptionFilter(ExitWithExceptionCode);\n\n#endif\n#endif  // GTEST_OS_WINDOWS\n  testing::InitGoogleTest(&argc, argv);\n\n  return RUN_ALL_TESTS();\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-catch-exceptions-test.py",
    "content": "#!/usr/bin/env python\n#\n# Copyright 2010 Google Inc.  All Rights Reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Tests Google Test's exception catching behavior.\n\nThis script invokes googletest-catch-exceptions-test_ and\ngoogletest-catch-exceptions-ex-test_ (programs written with\nGoogle Test) and verifies their output.\n\"\"\"\n\nfrom googletest.test import gtest_test_utils\n\n# Constants.\nFLAG_PREFIX = '--gtest_'\nLIST_TESTS_FLAG = FLAG_PREFIX + 'list_tests'\nNO_CATCH_EXCEPTIONS_FLAG = FLAG_PREFIX + 'catch_exceptions=0'\nFILTER_FLAG = FLAG_PREFIX + 'filter'\n\n# Path to the googletest-catch-exceptions-ex-test_ binary, compiled with\n# exceptions enabled.\nEX_EXE_PATH = gtest_test_utils.GetTestExecutablePath(\n    'googletest-catch-exceptions-ex-test_')\n\n# Path to the googletest-catch-exceptions-test_ binary, compiled with\n# exceptions disabled.\nEXE_PATH = gtest_test_utils.GetTestExecutablePath(\n    'googletest-catch-exceptions-no-ex-test_')\n\nenviron = gtest_test_utils.environ\nSetEnvVar = gtest_test_utils.SetEnvVar\n\n# Tests in this file run a Google-Test-based test program and expect it\n# to terminate prematurely.  Therefore they are incompatible with\n# the premature-exit-file protocol by design.  Unset the\n# premature-exit filepath to prevent Google Test from creating\n# the file.\nSetEnvVar(gtest_test_utils.PREMATURE_EXIT_FILE_ENV_VAR, None)\n\nTEST_LIST = gtest_test_utils.Subprocess(\n    [EXE_PATH, LIST_TESTS_FLAG], env=environ).output\n\nSUPPORTS_SEH_EXCEPTIONS = 'ThrowsSehException' in TEST_LIST\n\nif SUPPORTS_SEH_EXCEPTIONS:\n  BINARY_OUTPUT = gtest_test_utils.Subprocess([EXE_PATH], env=environ).output\n\nEX_BINARY_OUTPUT = gtest_test_utils.Subprocess(\n    [EX_EXE_PATH], env=environ).output\n\n\n# The tests.\nif SUPPORTS_SEH_EXCEPTIONS:\n  # pylint:disable-msg=C6302\n  class CatchSehExceptionsTest(gtest_test_utils.TestCase):\n    \"\"\"Tests exception-catching behavior.\"\"\"\n\n\n    def TestSehExceptions(self, test_output):\n      self.assert_('SEH exception with code 0x2a thrown '\n                   'in the test fixture\\'s constructor'\n                   in test_output)\n      self.assert_('SEH exception with code 0x2a thrown '\n                   'in the test fixture\\'s destructor'\n                   in test_output)\n      self.assert_('SEH exception with code 0x2a thrown in SetUpTestSuite()'\n                   in test_output)\n      self.assert_('SEH exception with code 0x2a thrown in TearDownTestSuite()'\n                   in test_output)\n      self.assert_('SEH exception with code 0x2a thrown in SetUp()'\n                   in test_output)\n      self.assert_('SEH exception with code 0x2a thrown in TearDown()'\n                   in test_output)\n      self.assert_('SEH exception with code 0x2a thrown in the test body'\n                   in test_output)\n\n    def testCatchesSehExceptionsWithCxxExceptionsEnabled(self):\n      self.TestSehExceptions(EX_BINARY_OUTPUT)\n\n    def testCatchesSehExceptionsWithCxxExceptionsDisabled(self):\n      self.TestSehExceptions(BINARY_OUTPUT)\n\n\nclass CatchCxxExceptionsTest(gtest_test_utils.TestCase):\n  \"\"\"Tests C++ exception-catching behavior.\n\n     Tests in this test case verify that:\n     * C++ exceptions are caught and logged as C++ (not SEH) exceptions\n     * Exception thrown affect the remainder of the test work flow in the\n       expected manner.\n  \"\"\"\n\n  def testCatchesCxxExceptionsInFixtureConstructor(self):\n    self.assertTrue(\n        'C++ exception with description '\n        '\"Standard C++ exception\" thrown '\n        'in the test fixture\\'s constructor' in EX_BINARY_OUTPUT,\n        EX_BINARY_OUTPUT)\n    self.assert_('unexpected' not in EX_BINARY_OUTPUT,\n                 'This failure belongs in this test only if '\n                 '\"CxxExceptionInConstructorTest\" (no quotes) '\n                 'appears on the same line as words \"called unexpectedly\"')\n\n  if ('CxxExceptionInDestructorTest.ThrowsExceptionInDestructor' in\n      EX_BINARY_OUTPUT):\n\n    def testCatchesCxxExceptionsInFixtureDestructor(self):\n      self.assertTrue(\n          'C++ exception with description '\n          '\"Standard C++ exception\" thrown '\n          'in the test fixture\\'s destructor' in EX_BINARY_OUTPUT,\n          EX_BINARY_OUTPUT)\n      self.assertTrue(\n          'CxxExceptionInDestructorTest::TearDownTestSuite() '\n          'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)\n\n  def testCatchesCxxExceptionsInSetUpTestCase(self):\n    self.assertTrue(\n        'C++ exception with description \"Standard C++ exception\"'\n        ' thrown in SetUpTestSuite()' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)\n    self.assertTrue(\n        'CxxExceptionInConstructorTest::TearDownTestSuite() '\n        'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)\n    self.assertFalse(\n        'CxxExceptionInSetUpTestSuiteTest constructor '\n        'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)\n    self.assertFalse(\n        'CxxExceptionInSetUpTestSuiteTest destructor '\n        'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)\n    self.assertFalse(\n        'CxxExceptionInSetUpTestSuiteTest::SetUp() '\n        'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)\n    self.assertFalse(\n        'CxxExceptionInSetUpTestSuiteTest::TearDown() '\n        'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)\n    self.assertFalse(\n        'CxxExceptionInSetUpTestSuiteTest test body '\n        'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)\n\n  def testCatchesCxxExceptionsInTearDownTestCase(self):\n    self.assertTrue(\n        'C++ exception with description \"Standard C++ exception\"'\n        ' thrown in TearDownTestSuite()' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)\n\n  def testCatchesCxxExceptionsInSetUp(self):\n    self.assertTrue(\n        'C++ exception with description \"Standard C++ exception\"'\n        ' thrown in SetUp()' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)\n    self.assertTrue(\n        'CxxExceptionInSetUpTest::TearDownTestSuite() '\n        'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)\n    self.assertTrue(\n        'CxxExceptionInSetUpTest destructor '\n        'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)\n    self.assertTrue(\n        'CxxExceptionInSetUpTest::TearDown() '\n        'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)\n    self.assert_('unexpected' not in EX_BINARY_OUTPUT,\n                 'This failure belongs in this test only if '\n                 '\"CxxExceptionInSetUpTest\" (no quotes) '\n                 'appears on the same line as words \"called unexpectedly\"')\n\n  def testCatchesCxxExceptionsInTearDown(self):\n    self.assertTrue(\n        'C++ exception with description \"Standard C++ exception\"'\n        ' thrown in TearDown()' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)\n    self.assertTrue(\n        'CxxExceptionInTearDownTest::TearDownTestSuite() '\n        'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)\n    self.assertTrue(\n        'CxxExceptionInTearDownTest destructor '\n        'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)\n\n  def testCatchesCxxExceptionsInTestBody(self):\n    self.assertTrue(\n        'C++ exception with description \"Standard C++ exception\"'\n        ' thrown in the test body' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)\n    self.assertTrue(\n        'CxxExceptionInTestBodyTest::TearDownTestSuite() '\n        'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)\n    self.assertTrue(\n        'CxxExceptionInTestBodyTest destructor '\n        'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)\n    self.assertTrue(\n        'CxxExceptionInTestBodyTest::TearDown() '\n        'called as expected.' in EX_BINARY_OUTPUT, EX_BINARY_OUTPUT)\n\n  def testCatchesNonStdCxxExceptions(self):\n    self.assertTrue(\n        'Unknown C++ exception thrown in the test body' in EX_BINARY_OUTPUT,\n        EX_BINARY_OUTPUT)\n\n  def testUnhandledCxxExceptionsAbortTheProgram(self):\n    # Filters out SEH exception tests on Windows. Unhandled SEH exceptions\n    # cause tests to show pop-up windows there.\n    FITLER_OUT_SEH_TESTS_FLAG = FILTER_FLAG + '=-*Seh*'\n    # By default, Google Test doesn't catch the exceptions.\n    uncaught_exceptions_ex_binary_output = gtest_test_utils.Subprocess(\n        [EX_EXE_PATH,\n         NO_CATCH_EXCEPTIONS_FLAG,\n         FITLER_OUT_SEH_TESTS_FLAG],\n        env=environ).output\n\n    self.assert_('Unhandled C++ exception terminating the program'\n                 in uncaught_exceptions_ex_binary_output)\n    self.assert_('unexpected' not in uncaught_exceptions_ex_binary_output)\n\n\nif __name__ == '__main__':\n  gtest_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-catch-exceptions-test_.cc",
    "content": "// Copyright 2010, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// Tests for Google Test itself. Tests in this file throw C++ or SEH\n// exceptions, and the output is verified by\n// googletest-catch-exceptions-test.py.\n\n#include <stdio.h>   // NOLINT\n#include <stdlib.h>  // For exit().\n\n#include \"gtest/gtest.h\"\n\n#if GTEST_HAS_SEH\n#include <windows.h>\n#endif\n\n#if GTEST_HAS_EXCEPTIONS\n#include <exception>  // For set_terminate().\n#include <stdexcept>\n#endif\n\nusing testing::Test;\n\n#if GTEST_HAS_SEH\n\nclass SehExceptionInConstructorTest : public Test {\n public:\n  SehExceptionInConstructorTest() { RaiseException(42, 0, 0, NULL); }\n};\n\nTEST_F(SehExceptionInConstructorTest, ThrowsExceptionInConstructor) {}\n\nclass SehExceptionInDestructorTest : public Test {\n public:\n  ~SehExceptionInDestructorTest() { RaiseException(42, 0, 0, NULL); }\n};\n\nTEST_F(SehExceptionInDestructorTest, ThrowsExceptionInDestructor) {}\n\nclass SehExceptionInSetUpTestSuiteTest : public Test {\n public:\n  static void SetUpTestSuite() { RaiseException(42, 0, 0, NULL); }\n};\n\nTEST_F(SehExceptionInSetUpTestSuiteTest, ThrowsExceptionInSetUpTestSuite) {}\n\nclass SehExceptionInTearDownTestSuiteTest : public Test {\n public:\n  static void TearDownTestSuite() { RaiseException(42, 0, 0, NULL); }\n};\n\nTEST_F(SehExceptionInTearDownTestSuiteTest,\n       ThrowsExceptionInTearDownTestSuite) {}\n\nclass SehExceptionInSetUpTest : public Test {\n protected:\n  virtual void SetUp() { RaiseException(42, 0, 0, NULL); }\n};\n\nTEST_F(SehExceptionInSetUpTest, ThrowsExceptionInSetUp) {}\n\nclass SehExceptionInTearDownTest : public Test {\n protected:\n  virtual void TearDown() { RaiseException(42, 0, 0, NULL); }\n};\n\nTEST_F(SehExceptionInTearDownTest, ThrowsExceptionInTearDown) {}\n\nTEST(SehExceptionTest, ThrowsSehException) { RaiseException(42, 0, 0, NULL); }\n\n#endif  // GTEST_HAS_SEH\n\n#if GTEST_HAS_EXCEPTIONS\n\nclass CxxExceptionInConstructorTest : public Test {\n public:\n  CxxExceptionInConstructorTest() {\n    // Without this macro VC++ complains about unreachable code at the end of\n    // the constructor.\n    GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(\n        throw std::runtime_error(\"Standard C++ exception\"));\n  }\n\n  static void TearDownTestSuite() {\n    printf(\"%s\",\n           \"CxxExceptionInConstructorTest::TearDownTestSuite() \"\n           \"called as expected.\\n\");\n  }\n\n protected:\n  ~CxxExceptionInConstructorTest() override {\n    ADD_FAILURE() << \"CxxExceptionInConstructorTest destructor \"\n                  << \"called unexpectedly.\";\n  }\n\n  void SetUp() override {\n    ADD_FAILURE() << \"CxxExceptionInConstructorTest::SetUp() \"\n                  << \"called unexpectedly.\";\n  }\n\n  void TearDown() override {\n    ADD_FAILURE() << \"CxxExceptionInConstructorTest::TearDown() \"\n                  << \"called unexpectedly.\";\n  }\n};\n\nTEST_F(CxxExceptionInConstructorTest, ThrowsExceptionInConstructor) {\n  ADD_FAILURE() << \"CxxExceptionInConstructorTest test body \"\n                << \"called unexpectedly.\";\n}\n\nclass CxxExceptionInSetUpTestSuiteTest : public Test {\n public:\n  CxxExceptionInSetUpTestSuiteTest() {\n    printf(\"%s\",\n           \"CxxExceptionInSetUpTestSuiteTest constructor \"\n           \"called as expected.\\n\");\n  }\n\n  static void SetUpTestSuite() {\n    throw std::runtime_error(\"Standard C++ exception\");\n  }\n\n  static void TearDownTestSuite() {\n    printf(\"%s\",\n           \"CxxExceptionInSetUpTestSuiteTest::TearDownTestSuite() \"\n           \"called as expected.\\n\");\n  }\n\n protected:\n  ~CxxExceptionInSetUpTestSuiteTest() override {\n    printf(\"%s\",\n           \"CxxExceptionInSetUpTestSuiteTest destructor \"\n           \"called as expected.\\n\");\n  }\n\n  void SetUp() override {\n    printf(\"%s\",\n           \"CxxExceptionInSetUpTestSuiteTest::SetUp() \"\n           \"called as expected.\\n\");\n  }\n\n  void TearDown() override {\n    printf(\"%s\",\n           \"CxxExceptionInSetUpTestSuiteTest::TearDown() \"\n           \"called as expected.\\n\");\n  }\n};\n\nTEST_F(CxxExceptionInSetUpTestSuiteTest, ThrowsExceptionInSetUpTestSuite) {\n  printf(\"%s\",\n         \"CxxExceptionInSetUpTestSuiteTest test body \"\n         \"called as expected.\\n\");\n}\n\nclass CxxExceptionInTearDownTestSuiteTest : public Test {\n public:\n  static void TearDownTestSuite() {\n    throw std::runtime_error(\"Standard C++ exception\");\n  }\n};\n\nTEST_F(CxxExceptionInTearDownTestSuiteTest,\n       ThrowsExceptionInTearDownTestSuite) {}\n\nclass CxxExceptionInSetUpTest : public Test {\n public:\n  static void TearDownTestSuite() {\n    printf(\"%s\",\n           \"CxxExceptionInSetUpTest::TearDownTestSuite() \"\n           \"called as expected.\\n\");\n  }\n\n protected:\n  ~CxxExceptionInSetUpTest() override {\n    printf(\"%s\",\n           \"CxxExceptionInSetUpTest destructor \"\n           \"called as expected.\\n\");\n  }\n\n  void SetUp() override { throw std::runtime_error(\"Standard C++ exception\"); }\n\n  void TearDown() override {\n    printf(\"%s\",\n           \"CxxExceptionInSetUpTest::TearDown() \"\n           \"called as expected.\\n\");\n  }\n};\n\nTEST_F(CxxExceptionInSetUpTest, ThrowsExceptionInSetUp) {\n  ADD_FAILURE() << \"CxxExceptionInSetUpTest test body \"\n                << \"called unexpectedly.\";\n}\n\nclass CxxExceptionInTearDownTest : public Test {\n public:\n  static void TearDownTestSuite() {\n    printf(\"%s\",\n           \"CxxExceptionInTearDownTest::TearDownTestSuite() \"\n           \"called as expected.\\n\");\n  }\n\n protected:\n  ~CxxExceptionInTearDownTest() override {\n    printf(\"%s\",\n           \"CxxExceptionInTearDownTest destructor \"\n           \"called as expected.\\n\");\n  }\n\n  void TearDown() override {\n    throw std::runtime_error(\"Standard C++ exception\");\n  }\n};\n\nTEST_F(CxxExceptionInTearDownTest, ThrowsExceptionInTearDown) {}\n\nclass CxxExceptionInTestBodyTest : public Test {\n public:\n  static void TearDownTestSuite() {\n    printf(\"%s\",\n           \"CxxExceptionInTestBodyTest::TearDownTestSuite() \"\n           \"called as expected.\\n\");\n  }\n\n protected:\n  ~CxxExceptionInTestBodyTest() override {\n    printf(\"%s\",\n           \"CxxExceptionInTestBodyTest destructor \"\n           \"called as expected.\\n\");\n  }\n\n  void TearDown() override {\n    printf(\"%s\",\n           \"CxxExceptionInTestBodyTest::TearDown() \"\n           \"called as expected.\\n\");\n  }\n};\n\nTEST_F(CxxExceptionInTestBodyTest, ThrowsStdCxxException) {\n  throw std::runtime_error(\"Standard C++ exception\");\n}\n\nTEST(CxxExceptionTest, ThrowsNonStdCxxException) { throw \"C-string\"; }\n\n// This terminate handler aborts the program using exit() rather than abort().\n// This avoids showing pop-ups on Windows systems and core dumps on Unix-like\n// ones.\nvoid TerminateHandler() {\n  fprintf(stderr, \"%s\\n\", \"Unhandled C++ exception terminating the program.\");\n  fflush(nullptr);\n  exit(3);\n}\n\n#endif  // GTEST_HAS_EXCEPTIONS\n\nint main(int argc, char** argv) {\n#if GTEST_HAS_EXCEPTIONS\n  std::set_terminate(&TerminateHandler);\n#endif\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-color-test.py",
    "content": "#!/usr/bin/env python\n#\n# Copyright 2008, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Verifies that Google Test correctly determines whether to use colors.\"\"\"\n\nimport os\nfrom googletest.test import gtest_test_utils\n\nIS_WINDOWS = os.name == 'nt'\n\nCOLOR_ENV_VAR = 'GTEST_COLOR'\nCOLOR_FLAG = 'gtest_color'\nCOMMAND = gtest_test_utils.GetTestExecutablePath('googletest-color-test_')\n\n\ndef SetEnvVar(env_var, value):\n  \"\"\"Sets the env variable to 'value'; unsets it when 'value' is None.\"\"\"\n\n  if value is not None:\n    os.environ[env_var] = value\n  elif env_var in os.environ:\n    del os.environ[env_var]\n\n\ndef UsesColor(term, color_env_var, color_flag):\n  \"\"\"Runs googletest-color-test_ and returns its exit code.\"\"\"\n\n  SetEnvVar('TERM', term)\n  SetEnvVar(COLOR_ENV_VAR, color_env_var)\n\n  if color_flag is None:\n    args = []\n  else:\n    args = ['--%s=%s' % (COLOR_FLAG, color_flag)]\n  p = gtest_test_utils.Subprocess([COMMAND] + args)\n  return not p.exited or p.exit_code\n\n\nclass GTestColorTest(gtest_test_utils.TestCase):\n  def testNoEnvVarNoFlag(self):\n    \"\"\"Tests the case when there's neither GTEST_COLOR nor --gtest_color.\"\"\"\n\n    if not IS_WINDOWS:\n      self.assert_(not UsesColor('dumb', None, None))\n      self.assert_(not UsesColor('emacs', None, None))\n      self.assert_(not UsesColor('xterm-mono', None, None))\n      self.assert_(not UsesColor('unknown', None, None))\n      self.assert_(not UsesColor(None, None, None))\n    self.assert_(UsesColor('linux', None, None))\n    self.assert_(UsesColor('cygwin', None, None))\n    self.assert_(UsesColor('xterm', None, None))\n    self.assert_(UsesColor('xterm-color', None, None))\n    self.assert_(UsesColor('xterm-256color', None, None))\n\n  def testFlagOnly(self):\n    \"\"\"Tests the case when there's --gtest_color but not GTEST_COLOR.\"\"\"\n\n    self.assert_(not UsesColor('dumb', None, 'no'))\n    self.assert_(not UsesColor('xterm-color', None, 'no'))\n    if not IS_WINDOWS:\n      self.assert_(not UsesColor('emacs', None, 'auto'))\n    self.assert_(UsesColor('xterm', None, 'auto'))\n    self.assert_(UsesColor('dumb', None, 'yes'))\n    self.assert_(UsesColor('xterm', None, 'yes'))\n\n  def testEnvVarOnly(self):\n    \"\"\"Tests the case when there's GTEST_COLOR but not --gtest_color.\"\"\"\n\n    self.assert_(not UsesColor('dumb', 'no', None))\n    self.assert_(not UsesColor('xterm-color', 'no', None))\n    if not IS_WINDOWS:\n      self.assert_(not UsesColor('dumb', 'auto', None))\n    self.assert_(UsesColor('xterm-color', 'auto', None))\n    self.assert_(UsesColor('dumb', 'yes', None))\n    self.assert_(UsesColor('xterm-color', 'yes', None))\n\n  def testEnvVarAndFlag(self):\n    \"\"\"Tests the case when there are both GTEST_COLOR and --gtest_color.\"\"\"\n\n    self.assert_(not UsesColor('xterm-color', 'no', 'no'))\n    self.assert_(UsesColor('dumb', 'no', 'yes'))\n    self.assert_(UsesColor('xterm-color', 'no', 'auto'))\n\n  def testAliasesOfYesAndNo(self):\n    \"\"\"Tests using aliases in specifying --gtest_color.\"\"\"\n\n    self.assert_(UsesColor('dumb', None, 'true'))\n    self.assert_(UsesColor('dumb', None, 'YES'))\n    self.assert_(UsesColor('dumb', None, 'T'))\n    self.assert_(UsesColor('dumb', None, '1'))\n\n    self.assert_(not UsesColor('xterm', None, 'f'))\n    self.assert_(not UsesColor('xterm', None, 'false'))\n    self.assert_(not UsesColor('xterm', None, '0'))\n    self.assert_(not UsesColor('xterm', None, 'unknown'))\n\n\nif __name__ == '__main__':\n  gtest_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-color-test_.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// A helper program for testing how Google Test determines whether to use\n// colors in the output.  It prints \"YES\" and returns 1 if Google Test\n// decides to use colors, and prints \"NO\" and returns 0 otherwise.\n\n#include <stdio.h>\n\n#include \"gtest/gtest.h\"\n#include \"src/gtest-internal-inl.h\"\n\nusing testing::internal::ShouldUseColor;\n\n// The purpose of this is to ensure that the UnitTest singleton is\n// created before main() is entered, and thus that ShouldUseColor()\n// works the same way as in a real Google-Test-based test.  We don't actual\n// run the TEST itself.\nTEST(GTestColorTest, Dummy) {}\n\nint main(int argc, char** argv) {\n  testing::InitGoogleTest(&argc, argv);\n\n  if (ShouldUseColor(true)) {\n    // Google Test decides to use colors in the output (assuming it\n    // goes to a TTY).\n    printf(\"YES\\n\");\n    return 1;\n  } else {\n    // Google Test decides not to use colors in the output.\n    printf(\"NO\\n\");\n    return 0;\n  }\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-death-test-test.cc",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// Tests for death tests.\n\n#include \"gtest/gtest-death-test.h\"\n#include \"gtest/gtest.h\"\n#include \"gtest/internal/gtest-filepath.h\"\n\nusing testing::internal::AlwaysFalse;\nusing testing::internal::AlwaysTrue;\n\n#if GTEST_HAS_DEATH_TEST\n\n#if GTEST_OS_WINDOWS\n#include <direct.h>  // For chdir().\n#include <fcntl.h>   // For O_BINARY\n#include <io.h>\n#else\n#include <sys/wait.h>  // For waitpid.\n#include <unistd.h>\n#endif  // GTEST_OS_WINDOWS\n\n#include <limits.h>\n#include <signal.h>\n#include <stdio.h>\n\n#if GTEST_OS_LINUX\n#include <sys/time.h>\n#endif  // GTEST_OS_LINUX\n\n#include \"gtest/gtest-spi.h\"\n#include \"src/gtest-internal-inl.h\"\n\nnamespace posix = ::testing::internal::posix;\n\nusing testing::ContainsRegex;\nusing testing::Matcher;\nusing testing::Message;\nusing testing::internal::DeathTest;\nusing testing::internal::DeathTestFactory;\nusing testing::internal::FilePath;\nusing testing::internal::GetLastErrnoDescription;\nusing testing::internal::GetUnitTestImpl;\nusing testing::internal::InDeathTestChild;\nusing testing::internal::ParseNaturalNumber;\n\nnamespace testing {\nnamespace internal {\n\n// A helper class whose objects replace the death test factory for a\n// single UnitTest object during their lifetimes.\nclass ReplaceDeathTestFactory {\n public:\n  explicit ReplaceDeathTestFactory(DeathTestFactory* new_factory)\n      : unit_test_impl_(GetUnitTestImpl()) {\n    old_factory_ = unit_test_impl_->death_test_factory_.release();\n    unit_test_impl_->death_test_factory_.reset(new_factory);\n  }\n\n  ~ReplaceDeathTestFactory() {\n    unit_test_impl_->death_test_factory_.release();\n    unit_test_impl_->death_test_factory_.reset(old_factory_);\n  }\n\n private:\n  // Prevents copying ReplaceDeathTestFactory objects.\n  ReplaceDeathTestFactory(const ReplaceDeathTestFactory&);\n  void operator=(const ReplaceDeathTestFactory&);\n\n  UnitTestImpl* unit_test_impl_;\n  DeathTestFactory* old_factory_;\n};\n\n}  // namespace internal\n}  // namespace testing\n\nnamespace {\n\nvoid DieWithMessage(const ::std::string& message) {\n  fprintf(stderr, \"%s\", message.c_str());\n  fflush(stderr);  // Make sure the text is printed before the process exits.\n\n  // We call _exit() instead of exit(), as the former is a direct\n  // system call and thus safer in the presence of threads.  exit()\n  // will invoke user-defined exit-hooks, which may do dangerous\n  // things that conflict with death tests.\n  //\n  // Some compilers can recognize that _exit() never returns and issue the\n  // 'unreachable code' warning for code following this function, unless\n  // fooled by a fake condition.\n  if (AlwaysTrue()) _exit(1);\n}\n\nvoid DieInside(const ::std::string& function) {\n  DieWithMessage(\"death inside \" + function + \"().\");\n}\n\n// Tests that death tests work.\n\nclass TestForDeathTest : public testing::Test {\n protected:\n  TestForDeathTest() : original_dir_(FilePath::GetCurrentDir()) {}\n\n  ~TestForDeathTest() override { posix::ChDir(original_dir_.c_str()); }\n\n  // A static member function that's expected to die.\n  static void StaticMemberFunction() { DieInside(\"StaticMemberFunction\"); }\n\n  // A method of the test fixture that may die.\n  void MemberFunction() {\n    if (should_die_) DieInside(\"MemberFunction\");\n  }\n\n  // True if and only if MemberFunction() should die.\n  bool should_die_;\n  const FilePath original_dir_;\n};\n\n// A class with a member function that may die.\nclass MayDie {\n public:\n  explicit MayDie(bool should_die) : should_die_(should_die) {}\n\n  // A member function that may die.\n  void MemberFunction() const {\n    if (should_die_) DieInside(\"MayDie::MemberFunction\");\n  }\n\n private:\n  // True if and only if MemberFunction() should die.\n  bool should_die_;\n};\n\n// A global function that's expected to die.\nvoid GlobalFunction() { DieInside(\"GlobalFunction\"); }\n\n// A non-void function that's expected to die.\nint NonVoidFunction() {\n  DieInside(\"NonVoidFunction\");\n  return 1;\n}\n\n// A unary function that may die.\nvoid DieIf(bool should_die) {\n  if (should_die) DieInside(\"DieIf\");\n}\n\n// A binary function that may die.\nbool DieIfLessThan(int x, int y) {\n  if (x < y) {\n    DieInside(\"DieIfLessThan\");\n  }\n  return true;\n}\n\n// Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.\nvoid DeathTestSubroutine() {\n  EXPECT_DEATH(GlobalFunction(), \"death.*GlobalFunction\");\n  ASSERT_DEATH(GlobalFunction(), \"death.*GlobalFunction\");\n}\n\n// Death in dbg, not opt.\nint DieInDebugElse12(int* sideeffect) {\n  if (sideeffect) *sideeffect = 12;\n\n#ifndef NDEBUG\n\n  DieInside(\"DieInDebugElse12\");\n\n#endif  // NDEBUG\n\n  return 12;\n}\n\n#if GTEST_OS_WINDOWS\n\n// Death in dbg due to Windows CRT assertion failure, not opt.\nint DieInCRTDebugElse12(int* sideeffect) {\n  if (sideeffect) *sideeffect = 12;\n\n  // Create an invalid fd by closing a valid one\n  int fdpipe[2];\n  EXPECT_EQ(_pipe(fdpipe, 256, O_BINARY), 0);\n  EXPECT_EQ(_close(fdpipe[0]), 0);\n  EXPECT_EQ(_close(fdpipe[1]), 0);\n\n  // _dup() should crash in debug mode\n  EXPECT_EQ(_dup(fdpipe[0]), -1);\n\n  return 12;\n}\n\n#endif  // GTEST_OS_WINDOWS\n\n#if GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA\n\n// Tests the ExitedWithCode predicate.\nTEST(ExitStatusPredicateTest, ExitedWithCode) {\n  // On Windows, the process's exit code is the same as its exit status,\n  // so the predicate just compares the its input with its parameter.\n  EXPECT_TRUE(testing::ExitedWithCode(0)(0));\n  EXPECT_TRUE(testing::ExitedWithCode(1)(1));\n  EXPECT_TRUE(testing::ExitedWithCode(42)(42));\n  EXPECT_FALSE(testing::ExitedWithCode(0)(1));\n  EXPECT_FALSE(testing::ExitedWithCode(1)(0));\n}\n\n#else\n\n// Returns the exit status of a process that calls _exit(2) with a\n// given exit code.  This is a helper function for the\n// ExitStatusPredicateTest test suite.\nstatic int NormalExitStatus(int exit_code) {\n  pid_t child_pid = fork();\n  if (child_pid == 0) {\n    _exit(exit_code);\n  }\n  int status;\n  waitpid(child_pid, &status, 0);\n  return status;\n}\n\n// Returns the exit status of a process that raises a given signal.\n// If the signal does not cause the process to die, then it returns\n// instead the exit status of a process that exits normally with exit\n// code 1.  This is a helper function for the ExitStatusPredicateTest\n// test suite.\nstatic int KilledExitStatus(int signum) {\n  pid_t child_pid = fork();\n  if (child_pid == 0) {\n    raise(signum);\n    _exit(1);\n  }\n  int status;\n  waitpid(child_pid, &status, 0);\n  return status;\n}\n\n// Tests the ExitedWithCode predicate.\nTEST(ExitStatusPredicateTest, ExitedWithCode) {\n  const int status0 = NormalExitStatus(0);\n  const int status1 = NormalExitStatus(1);\n  const int status42 = NormalExitStatus(42);\n  const testing::ExitedWithCode pred0(0);\n  const testing::ExitedWithCode pred1(1);\n  const testing::ExitedWithCode pred42(42);\n  EXPECT_PRED1(pred0, status0);\n  EXPECT_PRED1(pred1, status1);\n  EXPECT_PRED1(pred42, status42);\n  EXPECT_FALSE(pred0(status1));\n  EXPECT_FALSE(pred42(status0));\n  EXPECT_FALSE(pred1(status42));\n}\n\n// Tests the KilledBySignal predicate.\nTEST(ExitStatusPredicateTest, KilledBySignal) {\n  const int status_segv = KilledExitStatus(SIGSEGV);\n  const int status_kill = KilledExitStatus(SIGKILL);\n  const testing::KilledBySignal pred_segv(SIGSEGV);\n  const testing::KilledBySignal pred_kill(SIGKILL);\n  EXPECT_PRED1(pred_segv, status_segv);\n  EXPECT_PRED1(pred_kill, status_kill);\n  EXPECT_FALSE(pred_segv(status_kill));\n  EXPECT_FALSE(pred_kill(status_segv));\n}\n\n#endif  // GTEST_OS_WINDOWS || GTEST_OS_FUCHSIA\n\n// The following code intentionally tests a suboptimal syntax.\n#ifdef __GNUC__\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wdangling-else\"\n#pragma GCC diagnostic ignored \"-Wempty-body\"\n#pragma GCC diagnostic ignored \"-Wpragmas\"\n#endif\n// Tests that the death test macros expand to code which may or may not\n// be followed by operator<<, and that in either case the complete text\n// comprises only a single C++ statement.\nTEST_F(TestForDeathTest, SingleStatement) {\n  if (AlwaysFalse())\n    // This would fail if executed; this is a compilation test only\n    ASSERT_DEATH(return, \"\");\n\n  if (AlwaysTrue())\n    EXPECT_DEATH(_exit(1), \"\");\n  else\n    // This empty \"else\" branch is meant to ensure that EXPECT_DEATH\n    // doesn't expand into an \"if\" statement without an \"else\"\n    ;\n\n  if (AlwaysFalse()) ASSERT_DEATH(return, \"\") << \"did not die\";\n\n  if (AlwaysFalse())\n    ;\n  else\n    EXPECT_DEATH(_exit(1), \"\") << 1 << 2 << 3;\n}\n#ifdef __GNUC__\n#pragma GCC diagnostic pop\n#endif\n\n#if GTEST_USES_PCRE\n\nvoid DieWithEmbeddedNul() {\n  fprintf(stderr, \"Hello%cmy null world.\\n\", '\\0');\n  fflush(stderr);\n  _exit(1);\n}\n\n// Tests that EXPECT_DEATH and ASSERT_DEATH work when the error\n// message has a NUL character in it.\nTEST_F(TestForDeathTest, EmbeddedNulInMessage) {\n  EXPECT_DEATH(DieWithEmbeddedNul(), \"my null world\");\n  ASSERT_DEATH(DieWithEmbeddedNul(), \"my null world\");\n}\n\n#endif  // GTEST_USES_PCRE\n\n// Tests that death test macros expand to code which interacts well with switch\n// statements.\nTEST_F(TestForDeathTest, SwitchStatement) {\n  // Microsoft compiler usually complains about switch statements without\n  // case labels. We suppress that warning for this test.\n  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065)\n\n  switch (0)\n  default:\n    ASSERT_DEATH(_exit(1), \"\") << \"exit in default switch handler\";\n\n  switch (0)\n  case 0:\n    EXPECT_DEATH(_exit(1), \"\") << \"exit in switch case\";\n\n  GTEST_DISABLE_MSC_WARNINGS_POP_()\n}\n\n// Tests that a static member function can be used in a \"fast\" style\n// death test.\nTEST_F(TestForDeathTest, StaticMemberFunctionFastStyle) {\n  GTEST_FLAG_SET(death_test_style, \"fast\");\n  ASSERT_DEATH(StaticMemberFunction(), \"death.*StaticMember\");\n}\n\n// Tests that a method of the test fixture can be used in a \"fast\"\n// style death test.\nTEST_F(TestForDeathTest, MemberFunctionFastStyle) {\n  GTEST_FLAG_SET(death_test_style, \"fast\");\n  should_die_ = true;\n  EXPECT_DEATH(MemberFunction(), \"inside.*MemberFunction\");\n}\n\nvoid ChangeToRootDir() { posix::ChDir(GTEST_PATH_SEP_); }\n\n// Tests that death tests work even if the current directory has been\n// changed.\nTEST_F(TestForDeathTest, FastDeathTestInChangedDir) {\n  GTEST_FLAG_SET(death_test_style, \"fast\");\n\n  ChangeToRootDir();\n  EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), \"\");\n\n  ChangeToRootDir();\n  ASSERT_DEATH(_exit(1), \"\");\n}\n\n#if GTEST_OS_LINUX\nvoid SigprofAction(int, siginfo_t*, void*) { /* no op */\n}\n\n// Sets SIGPROF action and ITIMER_PROF timer (interval: 1ms).\nvoid SetSigprofActionAndTimer() {\n  struct sigaction signal_action;\n  memset(&signal_action, 0, sizeof(signal_action));\n  sigemptyset(&signal_action.sa_mask);\n  signal_action.sa_sigaction = SigprofAction;\n  signal_action.sa_flags = SA_RESTART | SA_SIGINFO;\n  ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, nullptr));\n  // timer comes second, to avoid SIGPROF premature delivery, as suggested at\n  // https://www.gnu.org/software/libc/manual/html_node/Setting-an-Alarm.html\n  struct itimerval timer;\n  timer.it_interval.tv_sec = 0;\n  timer.it_interval.tv_usec = 1;\n  timer.it_value = timer.it_interval;\n  ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, nullptr));\n}\n\n// Disables ITIMER_PROF timer and ignores SIGPROF signal.\nvoid DisableSigprofActionAndTimer(struct sigaction* old_signal_action) {\n  struct itimerval timer;\n  timer.it_interval.tv_sec = 0;\n  timer.it_interval.tv_usec = 0;\n  timer.it_value = timer.it_interval;\n  ASSERT_EQ(0, setitimer(ITIMER_PROF, &timer, nullptr));\n  struct sigaction signal_action;\n  memset(&signal_action, 0, sizeof(signal_action));\n  sigemptyset(&signal_action.sa_mask);\n  signal_action.sa_handler = SIG_IGN;\n  ASSERT_EQ(0, sigaction(SIGPROF, &signal_action, old_signal_action));\n}\n\n// Tests that death tests work when SIGPROF handler and timer are set.\nTEST_F(TestForDeathTest, FastSigprofActionSet) {\n  GTEST_FLAG_SET(death_test_style, \"fast\");\n  SetSigprofActionAndTimer();\n  EXPECT_DEATH(_exit(1), \"\");\n  struct sigaction old_signal_action;\n  DisableSigprofActionAndTimer(&old_signal_action);\n  EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction);\n}\n\nTEST_F(TestForDeathTest, ThreadSafeSigprofActionSet) {\n  GTEST_FLAG_SET(death_test_style, \"threadsafe\");\n  SetSigprofActionAndTimer();\n  EXPECT_DEATH(_exit(1), \"\");\n  struct sigaction old_signal_action;\n  DisableSigprofActionAndTimer(&old_signal_action);\n  EXPECT_TRUE(old_signal_action.sa_sigaction == SigprofAction);\n}\n#endif  // GTEST_OS_LINUX\n\n// Repeats a representative sample of death tests in the \"threadsafe\" style:\n\nTEST_F(TestForDeathTest, StaticMemberFunctionThreadsafeStyle) {\n  GTEST_FLAG_SET(death_test_style, \"threadsafe\");\n  ASSERT_DEATH(StaticMemberFunction(), \"death.*StaticMember\");\n}\n\nTEST_F(TestForDeathTest, MemberFunctionThreadsafeStyle) {\n  GTEST_FLAG_SET(death_test_style, \"threadsafe\");\n  should_die_ = true;\n  EXPECT_DEATH(MemberFunction(), \"inside.*MemberFunction\");\n}\n\nTEST_F(TestForDeathTest, ThreadsafeDeathTestInLoop) {\n  GTEST_FLAG_SET(death_test_style, \"threadsafe\");\n\n  for (int i = 0; i < 3; ++i)\n    EXPECT_EXIT(_exit(i), testing::ExitedWithCode(i), \"\") << \": i = \" << i;\n}\n\nTEST_F(TestForDeathTest, ThreadsafeDeathTestInChangedDir) {\n  GTEST_FLAG_SET(death_test_style, \"threadsafe\");\n\n  ChangeToRootDir();\n  EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), \"\");\n\n  ChangeToRootDir();\n  ASSERT_DEATH(_exit(1), \"\");\n}\n\nTEST_F(TestForDeathTest, MixedStyles) {\n  GTEST_FLAG_SET(death_test_style, \"threadsafe\");\n  EXPECT_DEATH(_exit(1), \"\");\n  GTEST_FLAG_SET(death_test_style, \"fast\");\n  EXPECT_DEATH(_exit(1), \"\");\n}\n\n#if GTEST_HAS_CLONE && GTEST_HAS_PTHREAD\n\nbool pthread_flag;\n\nvoid SetPthreadFlag() { pthread_flag = true; }\n\nTEST_F(TestForDeathTest, DoesNotExecuteAtforkHooks) {\n  if (!GTEST_FLAG_GET(death_test_use_fork)) {\n    GTEST_FLAG_SET(death_test_style, \"threadsafe\");\n    pthread_flag = false;\n    ASSERT_EQ(0, pthread_atfork(&SetPthreadFlag, nullptr, nullptr));\n    ASSERT_DEATH(_exit(1), \"\");\n    ASSERT_FALSE(pthread_flag);\n  }\n}\n\n#endif  // GTEST_HAS_CLONE && GTEST_HAS_PTHREAD\n\n// Tests that a method of another class can be used in a death test.\nTEST_F(TestForDeathTest, MethodOfAnotherClass) {\n  const MayDie x(true);\n  ASSERT_DEATH(x.MemberFunction(), \"MayDie\\\\:\\\\:MemberFunction\");\n}\n\n// Tests that a global function can be used in a death test.\nTEST_F(TestForDeathTest, GlobalFunction) {\n  EXPECT_DEATH(GlobalFunction(), \"GlobalFunction\");\n}\n\n// Tests that any value convertible to an RE works as a second\n// argument to EXPECT_DEATH.\nTEST_F(TestForDeathTest, AcceptsAnythingConvertibleToRE) {\n  static const char regex_c_str[] = \"GlobalFunction\";\n  EXPECT_DEATH(GlobalFunction(), regex_c_str);\n\n  const testing::internal::RE regex(regex_c_str);\n  EXPECT_DEATH(GlobalFunction(), regex);\n\n#if !GTEST_USES_PCRE\n\n  const ::std::string regex_std_str(regex_c_str);\n  EXPECT_DEATH(GlobalFunction(), regex_std_str);\n\n  // This one is tricky; a temporary pointer into another temporary.  Reference\n  // lifetime extension of the pointer is not sufficient.\n  EXPECT_DEATH(GlobalFunction(), ::std::string(regex_c_str).c_str());\n\n#endif  // !GTEST_USES_PCRE\n}\n\n// Tests that a non-void function can be used in a death test.\nTEST_F(TestForDeathTest, NonVoidFunction) {\n  ASSERT_DEATH(NonVoidFunction(), \"NonVoidFunction\");\n}\n\n// Tests that functions that take parameter(s) can be used in a death test.\nTEST_F(TestForDeathTest, FunctionWithParameter) {\n  EXPECT_DEATH(DieIf(true), \"DieIf\\\\(\\\\)\");\n  EXPECT_DEATH(DieIfLessThan(2, 3), \"DieIfLessThan\");\n}\n\n// Tests that ASSERT_DEATH can be used outside a TEST, TEST_F, or test fixture.\nTEST_F(TestForDeathTest, OutsideFixture) { DeathTestSubroutine(); }\n\n// Tests that death tests can be done inside a loop.\nTEST_F(TestForDeathTest, InsideLoop) {\n  for (int i = 0; i < 5; i++) {\n    EXPECT_DEATH(DieIfLessThan(-1, i), \"DieIfLessThan\") << \"where i == \" << i;\n  }\n}\n\n// Tests that a compound statement can be used in a death test.\nTEST_F(TestForDeathTest, CompoundStatement) {\n  EXPECT_DEATH(\n      {  // NOLINT\n        const int x = 2;\n        const int y = x + 1;\n        DieIfLessThan(x, y);\n      },\n      \"DieIfLessThan\");\n}\n\n// Tests that code that doesn't die causes a death test to fail.\nTEST_F(TestForDeathTest, DoesNotDie) {\n  EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(DieIf(false), \"DieIf\"), \"failed to die\");\n}\n\n// Tests that a death test fails when the error message isn't expected.\nTEST_F(TestForDeathTest, ErrorMessageMismatch) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_DEATH(DieIf(true), \"DieIfLessThan\")\n            << \"End of death test message.\";\n      },\n      \"died but not with expected error\");\n}\n\n// On exit, *aborted will be true if and only if the EXPECT_DEATH()\n// statement aborted the function.\nvoid ExpectDeathTestHelper(bool* aborted) {\n  *aborted = true;\n  EXPECT_DEATH(DieIf(false), \"DieIf\");  // This assertion should fail.\n  *aborted = false;\n}\n\n// Tests that EXPECT_DEATH doesn't abort the test on failure.\nTEST_F(TestForDeathTest, EXPECT_DEATH) {\n  bool aborted = true;\n  EXPECT_NONFATAL_FAILURE(ExpectDeathTestHelper(&aborted), \"failed to die\");\n  EXPECT_FALSE(aborted);\n}\n\n// Tests that ASSERT_DEATH does abort the test on failure.\nTEST_F(TestForDeathTest, ASSERT_DEATH) {\n  static bool aborted;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        aborted = true;\n        ASSERT_DEATH(DieIf(false), \"DieIf\");  // This assertion should fail.\n        aborted = false;\n      },\n      \"failed to die\");\n  EXPECT_TRUE(aborted);\n}\n\n// Tests that EXPECT_DEATH evaluates the arguments exactly once.\nTEST_F(TestForDeathTest, SingleEvaluation) {\n  int x = 3;\n  EXPECT_DEATH(DieIf((++x) == 4), \"DieIf\");\n\n  const char* regex = \"DieIf\";\n  const char* regex_save = regex;\n  EXPECT_DEATH(DieIfLessThan(3, 4), regex++);\n  EXPECT_EQ(regex_save + 1, regex);\n}\n\n// Tests that run-away death tests are reported as failures.\nTEST_F(TestForDeathTest, RunawayIsFailure) {\n  EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(static_cast<void>(0), \"Foo\"),\n                          \"failed to die.\");\n}\n\n// Tests that death tests report executing 'return' in the statement as\n// failure.\nTEST_F(TestForDeathTest, ReturnIsFailure) {\n  EXPECT_FATAL_FAILURE(ASSERT_DEATH(return, \"Bar\"),\n                       \"illegal return in test statement.\");\n}\n\n// Tests that EXPECT_DEBUG_DEATH works as expected, that is, you can stream a\n// message to it, and in debug mode it:\n// 1. Asserts on death.\n// 2. Has no side effect.\n//\n// And in opt mode, it:\n// 1.  Has side effects but does not assert.\nTEST_F(TestForDeathTest, TestExpectDebugDeath) {\n  int sideeffect = 0;\n\n  // Put the regex in a local variable to make sure we don't get an \"unused\"\n  // warning in opt mode.\n  const char* regex = \"death.*DieInDebugElse12\";\n\n  EXPECT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), regex)\n      << \"Must accept a streamed message\";\n\n#ifdef NDEBUG\n\n  // Checks that the assignment occurs in opt mode (sideeffect).\n  EXPECT_EQ(12, sideeffect);\n\n#else\n\n  // Checks that the assignment does not occur in dbg mode (no sideeffect).\n  EXPECT_EQ(0, sideeffect);\n\n#endif\n}\n\n#if GTEST_OS_WINDOWS\n\n// https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/crtsetreportmode\n// In debug mode, the calls to _CrtSetReportMode and _CrtSetReportFile enable\n// the dumping of assertions to stderr. Tests that EXPECT_DEATH works as\n// expected when in CRT debug mode (compiled with /MTd or /MDd, which defines\n// _DEBUG) the Windows CRT crashes the process with an assertion failure.\n// 1. Asserts on death.\n// 2. Has no side effect (doesn't pop up a window or wait for user input).\n#ifdef _DEBUG\nTEST_F(TestForDeathTest, CRTDebugDeath) {\n  EXPECT_DEATH(DieInCRTDebugElse12(nullptr), \"dup.* : Assertion failed\")\n      << \"Must accept a streamed message\";\n}\n#endif  // _DEBUG\n\n#endif  // GTEST_OS_WINDOWS\n\n// Tests that ASSERT_DEBUG_DEATH works as expected, that is, you can stream a\n// message to it, and in debug mode it:\n// 1. Asserts on death.\n// 2. Has no side effect.\n//\n// And in opt mode, it:\n// 1.  Has side effects but does not assert.\nTEST_F(TestForDeathTest, TestAssertDebugDeath) {\n  int sideeffect = 0;\n\n  ASSERT_DEBUG_DEATH(DieInDebugElse12(&sideeffect), \"death.*DieInDebugElse12\")\n      << \"Must accept a streamed message\";\n\n#ifdef NDEBUG\n\n  // Checks that the assignment occurs in opt mode (sideeffect).\n  EXPECT_EQ(12, sideeffect);\n\n#else\n\n  // Checks that the assignment does not occur in dbg mode (no sideeffect).\n  EXPECT_EQ(0, sideeffect);\n\n#endif\n}\n\n#ifndef NDEBUG\n\nvoid ExpectDebugDeathHelper(bool* aborted) {\n  *aborted = true;\n  EXPECT_DEBUG_DEATH(return, \"\") << \"This is expected to fail.\";\n  *aborted = false;\n}\n\n#if GTEST_OS_WINDOWS\nTEST(PopUpDeathTest, DoesNotShowPopUpOnAbort) {\n  printf(\n      \"This test should be considered failing if it shows \"\n      \"any pop-up dialogs.\\n\");\n  fflush(stdout);\n\n  EXPECT_DEATH(\n      {\n        GTEST_FLAG_SET(catch_exceptions, false);\n        abort();\n      },\n      \"\");\n}\n#endif  // GTEST_OS_WINDOWS\n\n// Tests that EXPECT_DEBUG_DEATH in debug mode does not abort\n// the function.\nTEST_F(TestForDeathTest, ExpectDebugDeathDoesNotAbort) {\n  bool aborted = true;\n  EXPECT_NONFATAL_FAILURE(ExpectDebugDeathHelper(&aborted), \"\");\n  EXPECT_FALSE(aborted);\n}\n\nvoid AssertDebugDeathHelper(bool* aborted) {\n  *aborted = true;\n  GTEST_LOG_(INFO) << \"Before ASSERT_DEBUG_DEATH\";\n  ASSERT_DEBUG_DEATH(GTEST_LOG_(INFO) << \"In ASSERT_DEBUG_DEATH\"; return, \"\")\n      << \"This is expected to fail.\";\n  GTEST_LOG_(INFO) << \"After ASSERT_DEBUG_DEATH\";\n  *aborted = false;\n}\n\n// Tests that ASSERT_DEBUG_DEATH in debug mode aborts the function on\n// failure.\nTEST_F(TestForDeathTest, AssertDebugDeathAborts) {\n  static bool aborted;\n  aborted = false;\n  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), \"\");\n  EXPECT_TRUE(aborted);\n}\n\nTEST_F(TestForDeathTest, AssertDebugDeathAborts2) {\n  static bool aborted;\n  aborted = false;\n  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), \"\");\n  EXPECT_TRUE(aborted);\n}\n\nTEST_F(TestForDeathTest, AssertDebugDeathAborts3) {\n  static bool aborted;\n  aborted = false;\n  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), \"\");\n  EXPECT_TRUE(aborted);\n}\n\nTEST_F(TestForDeathTest, AssertDebugDeathAborts4) {\n  static bool aborted;\n  aborted = false;\n  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), \"\");\n  EXPECT_TRUE(aborted);\n}\n\nTEST_F(TestForDeathTest, AssertDebugDeathAborts5) {\n  static bool aborted;\n  aborted = false;\n  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), \"\");\n  EXPECT_TRUE(aborted);\n}\n\nTEST_F(TestForDeathTest, AssertDebugDeathAborts6) {\n  static bool aborted;\n  aborted = false;\n  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), \"\");\n  EXPECT_TRUE(aborted);\n}\n\nTEST_F(TestForDeathTest, AssertDebugDeathAborts7) {\n  static bool aborted;\n  aborted = false;\n  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), \"\");\n  EXPECT_TRUE(aborted);\n}\n\nTEST_F(TestForDeathTest, AssertDebugDeathAborts8) {\n  static bool aborted;\n  aborted = false;\n  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), \"\");\n  EXPECT_TRUE(aborted);\n}\n\nTEST_F(TestForDeathTest, AssertDebugDeathAborts9) {\n  static bool aborted;\n  aborted = false;\n  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), \"\");\n  EXPECT_TRUE(aborted);\n}\n\nTEST_F(TestForDeathTest, AssertDebugDeathAborts10) {\n  static bool aborted;\n  aborted = false;\n  EXPECT_FATAL_FAILURE(AssertDebugDeathHelper(&aborted), \"\");\n  EXPECT_TRUE(aborted);\n}\n\n#endif  // _NDEBUG\n\n// Tests the *_EXIT family of macros, using a variety of predicates.\nstatic void TestExitMacros() {\n  EXPECT_EXIT(_exit(1), testing::ExitedWithCode(1), \"\");\n  ASSERT_EXIT(_exit(42), testing::ExitedWithCode(42), \"\");\n\n#if GTEST_OS_WINDOWS\n\n  // Of all signals effects on the process exit code, only those of SIGABRT\n  // are documented on Windows.\n  // See https://msdn.microsoft.com/en-us/query-bi/m/dwwzkt4c.\n  EXPECT_EXIT(raise(SIGABRT), testing::ExitedWithCode(3), \"\") << \"b_ar\";\n\n#elif !GTEST_OS_FUCHSIA\n\n  // Fuchsia has no unix signals.\n  EXPECT_EXIT(raise(SIGKILL), testing::KilledBySignal(SIGKILL), \"\") << \"foo\";\n  ASSERT_EXIT(raise(SIGUSR2), testing::KilledBySignal(SIGUSR2), \"\") << \"bar\";\n\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_EXIT(_exit(0), testing::KilledBySignal(SIGSEGV), \"\")\n            << \"This failure is expected, too.\";\n      },\n      \"This failure is expected, too.\");\n\n#endif  // GTEST_OS_WINDOWS\n\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_EXIT(raise(SIGSEGV), testing::ExitedWithCode(0), \"\")\n            << \"This failure is expected.\";\n      },\n      \"This failure is expected.\");\n}\n\nTEST_F(TestForDeathTest, ExitMacros) { TestExitMacros(); }\n\nTEST_F(TestForDeathTest, ExitMacrosUsingFork) {\n  GTEST_FLAG_SET(death_test_use_fork, true);\n  TestExitMacros();\n}\n\nTEST_F(TestForDeathTest, InvalidStyle) {\n  GTEST_FLAG_SET(death_test_style, \"rococo\");\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_DEATH(_exit(0), \"\") << \"This failure is expected.\";\n      },\n      \"This failure is expected.\");\n}\n\nTEST_F(TestForDeathTest, DeathTestFailedOutput) {\n  GTEST_FLAG_SET(death_test_style, \"fast\");\n  EXPECT_NONFATAL_FAILURE(\n      EXPECT_DEATH(DieWithMessage(\"death\\n\"), \"expected message\"),\n      \"Actual msg:\\n\"\n      \"[  DEATH   ] death\\n\");\n}\n\nTEST_F(TestForDeathTest, DeathTestUnexpectedReturnOutput) {\n  GTEST_FLAG_SET(death_test_style, \"fast\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(\n                              {\n                                fprintf(stderr, \"returning\\n\");\n                                fflush(stderr);\n                                return;\n                              },\n                              \"\"),\n                          \"    Result: illegal return in test statement.\\n\"\n                          \" Error msg:\\n\"\n                          \"[  DEATH   ] returning\\n\");\n}\n\nTEST_F(TestForDeathTest, DeathTestBadExitCodeOutput) {\n  GTEST_FLAG_SET(death_test_style, \"fast\");\n  EXPECT_NONFATAL_FAILURE(\n      EXPECT_EXIT(DieWithMessage(\"exiting with rc 1\\n\"),\n                  testing::ExitedWithCode(3), \"expected message\"),\n      \"    Result: died but not with expected exit code:\\n\"\n      \"            Exited with exit status 1\\n\"\n      \"Actual msg:\\n\"\n      \"[  DEATH   ] exiting with rc 1\\n\");\n}\n\nTEST_F(TestForDeathTest, DeathTestMultiLineMatchFail) {\n  GTEST_FLAG_SET(death_test_style, \"fast\");\n  EXPECT_NONFATAL_FAILURE(\n      EXPECT_DEATH(DieWithMessage(\"line 1\\nline 2\\nline 3\\n\"),\n                   \"line 1\\nxyz\\nline 3\\n\"),\n      \"Actual msg:\\n\"\n      \"[  DEATH   ] line 1\\n\"\n      \"[  DEATH   ] line 2\\n\"\n      \"[  DEATH   ] line 3\\n\");\n}\n\nTEST_F(TestForDeathTest, DeathTestMultiLineMatchPass) {\n  GTEST_FLAG_SET(death_test_style, \"fast\");\n  EXPECT_DEATH(DieWithMessage(\"line 1\\nline 2\\nline 3\\n\"),\n               \"line 1\\nline 2\\nline 3\\n\");\n}\n\n// A DeathTestFactory that returns MockDeathTests.\nclass MockDeathTestFactory : public DeathTestFactory {\n public:\n  MockDeathTestFactory();\n  bool Create(const char* statement,\n              testing::Matcher<const std::string&> matcher, const char* file,\n              int line, DeathTest** test) override;\n\n  // Sets the parameters for subsequent calls to Create.\n  void SetParameters(bool create, DeathTest::TestRole role, int status,\n                     bool passed);\n\n  // Accessors.\n  int AssumeRoleCalls() const { return assume_role_calls_; }\n  int WaitCalls() const { return wait_calls_; }\n  size_t PassedCalls() const { return passed_args_.size(); }\n  bool PassedArgument(int n) const {\n    return passed_args_[static_cast<size_t>(n)];\n  }\n  size_t AbortCalls() const { return abort_args_.size(); }\n  DeathTest::AbortReason AbortArgument(int n) const {\n    return abort_args_[static_cast<size_t>(n)];\n  }\n  bool TestDeleted() const { return test_deleted_; }\n\n private:\n  friend class MockDeathTest;\n  // If true, Create will return a MockDeathTest; otherwise it returns\n  // NULL.\n  bool create_;\n  // The value a MockDeathTest will return from its AssumeRole method.\n  DeathTest::TestRole role_;\n  // The value a MockDeathTest will return from its Wait method.\n  int status_;\n  // The value a MockDeathTest will return from its Passed method.\n  bool passed_;\n\n  // Number of times AssumeRole was called.\n  int assume_role_calls_;\n  // Number of times Wait was called.\n  int wait_calls_;\n  // The arguments to the calls to Passed since the last call to\n  // SetParameters.\n  std::vector<bool> passed_args_;\n  // The arguments to the calls to Abort since the last call to\n  // SetParameters.\n  std::vector<DeathTest::AbortReason> abort_args_;\n  // True if the last MockDeathTest returned by Create has been\n  // deleted.\n  bool test_deleted_;\n};\n\n// A DeathTest implementation useful in testing.  It returns values set\n// at its creation from its various inherited DeathTest methods, and\n// reports calls to those methods to its parent MockDeathTestFactory\n// object.\nclass MockDeathTest : public DeathTest {\n public:\n  MockDeathTest(MockDeathTestFactory* parent, TestRole role, int status,\n                bool passed)\n      : parent_(parent), role_(role), status_(status), passed_(passed) {}\n  ~MockDeathTest() override { parent_->test_deleted_ = true; }\n  TestRole AssumeRole() override {\n    ++parent_->assume_role_calls_;\n    return role_;\n  }\n  int Wait() override {\n    ++parent_->wait_calls_;\n    return status_;\n  }\n  bool Passed(bool exit_status_ok) override {\n    parent_->passed_args_.push_back(exit_status_ok);\n    return passed_;\n  }\n  void Abort(AbortReason reason) override {\n    parent_->abort_args_.push_back(reason);\n  }\n\n private:\n  MockDeathTestFactory* const parent_;\n  const TestRole role_;\n  const int status_;\n  const bool passed_;\n};\n\n// MockDeathTestFactory constructor.\nMockDeathTestFactory::MockDeathTestFactory()\n    : create_(true),\n      role_(DeathTest::OVERSEE_TEST),\n      status_(0),\n      passed_(true),\n      assume_role_calls_(0),\n      wait_calls_(0),\n      passed_args_(),\n      abort_args_() {}\n\n// Sets the parameters for subsequent calls to Create.\nvoid MockDeathTestFactory::SetParameters(bool create, DeathTest::TestRole role,\n                                         int status, bool passed) {\n  create_ = create;\n  role_ = role;\n  status_ = status;\n  passed_ = passed;\n\n  assume_role_calls_ = 0;\n  wait_calls_ = 0;\n  passed_args_.clear();\n  abort_args_.clear();\n}\n\n// Sets test to NULL (if create_ is false) or to the address of a new\n// MockDeathTest object with parameters taken from the last call\n// to SetParameters (if create_ is true).  Always returns true.\nbool MockDeathTestFactory::Create(\n    const char* /*statement*/, testing::Matcher<const std::string&> /*matcher*/,\n    const char* /*file*/, int /*line*/, DeathTest** test) {\n  test_deleted_ = false;\n  if (create_) {\n    *test = new MockDeathTest(this, role_, status_, passed_);\n  } else {\n    *test = nullptr;\n  }\n  return true;\n}\n\n// A test fixture for testing the logic of the GTEST_DEATH_TEST_ macro.\n// It installs a MockDeathTestFactory that is used for the duration\n// of the test case.\nclass MacroLogicDeathTest : public testing::Test {\n protected:\n  static testing::internal::ReplaceDeathTestFactory* replacer_;\n  static MockDeathTestFactory* factory_;\n\n  static void SetUpTestSuite() {\n    factory_ = new MockDeathTestFactory;\n    replacer_ = new testing::internal::ReplaceDeathTestFactory(factory_);\n  }\n\n  static void TearDownTestSuite() {\n    delete replacer_;\n    replacer_ = nullptr;\n    delete factory_;\n    factory_ = nullptr;\n  }\n\n  // Runs a death test that breaks the rules by returning.  Such a death\n  // test cannot be run directly from a test routine that uses a\n  // MockDeathTest, or the remainder of the routine will not be executed.\n  static void RunReturningDeathTest(bool* flag) {\n    ASSERT_DEATH(\n        {  // NOLINT\n          *flag = true;\n          return;\n        },\n        \"\");\n  }\n};\n\ntesting::internal::ReplaceDeathTestFactory* MacroLogicDeathTest::replacer_ =\n    nullptr;\nMockDeathTestFactory* MacroLogicDeathTest::factory_ = nullptr;\n\n// Test that nothing happens when the factory doesn't return a DeathTest:\nTEST_F(MacroLogicDeathTest, NothingHappens) {\n  bool flag = false;\n  factory_->SetParameters(false, DeathTest::OVERSEE_TEST, 0, true);\n  EXPECT_DEATH(flag = true, \"\");\n  EXPECT_FALSE(flag);\n  EXPECT_EQ(0, factory_->AssumeRoleCalls());\n  EXPECT_EQ(0, factory_->WaitCalls());\n  EXPECT_EQ(0U, factory_->PassedCalls());\n  EXPECT_EQ(0U, factory_->AbortCalls());\n  EXPECT_FALSE(factory_->TestDeleted());\n}\n\n// Test that the parent process doesn't run the death test code,\n// and that the Passed method returns false when the (simulated)\n// child process exits with status 0:\nTEST_F(MacroLogicDeathTest, ChildExitsSuccessfully) {\n  bool flag = false;\n  factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 0, true);\n  EXPECT_DEATH(flag = true, \"\");\n  EXPECT_FALSE(flag);\n  EXPECT_EQ(1, factory_->AssumeRoleCalls());\n  EXPECT_EQ(1, factory_->WaitCalls());\n  ASSERT_EQ(1U, factory_->PassedCalls());\n  EXPECT_FALSE(factory_->PassedArgument(0));\n  EXPECT_EQ(0U, factory_->AbortCalls());\n  EXPECT_TRUE(factory_->TestDeleted());\n}\n\n// Tests that the Passed method was given the argument \"true\" when\n// the (simulated) child process exits with status 1:\nTEST_F(MacroLogicDeathTest, ChildExitsUnsuccessfully) {\n  bool flag = false;\n  factory_->SetParameters(true, DeathTest::OVERSEE_TEST, 1, true);\n  EXPECT_DEATH(flag = true, \"\");\n  EXPECT_FALSE(flag);\n  EXPECT_EQ(1, factory_->AssumeRoleCalls());\n  EXPECT_EQ(1, factory_->WaitCalls());\n  ASSERT_EQ(1U, factory_->PassedCalls());\n  EXPECT_TRUE(factory_->PassedArgument(0));\n  EXPECT_EQ(0U, factory_->AbortCalls());\n  EXPECT_TRUE(factory_->TestDeleted());\n}\n\n// Tests that the (simulated) child process executes the death test\n// code, and is aborted with the correct AbortReason if it\n// executes a return statement.\nTEST_F(MacroLogicDeathTest, ChildPerformsReturn) {\n  bool flag = false;\n  factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);\n  RunReturningDeathTest(&flag);\n  EXPECT_TRUE(flag);\n  EXPECT_EQ(1, factory_->AssumeRoleCalls());\n  EXPECT_EQ(0, factory_->WaitCalls());\n  EXPECT_EQ(0U, factory_->PassedCalls());\n  EXPECT_EQ(1U, factory_->AbortCalls());\n  EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,\n            factory_->AbortArgument(0));\n  EXPECT_TRUE(factory_->TestDeleted());\n}\n\n// Tests that the (simulated) child process is aborted with the\n// correct AbortReason if it does not die.\nTEST_F(MacroLogicDeathTest, ChildDoesNotDie) {\n  bool flag = false;\n  factory_->SetParameters(true, DeathTest::EXECUTE_TEST, 0, true);\n  EXPECT_DEATH(flag = true, \"\");\n  EXPECT_TRUE(flag);\n  EXPECT_EQ(1, factory_->AssumeRoleCalls());\n  EXPECT_EQ(0, factory_->WaitCalls());\n  EXPECT_EQ(0U, factory_->PassedCalls());\n  // This time there are two calls to Abort: one since the test didn't\n  // die, and another from the ReturnSentinel when it's destroyed.  The\n  // sentinel normally isn't destroyed if a test doesn't die, since\n  // _exit(2) is called in that case by ForkingDeathTest, but not by\n  // our MockDeathTest.\n  ASSERT_EQ(2U, factory_->AbortCalls());\n  EXPECT_EQ(DeathTest::TEST_DID_NOT_DIE, factory_->AbortArgument(0));\n  EXPECT_EQ(DeathTest::TEST_ENCOUNTERED_RETURN_STATEMENT,\n            factory_->AbortArgument(1));\n  EXPECT_TRUE(factory_->TestDeleted());\n}\n\n// Tests that a successful death test does not register a successful\n// test part.\nTEST(SuccessRegistrationDeathTest, NoSuccessPart) {\n  EXPECT_DEATH(_exit(1), \"\");\n  EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());\n}\n\nTEST(StreamingAssertionsDeathTest, DeathTest) {\n  EXPECT_DEATH(_exit(1), \"\") << \"unexpected failure\";\n  ASSERT_DEATH(_exit(1), \"\") << \"unexpected failure\";\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_DEATH(_exit(0), \"\") << \"expected failure\";\n      },\n      \"expected failure\");\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_DEATH(_exit(0), \"\") << \"expected failure\";\n      },\n      \"expected failure\");\n}\n\n// Tests that GetLastErrnoDescription returns an empty string when the\n// last error is 0 and non-empty string when it is non-zero.\nTEST(GetLastErrnoDescription, GetLastErrnoDescriptionWorks) {\n  errno = ENOENT;\n  EXPECT_STRNE(\"\", GetLastErrnoDescription().c_str());\n  errno = 0;\n  EXPECT_STREQ(\"\", GetLastErrnoDescription().c_str());\n}\n\n#if GTEST_OS_WINDOWS\nTEST(AutoHandleTest, AutoHandleWorks) {\n  HANDLE handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);\n  ASSERT_NE(INVALID_HANDLE_VALUE, handle);\n\n  // Tests that the AutoHandle is correctly initialized with a handle.\n  testing::internal::AutoHandle auto_handle(handle);\n  EXPECT_EQ(handle, auto_handle.Get());\n\n  // Tests that Reset assigns INVALID_HANDLE_VALUE.\n  // Note that this cannot verify whether the original handle is closed.\n  auto_handle.Reset();\n  EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle.Get());\n\n  // Tests that Reset assigns the new handle.\n  // Note that this cannot verify whether the original handle is closed.\n  handle = ::CreateEvent(NULL, FALSE, FALSE, NULL);\n  ASSERT_NE(INVALID_HANDLE_VALUE, handle);\n  auto_handle.Reset(handle);\n  EXPECT_EQ(handle, auto_handle.Get());\n\n  // Tests that AutoHandle contains INVALID_HANDLE_VALUE by default.\n  testing::internal::AutoHandle auto_handle2;\n  EXPECT_EQ(INVALID_HANDLE_VALUE, auto_handle2.Get());\n}\n#endif  // GTEST_OS_WINDOWS\n\n#if GTEST_OS_WINDOWS\ntypedef unsigned __int64 BiggestParsable;\ntypedef signed __int64 BiggestSignedParsable;\n#else\ntypedef unsigned long long BiggestParsable;\ntypedef signed long long BiggestSignedParsable;\n#endif  // GTEST_OS_WINDOWS\n\n// We cannot use std::numeric_limits<T>::max() as it clashes with the\n// max() macro defined by <windows.h>.\nconst BiggestParsable kBiggestParsableMax = ULLONG_MAX;\nconst BiggestSignedParsable kBiggestSignedParsableMax = LLONG_MAX;\n\nTEST(ParseNaturalNumberTest, RejectsInvalidFormat) {\n  BiggestParsable result = 0;\n\n  // Rejects non-numbers.\n  EXPECT_FALSE(ParseNaturalNumber(\"non-number string\", &result));\n\n  // Rejects numbers with whitespace prefix.\n  EXPECT_FALSE(ParseNaturalNumber(\" 123\", &result));\n\n  // Rejects negative numbers.\n  EXPECT_FALSE(ParseNaturalNumber(\"-123\", &result));\n\n  // Rejects numbers starting with a plus sign.\n  EXPECT_FALSE(ParseNaturalNumber(\"+123\", &result));\n  errno = 0;\n}\n\nTEST(ParseNaturalNumberTest, RejectsOverflownNumbers) {\n  BiggestParsable result = 0;\n\n  EXPECT_FALSE(ParseNaturalNumber(\"99999999999999999999999\", &result));\n\n  signed char char_result = 0;\n  EXPECT_FALSE(ParseNaturalNumber(\"200\", &char_result));\n  errno = 0;\n}\n\nTEST(ParseNaturalNumberTest, AcceptsValidNumbers) {\n  BiggestParsable result = 0;\n\n  result = 0;\n  ASSERT_TRUE(ParseNaturalNumber(\"123\", &result));\n  EXPECT_EQ(123U, result);\n\n  // Check 0 as an edge case.\n  result = 1;\n  ASSERT_TRUE(ParseNaturalNumber(\"0\", &result));\n  EXPECT_EQ(0U, result);\n\n  result = 1;\n  ASSERT_TRUE(ParseNaturalNumber(\"00000\", &result));\n  EXPECT_EQ(0U, result);\n}\n\nTEST(ParseNaturalNumberTest, AcceptsTypeLimits) {\n  Message msg;\n  msg << kBiggestParsableMax;\n\n  BiggestParsable result = 0;\n  EXPECT_TRUE(ParseNaturalNumber(msg.GetString(), &result));\n  EXPECT_EQ(kBiggestParsableMax, result);\n\n  Message msg2;\n  msg2 << kBiggestSignedParsableMax;\n\n  BiggestSignedParsable signed_result = 0;\n  EXPECT_TRUE(ParseNaturalNumber(msg2.GetString(), &signed_result));\n  EXPECT_EQ(kBiggestSignedParsableMax, signed_result);\n\n  Message msg3;\n  msg3 << INT_MAX;\n\n  int int_result = 0;\n  EXPECT_TRUE(ParseNaturalNumber(msg3.GetString(), &int_result));\n  EXPECT_EQ(INT_MAX, int_result);\n\n  Message msg4;\n  msg4 << UINT_MAX;\n\n  unsigned int uint_result = 0;\n  EXPECT_TRUE(ParseNaturalNumber(msg4.GetString(), &uint_result));\n  EXPECT_EQ(UINT_MAX, uint_result);\n}\n\nTEST(ParseNaturalNumberTest, WorksForShorterIntegers) {\n  short short_result = 0;\n  ASSERT_TRUE(ParseNaturalNumber(\"123\", &short_result));\n  EXPECT_EQ(123, short_result);\n\n  signed char char_result = 0;\n  ASSERT_TRUE(ParseNaturalNumber(\"123\", &char_result));\n  EXPECT_EQ(123, char_result);\n}\n\n#if GTEST_OS_WINDOWS\nTEST(EnvironmentTest, HandleFitsIntoSizeT) {\n  ASSERT_TRUE(sizeof(HANDLE) <= sizeof(size_t));\n}\n#endif  // GTEST_OS_WINDOWS\n\n// Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED trigger\n// failures when death tests are available on the system.\nTEST(ConditionalDeathMacrosDeathTest, ExpectsDeathWhenDeathTestsAvailable) {\n  EXPECT_DEATH_IF_SUPPORTED(DieInside(\"CondDeathTestExpectMacro\"),\n                            \"death inside CondDeathTestExpectMacro\");\n  ASSERT_DEATH_IF_SUPPORTED(DieInside(\"CondDeathTestAssertMacro\"),\n                            \"death inside CondDeathTestAssertMacro\");\n\n  // Empty statement will not crash, which must trigger a failure.\n  EXPECT_NONFATAL_FAILURE(EXPECT_DEATH_IF_SUPPORTED(;, \"\"), \"\");\n  EXPECT_FATAL_FAILURE(ASSERT_DEATH_IF_SUPPORTED(;, \"\"), \"\");\n}\n\nTEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInFastStyle) {\n  GTEST_FLAG_SET(death_test_style, \"fast\");\n  EXPECT_FALSE(InDeathTestChild());\n  EXPECT_DEATH(\n      {\n        fprintf(stderr, InDeathTestChild() ? \"Inside\" : \"Outside\");\n        fflush(stderr);\n        _exit(1);\n      },\n      \"Inside\");\n}\n\nTEST(InDeathTestChildDeathTest, ReportsDeathTestCorrectlyInThreadSafeStyle) {\n  GTEST_FLAG_SET(death_test_style, \"threadsafe\");\n  EXPECT_FALSE(InDeathTestChild());\n  EXPECT_DEATH(\n      {\n        fprintf(stderr, InDeathTestChild() ? \"Inside\" : \"Outside\");\n        fflush(stderr);\n        _exit(1);\n      },\n      \"Inside\");\n}\n\nvoid DieWithMessage(const char* message) {\n  fputs(message, stderr);\n  fflush(stderr);  // Make sure the text is printed before the process exits.\n  _exit(1);\n}\n\nTEST(MatcherDeathTest, DoesNotBreakBareRegexMatching) {\n  // googletest tests this, of course; here we ensure that including googlemock\n  // has not broken it.\n#if GTEST_USES_POSIX_RE\n  EXPECT_DEATH(DieWithMessage(\"O, I die, Horatio.\"), \"I d[aeiou]e\");\n#else\n  EXPECT_DEATH(DieWithMessage(\"O, I die, Horatio.\"), \"I di?e\");\n#endif\n}\n\nTEST(MatcherDeathTest, MonomorphicMatcherMatches) {\n  EXPECT_DEATH(DieWithMessage(\"Behind O, I am slain!\"),\n               Matcher<const std::string&>(ContainsRegex(\"I am slain\")));\n}\n\nTEST(MatcherDeathTest, MonomorphicMatcherDoesNotMatch) {\n  EXPECT_NONFATAL_FAILURE(\n      EXPECT_DEATH(\n          DieWithMessage(\"Behind O, I am slain!\"),\n          Matcher<const std::string&>(ContainsRegex(\"Ow, I am slain\"))),\n      \"Expected: contains regular expression \\\"Ow, I am slain\\\"\");\n}\n\nTEST(MatcherDeathTest, PolymorphicMatcherMatches) {\n  EXPECT_DEATH(DieWithMessage(\"The rest is silence.\"),\n               ContainsRegex(\"rest is silence\"));\n}\n\nTEST(MatcherDeathTest, PolymorphicMatcherDoesNotMatch) {\n  EXPECT_NONFATAL_FAILURE(\n      EXPECT_DEATH(DieWithMessage(\"The rest is silence.\"),\n                   ContainsRegex(\"rest is science\")),\n      \"Expected: contains regular expression \\\"rest is science\\\"\");\n}\n\n}  // namespace\n\n#else  // !GTEST_HAS_DEATH_TEST follows\n\nnamespace {\n\nusing testing::internal::CaptureStderr;\nusing testing::internal::GetCapturedStderr;\n\n// Tests that EXPECT_DEATH_IF_SUPPORTED/ASSERT_DEATH_IF_SUPPORTED are still\n// defined but do not trigger failures when death tests are not available on\n// the system.\nTEST(ConditionalDeathMacrosTest, WarnsWhenDeathTestsNotAvailable) {\n  // Empty statement will not crash, but that should not trigger a failure\n  // when death tests are not supported.\n  CaptureStderr();\n  EXPECT_DEATH_IF_SUPPORTED(;, \"\");\n  std::string output = GetCapturedStderr();\n  ASSERT_TRUE(NULL != strstr(output.c_str(),\n                             \"Death tests are not supported on this platform\"));\n  ASSERT_TRUE(NULL != strstr(output.c_str(), \";\"));\n\n  // The streamed message should not be printed as there is no test failure.\n  CaptureStderr();\n  EXPECT_DEATH_IF_SUPPORTED(;, \"\") << \"streamed message\";\n  output = GetCapturedStderr();\n  ASSERT_TRUE(NULL == strstr(output.c_str(), \"streamed message\"));\n\n  CaptureStderr();\n  ASSERT_DEATH_IF_SUPPORTED(;, \"\");  // NOLINT\n  output = GetCapturedStderr();\n  ASSERT_TRUE(NULL != strstr(output.c_str(),\n                             \"Death tests are not supported on this platform\"));\n  ASSERT_TRUE(NULL != strstr(output.c_str(), \";\"));\n\n  CaptureStderr();\n  ASSERT_DEATH_IF_SUPPORTED(;, \"\") << \"streamed message\";  // NOLINT\n  output = GetCapturedStderr();\n  ASSERT_TRUE(NULL == strstr(output.c_str(), \"streamed message\"));\n}\n\nvoid FuncWithAssert(int* n) {\n  ASSERT_DEATH_IF_SUPPORTED(return;, \"\");\n  (*n)++;\n}\n\n// Tests that ASSERT_DEATH_IF_SUPPORTED does not return from the current\n// function (as ASSERT_DEATH does) if death tests are not supported.\nTEST(ConditionalDeathMacrosTest, AssertDeatDoesNotReturnhIfUnsupported) {\n  int n = 0;\n  FuncWithAssert(&n);\n  EXPECT_EQ(1, n);\n}\n\n}  // namespace\n\n#endif  // !GTEST_HAS_DEATH_TEST\n\nnamespace {\n\n// The following code intentionally tests a suboptimal syntax.\n#ifdef __GNUC__\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wdangling-else\"\n#pragma GCC diagnostic ignored \"-Wempty-body\"\n#pragma GCC diagnostic ignored \"-Wpragmas\"\n#endif\n// Tests that the death test macros expand to code which may or may not\n// be followed by operator<<, and that in either case the complete text\n// comprises only a single C++ statement.\n//\n// The syntax should work whether death tests are available or not.\nTEST(ConditionalDeathMacrosSyntaxDeathTest, SingleStatement) {\n  if (AlwaysFalse())\n    // This would fail if executed; this is a compilation test only\n    ASSERT_DEATH_IF_SUPPORTED(return, \"\");\n\n  if (AlwaysTrue())\n    EXPECT_DEATH_IF_SUPPORTED(_exit(1), \"\");\n  else\n    // This empty \"else\" branch is meant to ensure that EXPECT_DEATH\n    // doesn't expand into an \"if\" statement without an \"else\"\n    ;  // NOLINT\n\n  if (AlwaysFalse()) ASSERT_DEATH_IF_SUPPORTED(return, \"\") << \"did not die\";\n\n  if (AlwaysFalse())\n    ;  // NOLINT\n  else\n    EXPECT_DEATH_IF_SUPPORTED(_exit(1), \"\") << 1 << 2 << 3;\n}\n#ifdef __GNUC__\n#pragma GCC diagnostic pop\n#endif\n\n// Tests that conditional death test macros expand to code which interacts\n// well with switch statements.\nTEST(ConditionalDeathMacrosSyntaxDeathTest, SwitchStatement) {\n  // Microsoft compiler usually complains about switch statements without\n  // case labels. We suppress that warning for this test.\n  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4065)\n\n  switch (0)\n  default:\n    ASSERT_DEATH_IF_SUPPORTED(_exit(1), \"\") << \"exit in default switch handler\";\n\n  switch (0)\n  case 0:\n    EXPECT_DEATH_IF_SUPPORTED(_exit(1), \"\") << \"exit in switch case\";\n\n  GTEST_DISABLE_MSC_WARNINGS_POP_()\n}\n\n// Tests that a test case whose name ends with \"DeathTest\" works fine\n// on Windows.\nTEST(NotADeathTest, Test) { SUCCEED(); }\n\n}  // namespace\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-death-test_ex_test.cc",
    "content": "// Copyright 2010, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// Tests that verify interaction of exceptions and death tests.\n\n#include \"gtest/gtest-death-test.h\"\n#include \"gtest/gtest.h\"\n\n#if GTEST_HAS_DEATH_TEST\n\n#if GTEST_HAS_SEH\n#include <windows.h>  // For RaiseException().\n#endif\n\n#include \"gtest/gtest-spi.h\"\n\n#if GTEST_HAS_EXCEPTIONS\n\n#include <exception>  // For std::exception.\n\n// Tests that death tests report thrown exceptions as failures and that the\n// exceptions do not escape death test macros.\nTEST(CxxExceptionDeathTest, ExceptionIsFailure) {\n  try {\n    EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw 1, \"\"), \"threw an exception\");\n  } catch (...) {  // NOLINT\n    FAIL() << \"An exception escaped a death test macro invocation \"\n           << \"with catch_exceptions \"\n           << (GTEST_FLAG_GET(catch_exceptions) ? \"enabled\" : \"disabled\");\n  }\n}\n\nclass TestException : public std::exception {\n public:\n  const char* what() const noexcept override { return \"exceptional message\"; }\n};\n\nTEST(CxxExceptionDeathTest, PrintsMessageForStdExceptions) {\n  // Verifies that the exception message is quoted in the failure text.\n  EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), \"\"),\n                          \"exceptional message\");\n  // Verifies that the location is mentioned in the failure text.\n  EXPECT_NONFATAL_FAILURE(EXPECT_DEATH(throw TestException(), \"\"), __FILE__);\n}\n#endif  // GTEST_HAS_EXCEPTIONS\n\n#if GTEST_HAS_SEH\n// Tests that enabling interception of SEH exceptions with the\n// catch_exceptions flag does not interfere with SEH exceptions being\n// treated as death by death tests.\nTEST(SehExceptionDeasTest, CatchExceptionsDoesNotInterfere) {\n  EXPECT_DEATH(RaiseException(42, 0x0, 0, NULL), \"\")\n      << \"with catch_exceptions \"\n      << (GTEST_FLAG_GET(catch_exceptions) ? \"enabled\" : \"disabled\");\n}\n#endif\n\n#endif  // GTEST_HAS_DEATH_TEST\n\nint main(int argc, char** argv) {\n  testing::InitGoogleTest(&argc, argv);\n  GTEST_FLAG_SET(catch_exceptions, GTEST_ENABLE_CATCH_EXCEPTIONS_ != 0);\n  return RUN_ALL_TESTS();\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-env-var-test.py",
    "content": "#!/usr/bin/env python\n#\n# Copyright 2008, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Verifies that Google Test correctly parses environment variables.\"\"\"\n\nimport os\nfrom googletest.test import gtest_test_utils\n\n\nIS_WINDOWS = os.name == 'nt'\nIS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux'\n\nCOMMAND = gtest_test_utils.GetTestExecutablePath('googletest-env-var-test_')\n\nenviron = os.environ.copy()\n\n\ndef AssertEq(expected, actual):\n  if expected != actual:\n    print('Expected: %s' % (expected,))\n    print('  Actual: %s' % (actual,))\n    raise AssertionError\n\n\ndef SetEnvVar(env_var, value):\n  \"\"\"Sets the env variable to 'value'; unsets it when 'value' is None.\"\"\"\n\n  if value is not None:\n    environ[env_var] = value\n  elif env_var in environ:\n    del environ[env_var]\n\n\ndef GetFlag(flag):\n  \"\"\"Runs googletest-env-var-test_ and returns its output.\"\"\"\n\n  args = [COMMAND]\n  if flag is not None:\n    args += [flag]\n  return gtest_test_utils.Subprocess(args, env=environ).output\n\n\ndef TestFlag(flag, test_val, default_val):\n  \"\"\"Verifies that the given flag is affected by the corresponding env var.\"\"\"\n\n  env_var = 'GTEST_' + flag.upper()\n  SetEnvVar(env_var, test_val)\n  AssertEq(test_val, GetFlag(flag))\n  SetEnvVar(env_var, None)\n  AssertEq(default_val, GetFlag(flag))\n\n\nclass GTestEnvVarTest(gtest_test_utils.TestCase):\n\n  def testEnvVarAffectsFlag(self):\n    \"\"\"Tests that environment variable should affect the corresponding flag.\"\"\"\n\n    TestFlag('break_on_failure', '1', '0')\n    TestFlag('color', 'yes', 'auto')\n    SetEnvVar('TESTBRIDGE_TEST_RUNNER_FAIL_FAST', None)  # For 'fail_fast' test\n    TestFlag('fail_fast', '1', '0')\n    TestFlag('filter', 'FooTest.Bar', '*')\n    SetEnvVar('XML_OUTPUT_FILE', None)  # For 'output' test\n    TestFlag('output', 'xml:tmp/foo.xml', '')\n    TestFlag('brief', '1', '0')\n    TestFlag('print_time', '0', '1')\n    TestFlag('repeat', '999', '1')\n    TestFlag('throw_on_failure', '1', '0')\n    TestFlag('death_test_style', 'threadsafe', 'fast')\n    TestFlag('catch_exceptions', '0', '1')\n\n    if IS_LINUX:\n      TestFlag('death_test_use_fork', '1', '0')\n      TestFlag('stack_trace_depth', '0', '100')\n\n\n  def testXmlOutputFile(self):\n    \"\"\"Tests that $XML_OUTPUT_FILE affects the output flag.\"\"\"\n\n    SetEnvVar('GTEST_OUTPUT', None)\n    SetEnvVar('XML_OUTPUT_FILE', 'tmp/bar.xml')\n    AssertEq('xml:tmp/bar.xml', GetFlag('output'))\n\n  def testXmlOutputFileOverride(self):\n    \"\"\"Tests that $XML_OUTPUT_FILE is overridden by $GTEST_OUTPUT.\"\"\"\n\n    SetEnvVar('GTEST_OUTPUT', 'xml:tmp/foo.xml')\n    SetEnvVar('XML_OUTPUT_FILE', 'tmp/bar.xml')\n    AssertEq('xml:tmp/foo.xml', GetFlag('output'))\n\nif __name__ == '__main__':\n  gtest_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-env-var-test_.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// A helper program for testing that Google Test parses the environment\n// variables correctly.\n\n#include <iostream>\n\n#include \"gtest/gtest.h\"\n#include \"src/gtest-internal-inl.h\"\n\nusing ::std::cout;\n\nnamespace testing {\n\n// The purpose of this is to make the test more realistic by ensuring\n// that the UnitTest singleton is created before main() is entered.\n// We don't actual run the TEST itself.\nTEST(GTestEnvVarTest, Dummy) {}\n\nvoid PrintFlag(const char* flag) {\n  if (strcmp(flag, \"break_on_failure\") == 0) {\n    cout << GTEST_FLAG_GET(break_on_failure);\n    return;\n  }\n\n  if (strcmp(flag, \"catch_exceptions\") == 0) {\n    cout << GTEST_FLAG_GET(catch_exceptions);\n    return;\n  }\n\n  if (strcmp(flag, \"color\") == 0) {\n    cout << GTEST_FLAG_GET(color);\n    return;\n  }\n\n  if (strcmp(flag, \"death_test_style\") == 0) {\n    cout << GTEST_FLAG_GET(death_test_style);\n    return;\n  }\n\n  if (strcmp(flag, \"death_test_use_fork\") == 0) {\n    cout << GTEST_FLAG_GET(death_test_use_fork);\n    return;\n  }\n\n  if (strcmp(flag, \"fail_fast\") == 0) {\n    cout << GTEST_FLAG_GET(fail_fast);\n    return;\n  }\n\n  if (strcmp(flag, \"filter\") == 0) {\n    cout << GTEST_FLAG_GET(filter);\n    return;\n  }\n\n  if (strcmp(flag, \"output\") == 0) {\n    cout << GTEST_FLAG_GET(output);\n    return;\n  }\n\n  if (strcmp(flag, \"brief\") == 0) {\n    cout << GTEST_FLAG_GET(brief);\n    return;\n  }\n\n  if (strcmp(flag, \"print_time\") == 0) {\n    cout << GTEST_FLAG_GET(print_time);\n    return;\n  }\n\n  if (strcmp(flag, \"repeat\") == 0) {\n    cout << GTEST_FLAG_GET(repeat);\n    return;\n  }\n\n  if (strcmp(flag, \"stack_trace_depth\") == 0) {\n    cout << GTEST_FLAG_GET(stack_trace_depth);\n    return;\n  }\n\n  if (strcmp(flag, \"throw_on_failure\") == 0) {\n    cout << GTEST_FLAG_GET(throw_on_failure);\n    return;\n  }\n\n  cout << \"Invalid flag name \" << flag\n       << \".  Valid names are break_on_failure, color, filter, etc.\\n\";\n  exit(1);\n}\n\n}  // namespace testing\n\nint main(int argc, char** argv) {\n  testing::InitGoogleTest(&argc, argv);\n\n  if (argc != 2) {\n    cout << \"Usage: googletest-env-var-test_ NAME_OF_FLAG\\n\";\n    return 1;\n  }\n\n  testing::PrintFlag(argv[1]);\n  return 0;\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-failfast-unittest.py",
    "content": "#!/usr/bin/env python\n#\n# Copyright 2020 Google Inc. All Rights Reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Unit test for Google Test fail_fast.\n\nA user can specify if a Google Test program should continue test execution\nafter a test failure via the GTEST_FAIL_FAST environment variable or the\n--gtest_fail_fast flag. The default value of the flag can also be changed\nby Bazel fail fast environment variable TESTBRIDGE_TEST_RUNNER_FAIL_FAST.\n\nThis script tests such functionality by invoking googletest-failfast-unittest_\n(a program written with Google Test) with different environments and command\nline flags.\n\"\"\"\n\nimport os\nfrom googletest.test import gtest_test_utils\n\n# Constants.\n\n# Bazel testbridge environment variable for fail fast\nBAZEL_FAIL_FAST_ENV_VAR = 'TESTBRIDGE_TEST_RUNNER_FAIL_FAST'\n\n# The environment variable for specifying fail fast.\nFAIL_FAST_ENV_VAR = 'GTEST_FAIL_FAST'\n\n# The command line flag for specifying fail fast.\nFAIL_FAST_FLAG = 'gtest_fail_fast'\n\n# The command line flag to run disabled tests.\nRUN_DISABLED_FLAG = 'gtest_also_run_disabled_tests'\n\n# The command line flag for specifying a filter.\nFILTER_FLAG = 'gtest_filter'\n\n# Command to run the googletest-failfast-unittest_ program.\nCOMMAND = gtest_test_utils.GetTestExecutablePath(\n    'googletest-failfast-unittest_')\n\n# The command line flag to tell Google Test to output the list of tests it\n# will run.\nLIST_TESTS_FLAG = '--gtest_list_tests'\n\n# Indicates whether Google Test supports death tests.\nSUPPORTS_DEATH_TESTS = 'HasDeathTest' in gtest_test_utils.Subprocess(\n    [COMMAND, LIST_TESTS_FLAG]).output\n\n# Utilities.\n\nenviron = os.environ.copy()\n\n\ndef SetEnvVar(env_var, value):\n  \"\"\"Sets the env variable to 'value'; unsets it when 'value' is None.\"\"\"\n\n  if value is not None:\n    environ[env_var] = value\n  elif env_var in environ:\n    del environ[env_var]\n\n\ndef RunAndReturnOutput(test_suite=None, fail_fast=None, run_disabled=False):\n  \"\"\"Runs the test program and returns its output.\"\"\"\n\n  args = []\n  xml_path = os.path.join(gtest_test_utils.GetTempDir(),\n                          '.GTestFailFastUnitTest.xml')\n  args += ['--gtest_output=xml:' + xml_path]\n  if fail_fast is not None:\n    if isinstance(fail_fast, str):\n      args += ['--%s=%s' % (FAIL_FAST_FLAG, fail_fast)]\n    elif fail_fast:\n      args += ['--%s' % FAIL_FAST_FLAG]\n    else:\n      args += ['--no%s' % FAIL_FAST_FLAG]\n  if test_suite:\n    args += ['--%s=%s.*' % (FILTER_FLAG, test_suite)]\n  if run_disabled:\n    args += ['--%s' % RUN_DISABLED_FLAG]\n  txt_out = gtest_test_utils.Subprocess([COMMAND] + args, env=environ).output\n  with open(xml_path) as xml_file:\n    return txt_out, xml_file.read()\n\n\n# The unit test.\nclass GTestFailFastUnitTest(gtest_test_utils.TestCase):\n  \"\"\"Tests the env variable or the command line flag for fail_fast.\"\"\"\n\n  def testDefaultBehavior(self):\n    \"\"\"Tests the behavior of not specifying the fail_fast.\"\"\"\n\n    txt, _ = RunAndReturnOutput()\n    self.assertIn('22 FAILED TEST', txt)\n\n  def testGoogletestFlag(self):\n    txt, _ = RunAndReturnOutput(test_suite='HasSimpleTest', fail_fast=True)\n    self.assertIn('1 FAILED TEST', txt)\n    self.assertIn('[  SKIPPED ] 3 tests', txt)\n\n    txt, _ = RunAndReturnOutput(test_suite='HasSimpleTest', fail_fast=False)\n    self.assertIn('4 FAILED TEST', txt)\n    self.assertNotIn('[  SKIPPED ]', txt)\n\n  def testGoogletestEnvVar(self):\n    \"\"\"Tests the behavior of specifying fail_fast via Googletest env var.\"\"\"\n\n    try:\n      SetEnvVar(FAIL_FAST_ENV_VAR, '1')\n      txt, _ = RunAndReturnOutput('HasSimpleTest')\n      self.assertIn('1 FAILED TEST', txt)\n      self.assertIn('[  SKIPPED ] 3 tests', txt)\n\n      SetEnvVar(FAIL_FAST_ENV_VAR, '0')\n      txt, _ = RunAndReturnOutput('HasSimpleTest')\n      self.assertIn('4 FAILED TEST', txt)\n      self.assertNotIn('[  SKIPPED ]', txt)\n    finally:\n      SetEnvVar(FAIL_FAST_ENV_VAR, None)\n\n  def testBazelEnvVar(self):\n    \"\"\"Tests the behavior of specifying fail_fast via Bazel testbridge.\"\"\"\n\n    try:\n      SetEnvVar(BAZEL_FAIL_FAST_ENV_VAR, '1')\n      txt, _ = RunAndReturnOutput('HasSimpleTest')\n      self.assertIn('1 FAILED TEST', txt)\n      self.assertIn('[  SKIPPED ] 3 tests', txt)\n\n      SetEnvVar(BAZEL_FAIL_FAST_ENV_VAR, '0')\n      txt, _ = RunAndReturnOutput('HasSimpleTest')\n      self.assertIn('4 FAILED TEST', txt)\n      self.assertNotIn('[  SKIPPED ]', txt)\n    finally:\n      SetEnvVar(BAZEL_FAIL_FAST_ENV_VAR, None)\n\n  def testFlagOverridesEnvVar(self):\n    \"\"\"Tests precedence of flag over env var.\"\"\"\n\n    try:\n      SetEnvVar(FAIL_FAST_ENV_VAR, '0')\n      txt, _ = RunAndReturnOutput('HasSimpleTest', True)\n      self.assertIn('1 FAILED TEST', txt)\n      self.assertIn('[  SKIPPED ] 3 tests', txt)\n    finally:\n      SetEnvVar(FAIL_FAST_ENV_VAR, None)\n\n  def testGoogletestEnvVarOverridesBazelEnvVar(self):\n    \"\"\"Tests that the Googletest native env var over Bazel testbridge.\"\"\"\n\n    try:\n      SetEnvVar(BAZEL_FAIL_FAST_ENV_VAR, '0')\n      SetEnvVar(FAIL_FAST_ENV_VAR, '1')\n      txt, _ = RunAndReturnOutput('HasSimpleTest')\n      self.assertIn('1 FAILED TEST', txt)\n      self.assertIn('[  SKIPPED ] 3 tests', txt)\n    finally:\n      SetEnvVar(FAIL_FAST_ENV_VAR, None)\n      SetEnvVar(BAZEL_FAIL_FAST_ENV_VAR, None)\n\n  def testEventListener(self):\n    txt, _ = RunAndReturnOutput(test_suite='HasSkipTest', fail_fast=True)\n    self.assertIn('1 FAILED TEST', txt)\n    self.assertIn('[  SKIPPED ] 3 tests', txt)\n    for expected_count, callback in [(1, 'OnTestSuiteStart'),\n                                     (5, 'OnTestStart'),\n                                     (5, 'OnTestEnd'),\n                                     (5, 'OnTestPartResult'),\n                                     (1, 'OnTestSuiteEnd')]:\n      self.assertEqual(\n          expected_count, txt.count(callback),\n          'Expected %d calls to callback %s match count on output: %s ' %\n          (expected_count, callback, txt))\n\n    txt, _ = RunAndReturnOutput(test_suite='HasSkipTest', fail_fast=False)\n    self.assertIn('3 FAILED TEST', txt)\n    self.assertIn('[  SKIPPED ] 1 test', txt)\n    for expected_count, callback in [(1, 'OnTestSuiteStart'),\n                                     (5, 'OnTestStart'),\n                                     (5, 'OnTestEnd'),\n                                     (5, 'OnTestPartResult'),\n                                     (1, 'OnTestSuiteEnd')]:\n      self.assertEqual(\n          expected_count, txt.count(callback),\n          'Expected %d calls to callback %s match count on output: %s ' %\n          (expected_count, callback, txt))\n\n  def assertXmlResultCount(self, result, count, xml):\n    self.assertEqual(\n        count, xml.count('result=\"%s\"' % result),\n        'Expected \\'result=\"%s\"\\' match count of %s: %s ' %\n        (result, count, xml))\n\n  def assertXmlStatusCount(self, status, count, xml):\n    self.assertEqual(\n        count, xml.count('status=\"%s\"' % status),\n        'Expected \\'status=\"%s\"\\' match count of %s: %s ' %\n        (status, count, xml))\n\n  def assertFailFastXmlAndTxtOutput(self,\n                                    fail_fast,\n                                    test_suite,\n                                    passed_count,\n                                    failure_count,\n                                    skipped_count,\n                                    suppressed_count,\n                                    run_disabled=False):\n    \"\"\"Assert XML and text output of a test execution.\"\"\"\n\n    txt, xml = RunAndReturnOutput(test_suite, fail_fast, run_disabled)\n    if failure_count > 0:\n      self.assertIn('%s FAILED TEST' % failure_count, txt)\n    if suppressed_count > 0:\n      self.assertIn('%s DISABLED TEST' % suppressed_count, txt)\n    if skipped_count > 0:\n      self.assertIn('[  SKIPPED ] %s tests' % skipped_count, txt)\n    self.assertXmlStatusCount('run',\n                              passed_count + failure_count + skipped_count, xml)\n    self.assertXmlStatusCount('notrun', suppressed_count, xml)\n    self.assertXmlResultCount('completed', passed_count + failure_count, xml)\n    self.assertXmlResultCount('skipped', skipped_count, xml)\n    self.assertXmlResultCount('suppressed', suppressed_count, xml)\n\n  def assertFailFastBehavior(self,\n                             test_suite,\n                             passed_count,\n                             failure_count,\n                             skipped_count,\n                             suppressed_count,\n                             run_disabled=False):\n    \"\"\"Assert --fail_fast via flag.\"\"\"\n\n    for fail_fast in ('true', '1', 't', True):\n      self.assertFailFastXmlAndTxtOutput(fail_fast, test_suite, passed_count,\n                                         failure_count, skipped_count,\n                                         suppressed_count, run_disabled)\n\n  def assertNotFailFastBehavior(self,\n                                test_suite,\n                                passed_count,\n                                failure_count,\n                                skipped_count,\n                                suppressed_count,\n                                run_disabled=False):\n    \"\"\"Assert --nofail_fast via flag.\"\"\"\n\n    for fail_fast in ('false', '0', 'f', False):\n      self.assertFailFastXmlAndTxtOutput(fail_fast, test_suite, passed_count,\n                                         failure_count, skipped_count,\n                                         suppressed_count, run_disabled)\n\n  def testFlag_HasFixtureTest(self):\n    \"\"\"Tests the behavior of fail_fast and TEST_F.\"\"\"\n    self.assertFailFastBehavior(\n        test_suite='HasFixtureTest',\n        passed_count=1,\n        failure_count=1,\n        skipped_count=3,\n        suppressed_count=0)\n    self.assertNotFailFastBehavior(\n        test_suite='HasFixtureTest',\n        passed_count=1,\n        failure_count=4,\n        skipped_count=0,\n        suppressed_count=0)\n\n  def testFlag_HasSimpleTest(self):\n    \"\"\"Tests the behavior of fail_fast and TEST.\"\"\"\n    self.assertFailFastBehavior(\n        test_suite='HasSimpleTest',\n        passed_count=1,\n        failure_count=1,\n        skipped_count=3,\n        suppressed_count=0)\n    self.assertNotFailFastBehavior(\n        test_suite='HasSimpleTest',\n        passed_count=1,\n        failure_count=4,\n        skipped_count=0,\n        suppressed_count=0)\n\n  def testFlag_HasParametersTest(self):\n    \"\"\"Tests the behavior of fail_fast and TEST_P.\"\"\"\n    self.assertFailFastBehavior(\n        test_suite='HasParametersSuite/HasParametersTest',\n        passed_count=0,\n        failure_count=1,\n        skipped_count=3,\n        suppressed_count=0)\n    self.assertNotFailFastBehavior(\n        test_suite='HasParametersSuite/HasParametersTest',\n        passed_count=0,\n        failure_count=4,\n        skipped_count=0,\n        suppressed_count=0)\n\n  def testFlag_HasDisabledTest(self):\n    \"\"\"Tests the behavior of fail_fast and Disabled test cases.\"\"\"\n    self.assertFailFastBehavior(\n        test_suite='HasDisabledTest',\n        passed_count=1,\n        failure_count=1,\n        skipped_count=2,\n        suppressed_count=1,\n        run_disabled=False)\n    self.assertNotFailFastBehavior(\n        test_suite='HasDisabledTest',\n        passed_count=1,\n        failure_count=3,\n        skipped_count=0,\n        suppressed_count=1,\n        run_disabled=False)\n\n  def testFlag_HasDisabledRunDisabledTest(self):\n    \"\"\"Tests the behavior of fail_fast and Disabled test cases enabled.\"\"\"\n    self.assertFailFastBehavior(\n        test_suite='HasDisabledTest',\n        passed_count=1,\n        failure_count=1,\n        skipped_count=3,\n        suppressed_count=0,\n        run_disabled=True)\n    self.assertNotFailFastBehavior(\n        test_suite='HasDisabledTest',\n        passed_count=1,\n        failure_count=4,\n        skipped_count=0,\n        suppressed_count=0,\n        run_disabled=True)\n\n  def testFlag_HasDisabledSuiteTest(self):\n    \"\"\"Tests the behavior of fail_fast and Disabled test suites.\"\"\"\n    self.assertFailFastBehavior(\n        test_suite='DISABLED_HasDisabledSuite',\n        passed_count=0,\n        failure_count=0,\n        skipped_count=0,\n        suppressed_count=5,\n        run_disabled=False)\n    self.assertNotFailFastBehavior(\n        test_suite='DISABLED_HasDisabledSuite',\n        passed_count=0,\n        failure_count=0,\n        skipped_count=0,\n        suppressed_count=5,\n        run_disabled=False)\n\n  def testFlag_HasDisabledSuiteRunDisabledTest(self):\n    \"\"\"Tests the behavior of fail_fast and Disabled test suites enabled.\"\"\"\n    self.assertFailFastBehavior(\n        test_suite='DISABLED_HasDisabledSuite',\n        passed_count=1,\n        failure_count=1,\n        skipped_count=3,\n        suppressed_count=0,\n        run_disabled=True)\n    self.assertNotFailFastBehavior(\n        test_suite='DISABLED_HasDisabledSuite',\n        passed_count=1,\n        failure_count=4,\n        skipped_count=0,\n        suppressed_count=0,\n        run_disabled=True)\n\n  if SUPPORTS_DEATH_TESTS:\n\n    def testFlag_HasDeathTest(self):\n      \"\"\"Tests the behavior of fail_fast and death tests.\"\"\"\n      self.assertFailFastBehavior(\n          test_suite='HasDeathTest',\n          passed_count=1,\n          failure_count=1,\n          skipped_count=3,\n          suppressed_count=0)\n      self.assertNotFailFastBehavior(\n          test_suite='HasDeathTest',\n          passed_count=1,\n          failure_count=4,\n          skipped_count=0,\n          suppressed_count=0)\n\n\nif __name__ == '__main__':\n  gtest_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-failfast-unittest_.cc",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Unit test for Google Test test filters.\n//\n// A user can specify which test(s) in a Google Test program to run via\n// either the GTEST_FILTER environment variable or the --gtest_filter\n// flag.  This is used for testing such functionality.\n//\n// The program will be invoked from a Python unit test.  Don't run it\n// directly.\n\n#include \"gtest/gtest.h\"\n\nnamespace {\n\n// Test HasFixtureTest.\n\nclass HasFixtureTest : public testing::Test {};\n\nTEST_F(HasFixtureTest, Test0) {}\n\nTEST_F(HasFixtureTest, Test1) { FAIL() << \"Expected failure.\"; }\n\nTEST_F(HasFixtureTest, Test2) { FAIL() << \"Expected failure.\"; }\n\nTEST_F(HasFixtureTest, Test3) { FAIL() << \"Expected failure.\"; }\n\nTEST_F(HasFixtureTest, Test4) { FAIL() << \"Expected failure.\"; }\n\n// Test HasSimpleTest.\n\nTEST(HasSimpleTest, Test0) {}\n\nTEST(HasSimpleTest, Test1) { FAIL() << \"Expected failure.\"; }\n\nTEST(HasSimpleTest, Test2) { FAIL() << \"Expected failure.\"; }\n\nTEST(HasSimpleTest, Test3) { FAIL() << \"Expected failure.\"; }\n\nTEST(HasSimpleTest, Test4) { FAIL() << \"Expected failure.\"; }\n\n// Test HasDisabledTest.\n\nTEST(HasDisabledTest, Test0) {}\n\nTEST(HasDisabledTest, DISABLED_Test1) { FAIL() << \"Expected failure.\"; }\n\nTEST(HasDisabledTest, Test2) { FAIL() << \"Expected failure.\"; }\n\nTEST(HasDisabledTest, Test3) { FAIL() << \"Expected failure.\"; }\n\nTEST(HasDisabledTest, Test4) { FAIL() << \"Expected failure.\"; }\n\n// Test HasDeathTest\n\nTEST(HasDeathTest, Test0) { EXPECT_DEATH_IF_SUPPORTED(exit(1), \".*\"); }\n\nTEST(HasDeathTest, Test1) {\n  EXPECT_DEATH_IF_SUPPORTED(FAIL() << \"Expected failure.\", \".*\");\n}\n\nTEST(HasDeathTest, Test2) {\n  EXPECT_DEATH_IF_SUPPORTED(FAIL() << \"Expected failure.\", \".*\");\n}\n\nTEST(HasDeathTest, Test3) {\n  EXPECT_DEATH_IF_SUPPORTED(FAIL() << \"Expected failure.\", \".*\");\n}\n\nTEST(HasDeathTest, Test4) {\n  EXPECT_DEATH_IF_SUPPORTED(FAIL() << \"Expected failure.\", \".*\");\n}\n\n// Test DISABLED_HasDisabledSuite\n\nTEST(DISABLED_HasDisabledSuite, Test0) {}\n\nTEST(DISABLED_HasDisabledSuite, Test1) { FAIL() << \"Expected failure.\"; }\n\nTEST(DISABLED_HasDisabledSuite, Test2) { FAIL() << \"Expected failure.\"; }\n\nTEST(DISABLED_HasDisabledSuite, Test3) { FAIL() << \"Expected failure.\"; }\n\nTEST(DISABLED_HasDisabledSuite, Test4) { FAIL() << \"Expected failure.\"; }\n\n// Test HasParametersTest\n\nclass HasParametersTest : public testing::TestWithParam<int> {};\n\nTEST_P(HasParametersTest, Test1) { FAIL() << \"Expected failure.\"; }\n\nTEST_P(HasParametersTest, Test2) { FAIL() << \"Expected failure.\"; }\n\nINSTANTIATE_TEST_SUITE_P(HasParametersSuite, HasParametersTest,\n                         testing::Values(1, 2));\n\nclass MyTestListener : public ::testing::EmptyTestEventListener {\n  void OnTestSuiteStart(const ::testing::TestSuite& test_suite) override {\n    printf(\"We are in OnTestSuiteStart of %s.\\n\", test_suite.name());\n  }\n\n  void OnTestStart(const ::testing::TestInfo& test_info) override {\n    printf(\"We are in OnTestStart of %s.%s.\\n\", test_info.test_suite_name(),\n           test_info.name());\n  }\n\n  void OnTestPartResult(\n      const ::testing::TestPartResult& test_part_result) override {\n    printf(\"We are in OnTestPartResult %s:%d.\\n\", test_part_result.file_name(),\n           test_part_result.line_number());\n  }\n\n  void OnTestEnd(const ::testing::TestInfo& test_info) override {\n    printf(\"We are in OnTestEnd of %s.%s.\\n\", test_info.test_suite_name(),\n           test_info.name());\n  }\n\n  void OnTestSuiteEnd(const ::testing::TestSuite& test_suite) override {\n    printf(\"We are in OnTestSuiteEnd of %s.\\n\", test_suite.name());\n  }\n};\n\nTEST(HasSkipTest, Test0) { SUCCEED() << \"Expected success.\"; }\n\nTEST(HasSkipTest, Test1) { GTEST_SKIP() << \"Expected skip.\"; }\n\nTEST(HasSkipTest, Test2) { FAIL() << \"Expected failure.\"; }\n\nTEST(HasSkipTest, Test3) { FAIL() << \"Expected failure.\"; }\n\nTEST(HasSkipTest, Test4) { FAIL() << \"Expected failure.\"; }\n\n}  // namespace\n\nint main(int argc, char** argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n  ::testing::UnitTest::GetInstance()->listeners().Append(new MyTestListener());\n  return RUN_ALL_TESTS();\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-filepath-test.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Google Test filepath utilities\n//\n// This file tests classes and functions used internally by\n// Google Test.  They are subject to change without notice.\n//\n// This file is #included from gtest-internal.h.\n// Do not #include this file anywhere else!\n\n#include \"gtest/gtest.h\"\n#include \"gtest/internal/gtest-filepath.h\"\n#include \"src/gtest-internal-inl.h\"\n\n#if GTEST_OS_WINDOWS_MOBILE\n#include <windows.h>  // NOLINT\n#elif GTEST_OS_WINDOWS\n#include <direct.h>  // NOLINT\n#endif               // GTEST_OS_WINDOWS_MOBILE\n\nnamespace testing {\nnamespace internal {\nnamespace {\n\n#if GTEST_OS_WINDOWS_MOBILE\n\n// Windows CE doesn't have the remove C function.\nint remove(const char* path) {\n  LPCWSTR wpath = String::AnsiToUtf16(path);\n  int ret = DeleteFile(wpath) ? 0 : -1;\n  delete[] wpath;\n  return ret;\n}\n// Windows CE doesn't have the _rmdir C function.\nint _rmdir(const char* path) {\n  FilePath filepath(path);\n  LPCWSTR wpath =\n      String::AnsiToUtf16(filepath.RemoveTrailingPathSeparator().c_str());\n  int ret = RemoveDirectory(wpath) ? 0 : -1;\n  delete[] wpath;\n  return ret;\n}\n\n#else\n\nTEST(GetCurrentDirTest, ReturnsCurrentDir) {\n  const FilePath original_dir = FilePath::GetCurrentDir();\n  EXPECT_FALSE(original_dir.IsEmpty());\n\n  posix::ChDir(GTEST_PATH_SEP_);\n  const FilePath cwd = FilePath::GetCurrentDir();\n  posix::ChDir(original_dir.c_str());\n\n#if GTEST_OS_WINDOWS || GTEST_OS_OS2\n\n  // Skips the \":\".\n  const char* const cwd_without_drive = strchr(cwd.c_str(), ':');\n  ASSERT_TRUE(cwd_without_drive != NULL);\n  EXPECT_STREQ(GTEST_PATH_SEP_, cwd_without_drive + 1);\n\n#else\n\n  EXPECT_EQ(GTEST_PATH_SEP_, cwd.string());\n\n#endif\n}\n\n#endif  // GTEST_OS_WINDOWS_MOBILE\n\nTEST(IsEmptyTest, ReturnsTrueForEmptyPath) {\n  EXPECT_TRUE(FilePath(\"\").IsEmpty());\n}\n\nTEST(IsEmptyTest, ReturnsFalseForNonEmptyPath) {\n  EXPECT_FALSE(FilePath(\"a\").IsEmpty());\n  EXPECT_FALSE(FilePath(\".\").IsEmpty());\n  EXPECT_FALSE(FilePath(\"a/b\").IsEmpty());\n  EXPECT_FALSE(FilePath(\"a\\\\b\\\\\").IsEmpty());\n}\n\n// RemoveDirectoryName \"\" -> \"\"\nTEST(RemoveDirectoryNameTest, WhenEmptyName) {\n  EXPECT_EQ(\"\", FilePath(\"\").RemoveDirectoryName().string());\n}\n\n// RemoveDirectoryName \"afile\" -> \"afile\"\nTEST(RemoveDirectoryNameTest, ButNoDirectory) {\n  EXPECT_EQ(\"afile\", FilePath(\"afile\").RemoveDirectoryName().string());\n}\n\n// RemoveDirectoryName \"/afile\" -> \"afile\"\nTEST(RemoveDirectoryNameTest, RootFileShouldGiveFileName) {\n  EXPECT_EQ(\"afile\",\n            FilePath(GTEST_PATH_SEP_ \"afile\").RemoveDirectoryName().string());\n}\n\n// RemoveDirectoryName \"adir/\" -> \"\"\nTEST(RemoveDirectoryNameTest, WhereThereIsNoFileName) {\n  EXPECT_EQ(\"\",\n            FilePath(\"adir\" GTEST_PATH_SEP_).RemoveDirectoryName().string());\n}\n\n// RemoveDirectoryName \"adir/afile\" -> \"afile\"\nTEST(RemoveDirectoryNameTest, ShouldGiveFileName) {\n  EXPECT_EQ(\n      \"afile\",\n      FilePath(\"adir\" GTEST_PATH_SEP_ \"afile\").RemoveDirectoryName().string());\n}\n\n// RemoveDirectoryName \"adir/subdir/afile\" -> \"afile\"\nTEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileName) {\n  EXPECT_EQ(\"afile\",\n            FilePath(\"adir\" GTEST_PATH_SEP_ \"subdir\" GTEST_PATH_SEP_ \"afile\")\n                .RemoveDirectoryName()\n                .string());\n}\n\n#if GTEST_HAS_ALT_PATH_SEP_\n\n// Tests that RemoveDirectoryName() works with the alternate separator\n// on Windows.\n\n// RemoveDirectoryName(\"/afile\") -> \"afile\"\nTEST(RemoveDirectoryNameTest, RootFileShouldGiveFileNameForAlternateSeparator) {\n  EXPECT_EQ(\"afile\", FilePath(\"/afile\").RemoveDirectoryName().string());\n}\n\n// RemoveDirectoryName(\"adir/\") -> \"\"\nTEST(RemoveDirectoryNameTest, WhereThereIsNoFileNameForAlternateSeparator) {\n  EXPECT_EQ(\"\", FilePath(\"adir/\").RemoveDirectoryName().string());\n}\n\n// RemoveDirectoryName(\"adir/afile\") -> \"afile\"\nTEST(RemoveDirectoryNameTest, ShouldGiveFileNameForAlternateSeparator) {\n  EXPECT_EQ(\"afile\", FilePath(\"adir/afile\").RemoveDirectoryName().string());\n}\n\n// RemoveDirectoryName(\"adir/subdir/afile\") -> \"afile\"\nTEST(RemoveDirectoryNameTest, ShouldAlsoGiveFileNameForAlternateSeparator) {\n  EXPECT_EQ(\"afile\",\n            FilePath(\"adir/subdir/afile\").RemoveDirectoryName().string());\n}\n\n#endif\n\n// RemoveFileName \"\" -> \"./\"\nTEST(RemoveFileNameTest, EmptyName) {\n#if GTEST_OS_WINDOWS_MOBILE\n  // On Windows CE, we use the root as the current directory.\n  EXPECT_EQ(GTEST_PATH_SEP_, FilePath(\"\").RemoveFileName().string());\n#else\n  EXPECT_EQ(\".\" GTEST_PATH_SEP_, FilePath(\"\").RemoveFileName().string());\n#endif\n}\n\n// RemoveFileName \"adir/\" -> \"adir/\"\nTEST(RemoveFileNameTest, ButNoFile) {\n  EXPECT_EQ(\"adir\" GTEST_PATH_SEP_,\n            FilePath(\"adir\" GTEST_PATH_SEP_).RemoveFileName().string());\n}\n\n// RemoveFileName \"adir/afile\" -> \"adir/\"\nTEST(RemoveFileNameTest, GivesDirName) {\n  EXPECT_EQ(\"adir\" GTEST_PATH_SEP_,\n            FilePath(\"adir\" GTEST_PATH_SEP_ \"afile\").RemoveFileName().string());\n}\n\n// RemoveFileName \"adir/subdir/afile\" -> \"adir/subdir/\"\nTEST(RemoveFileNameTest, GivesDirAndSubDirName) {\n  EXPECT_EQ(\"adir\" GTEST_PATH_SEP_ \"subdir\" GTEST_PATH_SEP_,\n            FilePath(\"adir\" GTEST_PATH_SEP_ \"subdir\" GTEST_PATH_SEP_ \"afile\")\n                .RemoveFileName()\n                .string());\n}\n\n// RemoveFileName \"/afile\" -> \"/\"\nTEST(RemoveFileNameTest, GivesRootDir) {\n  EXPECT_EQ(GTEST_PATH_SEP_,\n            FilePath(GTEST_PATH_SEP_ \"afile\").RemoveFileName().string());\n}\n\n#if GTEST_HAS_ALT_PATH_SEP_\n\n// Tests that RemoveFileName() works with the alternate separator on\n// Windows.\n\n// RemoveFileName(\"adir/\") -> \"adir/\"\nTEST(RemoveFileNameTest, ButNoFileForAlternateSeparator) {\n  EXPECT_EQ(\"adir\" GTEST_PATH_SEP_,\n            FilePath(\"adir/\").RemoveFileName().string());\n}\n\n// RemoveFileName(\"adir/afile\") -> \"adir/\"\nTEST(RemoveFileNameTest, GivesDirNameForAlternateSeparator) {\n  EXPECT_EQ(\"adir\" GTEST_PATH_SEP_,\n            FilePath(\"adir/afile\").RemoveFileName().string());\n}\n\n// RemoveFileName(\"adir/subdir/afile\") -> \"adir/subdir/\"\nTEST(RemoveFileNameTest, GivesDirAndSubDirNameForAlternateSeparator) {\n  EXPECT_EQ(\"adir\" GTEST_PATH_SEP_ \"subdir\" GTEST_PATH_SEP_,\n            FilePath(\"adir/subdir/afile\").RemoveFileName().string());\n}\n\n// RemoveFileName(\"/afile\") -> \"\\\"\nTEST(RemoveFileNameTest, GivesRootDirForAlternateSeparator) {\n  EXPECT_EQ(GTEST_PATH_SEP_, FilePath(\"/afile\").RemoveFileName().string());\n}\n\n#endif\n\nTEST(MakeFileNameTest, GenerateWhenNumberIsZero) {\n  FilePath actual =\n      FilePath::MakeFileName(FilePath(\"foo\"), FilePath(\"bar\"), 0, \"xml\");\n  EXPECT_EQ(\"foo\" GTEST_PATH_SEP_ \"bar.xml\", actual.string());\n}\n\nTEST(MakeFileNameTest, GenerateFileNameNumberGtZero) {\n  FilePath actual =\n      FilePath::MakeFileName(FilePath(\"foo\"), FilePath(\"bar\"), 12, \"xml\");\n  EXPECT_EQ(\"foo\" GTEST_PATH_SEP_ \"bar_12.xml\", actual.string());\n}\n\nTEST(MakeFileNameTest, GenerateFileNameWithSlashNumberIsZero) {\n  FilePath actual = FilePath::MakeFileName(FilePath(\"foo\" GTEST_PATH_SEP_),\n                                           FilePath(\"bar\"), 0, \"xml\");\n  EXPECT_EQ(\"foo\" GTEST_PATH_SEP_ \"bar.xml\", actual.string());\n}\n\nTEST(MakeFileNameTest, GenerateFileNameWithSlashNumberGtZero) {\n  FilePath actual = FilePath::MakeFileName(FilePath(\"foo\" GTEST_PATH_SEP_),\n                                           FilePath(\"bar\"), 12, \"xml\");\n  EXPECT_EQ(\"foo\" GTEST_PATH_SEP_ \"bar_12.xml\", actual.string());\n}\n\nTEST(MakeFileNameTest, GenerateWhenNumberIsZeroAndDirIsEmpty) {\n  FilePath actual =\n      FilePath::MakeFileName(FilePath(\"\"), FilePath(\"bar\"), 0, \"xml\");\n  EXPECT_EQ(\"bar.xml\", actual.string());\n}\n\nTEST(MakeFileNameTest, GenerateWhenNumberIsNotZeroAndDirIsEmpty) {\n  FilePath actual =\n      FilePath::MakeFileName(FilePath(\"\"), FilePath(\"bar\"), 14, \"xml\");\n  EXPECT_EQ(\"bar_14.xml\", actual.string());\n}\n\nTEST(ConcatPathsTest, WorksWhenDirDoesNotEndWithPathSep) {\n  FilePath actual = FilePath::ConcatPaths(FilePath(\"foo\"), FilePath(\"bar.xml\"));\n  EXPECT_EQ(\"foo\" GTEST_PATH_SEP_ \"bar.xml\", actual.string());\n}\n\nTEST(ConcatPathsTest, WorksWhenPath1EndsWithPathSep) {\n  FilePath actual = FilePath::ConcatPaths(FilePath(\"foo\" GTEST_PATH_SEP_),\n                                          FilePath(\"bar.xml\"));\n  EXPECT_EQ(\"foo\" GTEST_PATH_SEP_ \"bar.xml\", actual.string());\n}\n\nTEST(ConcatPathsTest, Path1BeingEmpty) {\n  FilePath actual = FilePath::ConcatPaths(FilePath(\"\"), FilePath(\"bar.xml\"));\n  EXPECT_EQ(\"bar.xml\", actual.string());\n}\n\nTEST(ConcatPathsTest, Path2BeingEmpty) {\n  FilePath actual = FilePath::ConcatPaths(FilePath(\"foo\"), FilePath(\"\"));\n  EXPECT_EQ(\"foo\" GTEST_PATH_SEP_, actual.string());\n}\n\nTEST(ConcatPathsTest, BothPathBeingEmpty) {\n  FilePath actual = FilePath::ConcatPaths(FilePath(\"\"), FilePath(\"\"));\n  EXPECT_EQ(\"\", actual.string());\n}\n\nTEST(ConcatPathsTest, Path1ContainsPathSep) {\n  FilePath actual = FilePath::ConcatPaths(FilePath(\"foo\" GTEST_PATH_SEP_ \"bar\"),\n                                          FilePath(\"foobar.xml\"));\n  EXPECT_EQ(\"foo\" GTEST_PATH_SEP_ \"bar\" GTEST_PATH_SEP_ \"foobar.xml\",\n            actual.string());\n}\n\nTEST(ConcatPathsTest, Path2ContainsPathSep) {\n  FilePath actual =\n      FilePath::ConcatPaths(FilePath(\"foo\" GTEST_PATH_SEP_),\n                            FilePath(\"bar\" GTEST_PATH_SEP_ \"bar.xml\"));\n  EXPECT_EQ(\"foo\" GTEST_PATH_SEP_ \"bar\" GTEST_PATH_SEP_ \"bar.xml\",\n            actual.string());\n}\n\nTEST(ConcatPathsTest, Path2EndsWithPathSep) {\n  FilePath actual =\n      FilePath::ConcatPaths(FilePath(\"foo\"), FilePath(\"bar\" GTEST_PATH_SEP_));\n  EXPECT_EQ(\"foo\" GTEST_PATH_SEP_ \"bar\" GTEST_PATH_SEP_, actual.string());\n}\n\n// RemoveTrailingPathSeparator \"\" -> \"\"\nTEST(RemoveTrailingPathSeparatorTest, EmptyString) {\n  EXPECT_EQ(\"\", FilePath(\"\").RemoveTrailingPathSeparator().string());\n}\n\n// RemoveTrailingPathSeparator \"foo\" -> \"foo\"\nTEST(RemoveTrailingPathSeparatorTest, FileNoSlashString) {\n  EXPECT_EQ(\"foo\", FilePath(\"foo\").RemoveTrailingPathSeparator().string());\n}\n\n// RemoveTrailingPathSeparator \"foo/\" -> \"foo\"\nTEST(RemoveTrailingPathSeparatorTest, ShouldRemoveTrailingSeparator) {\n  EXPECT_EQ(\n      \"foo\",\n      FilePath(\"foo\" GTEST_PATH_SEP_).RemoveTrailingPathSeparator().string());\n#if GTEST_HAS_ALT_PATH_SEP_\n  EXPECT_EQ(\"foo\", FilePath(\"foo/\").RemoveTrailingPathSeparator().string());\n#endif\n}\n\n// RemoveTrailingPathSeparator \"foo/bar/\" -> \"foo/bar/\"\nTEST(RemoveTrailingPathSeparatorTest, ShouldRemoveLastSeparator) {\n  EXPECT_EQ(\"foo\" GTEST_PATH_SEP_ \"bar\",\n            FilePath(\"foo\" GTEST_PATH_SEP_ \"bar\" GTEST_PATH_SEP_)\n                .RemoveTrailingPathSeparator()\n                .string());\n}\n\n// RemoveTrailingPathSeparator \"foo/bar\" -> \"foo/bar\"\nTEST(RemoveTrailingPathSeparatorTest, ShouldReturnUnmodified) {\n  EXPECT_EQ(\"foo\" GTEST_PATH_SEP_ \"bar\", FilePath(\"foo\" GTEST_PATH_SEP_ \"bar\")\n                                             .RemoveTrailingPathSeparator()\n                                             .string());\n}\n\nTEST(DirectoryTest, RootDirectoryExists) {\n#if GTEST_OS_WINDOWS              // We are on Windows.\n  char current_drive[_MAX_PATH];  // NOLINT\n  current_drive[0] = static_cast<char>(_getdrive() + 'A' - 1);\n  current_drive[1] = ':';\n  current_drive[2] = '\\\\';\n  current_drive[3] = '\\0';\n  EXPECT_TRUE(FilePath(current_drive).DirectoryExists());\n#else\n  EXPECT_TRUE(FilePath(\"/\").DirectoryExists());\n#endif  // GTEST_OS_WINDOWS\n}\n\n#if GTEST_OS_WINDOWS\nTEST(DirectoryTest, RootOfWrongDriveDoesNotExists) {\n  const int saved_drive_ = _getdrive();\n  // Find a drive that doesn't exist. Start with 'Z' to avoid common ones.\n  for (char drive = 'Z'; drive >= 'A'; drive--)\n    if (_chdrive(drive - 'A' + 1) == -1) {\n      char non_drive[_MAX_PATH];  // NOLINT\n      non_drive[0] = drive;\n      non_drive[1] = ':';\n      non_drive[2] = '\\\\';\n      non_drive[3] = '\\0';\n      EXPECT_FALSE(FilePath(non_drive).DirectoryExists());\n      break;\n    }\n  _chdrive(saved_drive_);\n}\n#endif  // GTEST_OS_WINDOWS\n\n#if !GTEST_OS_WINDOWS_MOBILE\n// Windows CE _does_ consider an empty directory to exist.\nTEST(DirectoryTest, EmptyPathDirectoryDoesNotExist) {\n  EXPECT_FALSE(FilePath(\"\").DirectoryExists());\n}\n#endif  // !GTEST_OS_WINDOWS_MOBILE\n\nTEST(DirectoryTest, CurrentDirectoryExists) {\n#if GTEST_OS_WINDOWS  // We are on Windows.\n#ifndef _WIN32_CE     // Windows CE doesn't have a current directory.\n\n  EXPECT_TRUE(FilePath(\".\").DirectoryExists());\n  EXPECT_TRUE(FilePath(\".\\\\\").DirectoryExists());\n\n#endif  // _WIN32_CE\n#else\n  EXPECT_TRUE(FilePath(\".\").DirectoryExists());\n  EXPECT_TRUE(FilePath(\"./\").DirectoryExists());\n#endif  // GTEST_OS_WINDOWS\n}\n\n// \"foo/bar\" == foo//bar\" == \"foo///bar\"\nTEST(NormalizeTest, MultipleConsecutiveSeparatorsInMidstring) {\n  EXPECT_EQ(\"foo\" GTEST_PATH_SEP_ \"bar\",\n            FilePath(\"foo\" GTEST_PATH_SEP_ \"bar\").string());\n  EXPECT_EQ(\"foo\" GTEST_PATH_SEP_ \"bar\",\n            FilePath(\"foo\" GTEST_PATH_SEP_ GTEST_PATH_SEP_ \"bar\").string());\n  EXPECT_EQ(\n      \"foo\" GTEST_PATH_SEP_ \"bar\",\n      FilePath(\"foo\" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ \"bar\")\n          .string());\n}\n\n// \"/bar\" == //bar\" == \"///bar\"\nTEST(NormalizeTest, MultipleConsecutiveSeparatorsAtStringStart) {\n  EXPECT_EQ(GTEST_PATH_SEP_ \"bar\", FilePath(GTEST_PATH_SEP_ \"bar\").string());\n  EXPECT_EQ(GTEST_PATH_SEP_ \"bar\",\n            FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ \"bar\").string());\n  EXPECT_EQ(\n      GTEST_PATH_SEP_ \"bar\",\n      FilePath(GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_ \"bar\").string());\n}\n\n// \"foo/\" == foo//\" == \"foo///\"\nTEST(NormalizeTest, MultipleConsecutiveSeparatorsAtStringEnd) {\n  EXPECT_EQ(\"foo\" GTEST_PATH_SEP_, FilePath(\"foo\" GTEST_PATH_SEP_).string());\n  EXPECT_EQ(\"foo\" GTEST_PATH_SEP_,\n            FilePath(\"foo\" GTEST_PATH_SEP_ GTEST_PATH_SEP_).string());\n  EXPECT_EQ(\n      \"foo\" GTEST_PATH_SEP_,\n      FilePath(\"foo\" GTEST_PATH_SEP_ GTEST_PATH_SEP_ GTEST_PATH_SEP_).string());\n}\n\n#if GTEST_HAS_ALT_PATH_SEP_\n\n// Tests that separators at the end of the string are normalized\n// regardless of their combination (e.g. \"foo\\\" ==\"foo/\\\" ==\n// \"foo\\\\/\").\nTEST(NormalizeTest, MixAlternateSeparatorAtStringEnd) {\n  EXPECT_EQ(\"foo\" GTEST_PATH_SEP_, FilePath(\"foo/\").string());\n  EXPECT_EQ(\"foo\" GTEST_PATH_SEP_,\n            FilePath(\"foo\" GTEST_PATH_SEP_ \"/\").string());\n  EXPECT_EQ(\"foo\" GTEST_PATH_SEP_, FilePath(\"foo//\" GTEST_PATH_SEP_).string());\n}\n\n#endif\n\nTEST(AssignmentOperatorTest, DefaultAssignedToNonDefault) {\n  FilePath default_path;\n  FilePath non_default_path(\"path\");\n  non_default_path = default_path;\n  EXPECT_EQ(\"\", non_default_path.string());\n  EXPECT_EQ(\"\", default_path.string());  // RHS var is unchanged.\n}\n\nTEST(AssignmentOperatorTest, NonDefaultAssignedToDefault) {\n  FilePath non_default_path(\"path\");\n  FilePath default_path;\n  default_path = non_default_path;\n  EXPECT_EQ(\"path\", default_path.string());\n  EXPECT_EQ(\"path\", non_default_path.string());  // RHS var is unchanged.\n}\n\nTEST(AssignmentOperatorTest, ConstAssignedToNonConst) {\n  const FilePath const_default_path(\"const_path\");\n  FilePath non_default_path(\"path\");\n  non_default_path = const_default_path;\n  EXPECT_EQ(\"const_path\", non_default_path.string());\n}\n\nclass DirectoryCreationTest : public Test {\n protected:\n  void SetUp() override {\n    testdata_path_.Set(\n        FilePath(TempDir() + GetCurrentExecutableName().string() +\n                 \"_directory_creation\" GTEST_PATH_SEP_ \"test\" GTEST_PATH_SEP_));\n    testdata_file_.Set(testdata_path_.RemoveTrailingPathSeparator());\n\n    unique_file0_.Set(\n        FilePath::MakeFileName(testdata_path_, FilePath(\"unique\"), 0, \"txt\"));\n    unique_file1_.Set(\n        FilePath::MakeFileName(testdata_path_, FilePath(\"unique\"), 1, \"txt\"));\n\n    remove(testdata_file_.c_str());\n    remove(unique_file0_.c_str());\n    remove(unique_file1_.c_str());\n    posix::RmDir(testdata_path_.c_str());\n  }\n\n  void TearDown() override {\n    remove(testdata_file_.c_str());\n    remove(unique_file0_.c_str());\n    remove(unique_file1_.c_str());\n    posix::RmDir(testdata_path_.c_str());\n  }\n\n  void CreateTextFile(const char* filename) {\n    FILE* f = posix::FOpen(filename, \"w\");\n    fprintf(f, \"text\\n\");\n    fclose(f);\n  }\n\n  // Strings representing a directory and a file, with identical paths\n  // except for the trailing separator character that distinquishes\n  // a directory named 'test' from a file named 'test'. Example names:\n  FilePath testdata_path_;  // \"/tmp/directory_creation/test/\"\n  FilePath testdata_file_;  // \"/tmp/directory_creation/test\"\n  FilePath unique_file0_;   // \"/tmp/directory_creation/test/unique.txt\"\n  FilePath unique_file1_;   // \"/tmp/directory_creation/test/unique_1.txt\"\n};\n\nTEST_F(DirectoryCreationTest, CreateDirectoriesRecursively) {\n  EXPECT_FALSE(testdata_path_.DirectoryExists()) << testdata_path_.string();\n  EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively());\n  EXPECT_TRUE(testdata_path_.DirectoryExists());\n}\n\nTEST_F(DirectoryCreationTest, CreateDirectoriesForAlreadyExistingPath) {\n  EXPECT_FALSE(testdata_path_.DirectoryExists()) << testdata_path_.string();\n  EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively());\n  // Call 'create' again... should still succeed.\n  EXPECT_TRUE(testdata_path_.CreateDirectoriesRecursively());\n}\n\nTEST_F(DirectoryCreationTest, CreateDirectoriesAndUniqueFilename) {\n  FilePath file_path(FilePath::GenerateUniqueFileName(\n      testdata_path_, FilePath(\"unique\"), \"txt\"));\n  EXPECT_EQ(unique_file0_.string(), file_path.string());\n  EXPECT_FALSE(file_path.FileOrDirectoryExists());  // file not there\n\n  testdata_path_.CreateDirectoriesRecursively();\n  EXPECT_FALSE(file_path.FileOrDirectoryExists());  // file still not there\n  CreateTextFile(file_path.c_str());\n  EXPECT_TRUE(file_path.FileOrDirectoryExists());\n\n  FilePath file_path2(FilePath::GenerateUniqueFileName(\n      testdata_path_, FilePath(\"unique\"), \"txt\"));\n  EXPECT_EQ(unique_file1_.string(), file_path2.string());\n  EXPECT_FALSE(file_path2.FileOrDirectoryExists());  // file not there\n  CreateTextFile(file_path2.c_str());\n  EXPECT_TRUE(file_path2.FileOrDirectoryExists());\n}\n\nTEST_F(DirectoryCreationTest, CreateDirectoriesFail) {\n  // force a failure by putting a file where we will try to create a directory.\n  CreateTextFile(testdata_file_.c_str());\n  EXPECT_TRUE(testdata_file_.FileOrDirectoryExists());\n  EXPECT_FALSE(testdata_file_.DirectoryExists());\n  EXPECT_FALSE(testdata_file_.CreateDirectoriesRecursively());\n}\n\nTEST(NoDirectoryCreationTest, CreateNoDirectoriesForDefaultXmlFile) {\n  const FilePath test_detail_xml(\"test_detail.xml\");\n  EXPECT_FALSE(test_detail_xml.CreateDirectoriesRecursively());\n}\n\nTEST(FilePathTest, DefaultConstructor) {\n  FilePath fp;\n  EXPECT_EQ(\"\", fp.string());\n}\n\nTEST(FilePathTest, CharAndCopyConstructors) {\n  const FilePath fp(\"spicy\");\n  EXPECT_EQ(\"spicy\", fp.string());\n\n  const FilePath fp_copy(fp);\n  EXPECT_EQ(\"spicy\", fp_copy.string());\n}\n\nTEST(FilePathTest, StringConstructor) {\n  const FilePath fp(std::string(\"cider\"));\n  EXPECT_EQ(\"cider\", fp.string());\n}\n\nTEST(FilePathTest, Set) {\n  const FilePath apple(\"apple\");\n  FilePath mac(\"mac\");\n  mac.Set(apple);  // Implement Set() since overloading operator= is forbidden.\n  EXPECT_EQ(\"apple\", mac.string());\n  EXPECT_EQ(\"apple\", apple.string());\n}\n\nTEST(FilePathTest, ToString) {\n  const FilePath file(\"drink\");\n  EXPECT_EQ(\"drink\", file.string());\n}\n\nTEST(FilePathTest, RemoveExtension) {\n  EXPECT_EQ(\"app\", FilePath(\"app.cc\").RemoveExtension(\"cc\").string());\n  EXPECT_EQ(\"app\", FilePath(\"app.exe\").RemoveExtension(\"exe\").string());\n  EXPECT_EQ(\"APP\", FilePath(\"APP.EXE\").RemoveExtension(\"exe\").string());\n}\n\nTEST(FilePathTest, RemoveExtensionWhenThereIsNoExtension) {\n  EXPECT_EQ(\"app\", FilePath(\"app\").RemoveExtension(\"exe\").string());\n}\n\nTEST(FilePathTest, IsDirectory) {\n  EXPECT_FALSE(FilePath(\"cola\").IsDirectory());\n  EXPECT_TRUE(FilePath(\"koala\" GTEST_PATH_SEP_).IsDirectory());\n#if GTEST_HAS_ALT_PATH_SEP_\n  EXPECT_TRUE(FilePath(\"koala/\").IsDirectory());\n#endif\n}\n\nTEST(FilePathTest, IsAbsolutePath) {\n  EXPECT_FALSE(FilePath(\"is\" GTEST_PATH_SEP_ \"relative\").IsAbsolutePath());\n  EXPECT_FALSE(FilePath(\"\").IsAbsolutePath());\n#if GTEST_OS_WINDOWS\n  EXPECT_TRUE(\n      FilePath(\"c:\\\\\" GTEST_PATH_SEP_ \"is_not\" GTEST_PATH_SEP_ \"relative\")\n          .IsAbsolutePath());\n  EXPECT_FALSE(FilePath(\"c:foo\" GTEST_PATH_SEP_ \"bar\").IsAbsolutePath());\n  EXPECT_TRUE(\n      FilePath(\"c:/\" GTEST_PATH_SEP_ \"is_not\" GTEST_PATH_SEP_ \"relative\")\n          .IsAbsolutePath());\n#else\n  EXPECT_TRUE(FilePath(GTEST_PATH_SEP_ \"is_not\" GTEST_PATH_SEP_ \"relative\")\n                  .IsAbsolutePath());\n#endif  // GTEST_OS_WINDOWS\n}\n\nTEST(FilePathTest, IsRootDirectory) {\n#if GTEST_OS_WINDOWS\n  EXPECT_TRUE(FilePath(\"a:\\\\\").IsRootDirectory());\n  EXPECT_TRUE(FilePath(\"Z:/\").IsRootDirectory());\n  EXPECT_TRUE(FilePath(\"e://\").IsRootDirectory());\n  EXPECT_FALSE(FilePath(\"\").IsRootDirectory());\n  EXPECT_FALSE(FilePath(\"b:\").IsRootDirectory());\n  EXPECT_FALSE(FilePath(\"b:a\").IsRootDirectory());\n  EXPECT_FALSE(FilePath(\"8:/\").IsRootDirectory());\n  EXPECT_FALSE(FilePath(\"c|/\").IsRootDirectory());\n#else\n  EXPECT_TRUE(FilePath(\"/\").IsRootDirectory());\n  EXPECT_TRUE(FilePath(\"//\").IsRootDirectory());\n  EXPECT_FALSE(FilePath(\"\").IsRootDirectory());\n  EXPECT_FALSE(FilePath(\"\\\\\").IsRootDirectory());\n  EXPECT_FALSE(FilePath(\"/x\").IsRootDirectory());\n#endif\n}\n\n}  // namespace\n}  // namespace internal\n}  // namespace testing\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-filter-unittest.py",
    "content": "#!/usr/bin/env python\n#\n# Copyright 2005 Google Inc. All Rights Reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Unit test for Google Test test filters.\n\nA user can specify which test(s) in a Google Test program to run via either\nthe GTEST_FILTER environment variable or the --gtest_filter flag.\nThis script tests such functionality by invoking\ngoogletest-filter-unittest_ (a program written with Google Test) with different\nenvironments and command line flags.\n\nNote that test sharding may also influence which tests are filtered. Therefore,\nwe test that here also.\n\"\"\"\n\nimport os\nimport re\ntry:\n  from sets import Set as set  # For Python 2.3 compatibility\nexcept ImportError:\n  pass\nimport sys\nfrom googletest.test import gtest_test_utils\n\n# Constants.\n\n# Checks if this platform can pass empty environment variables to child\n# processes.  We set an env variable to an empty string and invoke a python\n# script in a subprocess to print whether the variable is STILL in\n# os.environ.  We then use 'eval' to parse the child's output so that an\n# exception is thrown if the input is anything other than 'True' nor 'False'.\nCAN_PASS_EMPTY_ENV = False\nif sys.executable:\n  os.environ['EMPTY_VAR'] = ''\n  child = gtest_test_utils.Subprocess(\n      [sys.executable, '-c', 'import os; print(\\'EMPTY_VAR\\' in os.environ)'])\n  CAN_PASS_EMPTY_ENV = eval(child.output)\n\n\n# Check if this platform can unset environment variables in child processes.\n# We set an env variable to a non-empty string, unset it, and invoke\n# a python script in a subprocess to print whether the variable\n# is NO LONGER in os.environ.\n# We use 'eval' to parse the child's output so that an exception\n# is thrown if the input is neither 'True' nor 'False'.\nCAN_UNSET_ENV = False\nif sys.executable:\n  os.environ['UNSET_VAR'] = 'X'\n  del os.environ['UNSET_VAR']\n  child = gtest_test_utils.Subprocess(\n      [sys.executable, '-c', 'import os; print(\\'UNSET_VAR\\' not in os.environ)'\n      ])\n  CAN_UNSET_ENV = eval(child.output)\n\n\n# Checks if we should test with an empty filter. This doesn't\n# make sense on platforms that cannot pass empty env variables (Win32)\n# and on platforms that cannot unset variables (since we cannot tell\n# the difference between \"\" and NULL -- Borland and Solaris < 5.10)\nCAN_TEST_EMPTY_FILTER = (CAN_PASS_EMPTY_ENV and CAN_UNSET_ENV)\n\n\n# The environment variable for specifying the test filters.\nFILTER_ENV_VAR = 'GTEST_FILTER'\n\n# The environment variables for test sharding.\nTOTAL_SHARDS_ENV_VAR = 'GTEST_TOTAL_SHARDS'\nSHARD_INDEX_ENV_VAR = 'GTEST_SHARD_INDEX'\nSHARD_STATUS_FILE_ENV_VAR = 'GTEST_SHARD_STATUS_FILE'\n\n# The command line flag for specifying the test filters.\nFILTER_FLAG = 'gtest_filter'\n\n# The command line flag for including disabled tests.\nALSO_RUN_DISABLED_TESTS_FLAG = 'gtest_also_run_disabled_tests'\n\n# Command to run the googletest-filter-unittest_ program.\nCOMMAND = gtest_test_utils.GetTestExecutablePath('googletest-filter-unittest_')\n\n# Regex for determining whether parameterized tests are enabled in the binary.\nPARAM_TEST_REGEX = re.compile(r'/ParamTest')\n\n# Regex for parsing test case names from Google Test's output.\nTEST_CASE_REGEX = re.compile(r'^\\[\\-+\\] \\d+ tests? from (\\w+(/\\w+)?)')\n\n# Regex for parsing test names from Google Test's output.\nTEST_REGEX = re.compile(r'^\\[\\s*RUN\\s*\\].*\\.(\\w+(/\\w+)?)')\n\n# Regex for parsing disabled banner from Google Test's output\nDISABLED_BANNER_REGEX = re.compile(r'^\\[\\s*DISABLED\\s*\\] (.*)')\n\n# The command line flag to tell Google Test to output the list of tests it\n# will run.\nLIST_TESTS_FLAG = '--gtest_list_tests'\n\n# Indicates whether Google Test supports death tests.\nSUPPORTS_DEATH_TESTS = 'HasDeathTest' in gtest_test_utils.Subprocess(\n    [COMMAND, LIST_TESTS_FLAG]).output\n\n# Full names of all tests in googletest-filter-unittests_.\nPARAM_TESTS = [\n    'SeqP/ParamTest.TestX/0',\n    'SeqP/ParamTest.TestX/1',\n    'SeqP/ParamTest.TestY/0',\n    'SeqP/ParamTest.TestY/1',\n    'SeqQ/ParamTest.TestX/0',\n    'SeqQ/ParamTest.TestX/1',\n    'SeqQ/ParamTest.TestY/0',\n    'SeqQ/ParamTest.TestY/1',\n    ]\n\nDISABLED_TESTS = [\n    'BarTest.DISABLED_TestFour',\n    'BarTest.DISABLED_TestFive',\n    'BazTest.DISABLED_TestC',\n    'DISABLED_FoobarTest.Test1',\n    'DISABLED_FoobarTest.DISABLED_Test2',\n    'DISABLED_FoobarbazTest.TestA',\n    ]\n\nif SUPPORTS_DEATH_TESTS:\n  DEATH_TESTS = [\n    'HasDeathTest.Test1',\n    'HasDeathTest.Test2',\n    ]\nelse:\n  DEATH_TESTS = []\n\n# All the non-disabled tests.\nACTIVE_TESTS = [\n    'FooTest.Abc',\n    'FooTest.Xyz',\n\n    'BarTest.TestOne',\n    'BarTest.TestTwo',\n    'BarTest.TestThree',\n\n    'BazTest.TestOne',\n    'BazTest.TestA',\n    'BazTest.TestB',\n    ] + DEATH_TESTS + PARAM_TESTS\n\nparam_tests_present = None\n\n# Utilities.\n\nenviron = os.environ.copy()\n\n\ndef SetEnvVar(env_var, value):\n  \"\"\"Sets the env variable to 'value'; unsets it when 'value' is None.\"\"\"\n\n  if value is not None:\n    environ[env_var] = value\n  elif env_var in environ:\n    del environ[env_var]\n\n\ndef RunAndReturnOutput(args = None):\n  \"\"\"Runs the test program and returns its output.\"\"\"\n\n  return gtest_test_utils.Subprocess([COMMAND] + (args or []),\n                                     env=environ).output\n\n\ndef RunAndExtractTestList(args = None):\n  \"\"\"Runs the test program and returns its exit code and a list of tests run.\"\"\"\n\n  p = gtest_test_utils.Subprocess([COMMAND] + (args or []), env=environ)\n  tests_run = []\n  test_case = ''\n  test = ''\n  for line in p.output.split('\\n'):\n    match = TEST_CASE_REGEX.match(line)\n    if match is not None:\n      test_case = match.group(1)\n    else:\n      match = TEST_REGEX.match(line)\n      if match is not None:\n        test = match.group(1)\n        tests_run.append(test_case + '.' + test)\n  return (tests_run, p.exit_code)\n\n\ndef RunAndExtractDisabledBannerList(args=None):\n  \"\"\"Runs the test program and returns tests that printed a disabled banner.\"\"\"\n  p = gtest_test_utils.Subprocess([COMMAND] + (args or []), env=environ)\n  banners_printed = []\n  for line in p.output.split('\\n'):\n    match = DISABLED_BANNER_REGEX.match(line)\n    if match is not None:\n      banners_printed.append(match.group(1))\n  return banners_printed\n\n\ndef InvokeWithModifiedEnv(extra_env, function, *args, **kwargs):\n  \"\"\"Runs the given function and arguments in a modified environment.\"\"\"\n  try:\n    original_env = environ.copy()\n    environ.update(extra_env)\n    return function(*args, **kwargs)\n  finally:\n    environ.clear()\n    environ.update(original_env)\n\n\ndef RunWithSharding(total_shards, shard_index, command):\n  \"\"\"Runs a test program shard and returns exit code and a list of tests run.\"\"\"\n\n  extra_env = {SHARD_INDEX_ENV_VAR: str(shard_index),\n               TOTAL_SHARDS_ENV_VAR: str(total_shards)}\n  return InvokeWithModifiedEnv(extra_env, RunAndExtractTestList, command)\n\n# The unit test.\n\n\nclass GTestFilterUnitTest(gtest_test_utils.TestCase):\n  \"\"\"Tests the env variable or the command line flag to filter tests.\"\"\"\n\n  # Utilities.\n\n  def AssertSetEqual(self, lhs, rhs):\n    \"\"\"Asserts that two sets are equal.\"\"\"\n\n    for elem in lhs:\n      self.assert_(elem in rhs, '%s in %s' % (elem, rhs))\n\n    for elem in rhs:\n      self.assert_(elem in lhs, '%s in %s' % (elem, lhs))\n\n  def AssertPartitionIsValid(self, set_var, list_of_sets):\n    \"\"\"Asserts that list_of_sets is a valid partition of set_var.\"\"\"\n\n    full_partition = []\n    for slice_var in list_of_sets:\n      full_partition.extend(slice_var)\n    self.assertEqual(len(set_var), len(full_partition))\n    self.assertEqual(set(set_var), set(full_partition))\n\n  def AdjustForParameterizedTests(self, tests_to_run):\n    \"\"\"Adjust tests_to_run in case value parameterized tests are disabled.\"\"\"\n\n    global param_tests_present\n    if not param_tests_present:\n      return list(set(tests_to_run) - set(PARAM_TESTS))\n    else:\n      return tests_to_run\n\n  def RunAndVerify(self, gtest_filter, tests_to_run):\n    \"\"\"Checks that the binary runs correct set of tests for a given filter.\"\"\"\n\n    tests_to_run = self.AdjustForParameterizedTests(tests_to_run)\n\n    # First, tests using the environment variable.\n\n    # Windows removes empty variables from the environment when passing it\n    # to a new process.  This means it is impossible to pass an empty filter\n    # into a process using the environment variable.  However, we can still\n    # test the case when the variable is not supplied (i.e., gtest_filter is\n    # None).\n    # pylint: disable-msg=C6403\n    if CAN_TEST_EMPTY_FILTER or gtest_filter != '':\n      SetEnvVar(FILTER_ENV_VAR, gtest_filter)\n      tests_run = RunAndExtractTestList()[0]\n      SetEnvVar(FILTER_ENV_VAR, None)\n      self.AssertSetEqual(tests_run, tests_to_run)\n    # pylint: enable-msg=C6403\n\n    # Next, tests using the command line flag.\n\n    if gtest_filter is None:\n      args = []\n    else:\n      args = ['--%s=%s' % (FILTER_FLAG, gtest_filter)]\n\n    tests_run = RunAndExtractTestList(args)[0]\n    self.AssertSetEqual(tests_run, tests_to_run)\n\n  def RunAndVerifyWithSharding(self, gtest_filter, total_shards, tests_to_run,\n                               args=None, check_exit_0=False):\n    \"\"\"Checks that binary runs correct tests for the given filter and shard.\n\n    Runs all shards of googletest-filter-unittest_ with the given filter, and\n    verifies that the right set of tests were run. The union of tests run\n    on each shard should be identical to tests_to_run, without duplicates.\n    If check_exit_0, .\n\n    Args:\n      gtest_filter: A filter to apply to the tests.\n      total_shards: A total number of shards to split test run into.\n      tests_to_run: A set of tests expected to run.\n      args   :      Arguments to pass to the to the test binary.\n      check_exit_0: When set to a true value, make sure that all shards\n                    return 0.\n    \"\"\"\n\n    tests_to_run = self.AdjustForParameterizedTests(tests_to_run)\n\n    # Windows removes empty variables from the environment when passing it\n    # to a new process.  This means it is impossible to pass an empty filter\n    # into a process using the environment variable.  However, we can still\n    # test the case when the variable is not supplied (i.e., gtest_filter is\n    # None).\n    # pylint: disable-msg=C6403\n    if CAN_TEST_EMPTY_FILTER or gtest_filter != '':\n      SetEnvVar(FILTER_ENV_VAR, gtest_filter)\n      partition = []\n      for i in range(0, total_shards):\n        (tests_run, exit_code) = RunWithSharding(total_shards, i, args)\n        if check_exit_0:\n          self.assertEqual(0, exit_code)\n        partition.append(tests_run)\n\n      self.AssertPartitionIsValid(tests_to_run, partition)\n      SetEnvVar(FILTER_ENV_VAR, None)\n    # pylint: enable-msg=C6403\n\n  def RunAndVerifyAllowingDisabled(self, gtest_filter, tests_to_run):\n    \"\"\"Checks that the binary runs correct set of tests for the given filter.\n\n    Runs googletest-filter-unittest_ with the given filter, and enables\n    disabled tests. Verifies that the right set of tests were run.\n\n    Args:\n      gtest_filter: A filter to apply to the tests.\n      tests_to_run: A set of tests expected to run.\n    \"\"\"\n\n    tests_to_run = self.AdjustForParameterizedTests(tests_to_run)\n\n    # Construct the command line.\n    args = ['--%s' % ALSO_RUN_DISABLED_TESTS_FLAG]\n    if gtest_filter is not None:\n      args.append('--%s=%s' % (FILTER_FLAG, gtest_filter))\n\n    tests_run = RunAndExtractTestList(args)[0]\n    self.AssertSetEqual(tests_run, tests_to_run)\n\n  def setUp(self):\n    \"\"\"Sets up test case.\n\n    Determines whether value-parameterized tests are enabled in the binary and\n    sets the flags accordingly.\n    \"\"\"\n\n    global param_tests_present\n    if param_tests_present is None:\n      param_tests_present = PARAM_TEST_REGEX.search(\n          RunAndReturnOutput()) is not None\n\n  def testDefaultBehavior(self):\n    \"\"\"Tests the behavior of not specifying the filter.\"\"\"\n\n    self.RunAndVerify(None, ACTIVE_TESTS)\n\n  def testDefaultBehaviorWithShards(self):\n    \"\"\"Tests the behavior without the filter, with sharding enabled.\"\"\"\n\n    self.RunAndVerifyWithSharding(None, 1, ACTIVE_TESTS)\n    self.RunAndVerifyWithSharding(None, 2, ACTIVE_TESTS)\n    self.RunAndVerifyWithSharding(None, len(ACTIVE_TESTS) - 1, ACTIVE_TESTS)\n    self.RunAndVerifyWithSharding(None, len(ACTIVE_TESTS), ACTIVE_TESTS)\n    self.RunAndVerifyWithSharding(None, len(ACTIVE_TESTS) + 1, ACTIVE_TESTS)\n\n  def testEmptyFilter(self):\n    \"\"\"Tests an empty filter.\"\"\"\n\n    self.RunAndVerify('', [])\n    self.RunAndVerifyWithSharding('', 1, [])\n    self.RunAndVerifyWithSharding('', 2, [])\n\n  def testBadFilter(self):\n    \"\"\"Tests a filter that matches nothing.\"\"\"\n\n    self.RunAndVerify('BadFilter', [])\n    self.RunAndVerifyAllowingDisabled('BadFilter', [])\n\n  def testFullName(self):\n    \"\"\"Tests filtering by full name.\"\"\"\n\n    self.RunAndVerify('FooTest.Xyz', ['FooTest.Xyz'])\n    self.RunAndVerifyAllowingDisabled('FooTest.Xyz', ['FooTest.Xyz'])\n    self.RunAndVerifyWithSharding('FooTest.Xyz', 5, ['FooTest.Xyz'])\n\n  def testUniversalFilters(self):\n    \"\"\"Tests filters that match everything.\"\"\"\n\n    self.RunAndVerify('*', ACTIVE_TESTS)\n    self.RunAndVerify('*.*', ACTIVE_TESTS)\n    self.RunAndVerifyWithSharding('*.*', len(ACTIVE_TESTS) - 3, ACTIVE_TESTS)\n    self.RunAndVerifyAllowingDisabled('*', ACTIVE_TESTS + DISABLED_TESTS)\n    self.RunAndVerifyAllowingDisabled('*.*', ACTIVE_TESTS + DISABLED_TESTS)\n\n  def testFilterByTestCase(self):\n    \"\"\"Tests filtering by test case name.\"\"\"\n\n    self.RunAndVerify('FooTest.*', ['FooTest.Abc', 'FooTest.Xyz'])\n\n    BAZ_TESTS = ['BazTest.TestOne', 'BazTest.TestA', 'BazTest.TestB']\n    self.RunAndVerify('BazTest.*', BAZ_TESTS)\n    self.RunAndVerifyAllowingDisabled('BazTest.*',\n                                      BAZ_TESTS + ['BazTest.DISABLED_TestC'])\n\n  def testFilterByTest(self):\n    \"\"\"Tests filtering by test name.\"\"\"\n\n    self.RunAndVerify('*.TestOne', ['BarTest.TestOne', 'BazTest.TestOne'])\n\n  def testFilterDisabledTests(self):\n    \"\"\"Select only the disabled tests to run.\"\"\"\n\n    self.RunAndVerify('DISABLED_FoobarTest.Test1', [])\n    self.RunAndVerifyAllowingDisabled('DISABLED_FoobarTest.Test1',\n                                      ['DISABLED_FoobarTest.Test1'])\n\n    self.RunAndVerify('*DISABLED_*', [])\n    self.RunAndVerifyAllowingDisabled('*DISABLED_*', DISABLED_TESTS)\n\n    self.RunAndVerify('*.DISABLED_*', [])\n    self.RunAndVerifyAllowingDisabled('*.DISABLED_*', [\n        'BarTest.DISABLED_TestFour',\n        'BarTest.DISABLED_TestFive',\n        'BazTest.DISABLED_TestC',\n        'DISABLED_FoobarTest.DISABLED_Test2',\n        ])\n\n    self.RunAndVerify('DISABLED_*', [])\n    self.RunAndVerifyAllowingDisabled('DISABLED_*', [\n        'DISABLED_FoobarTest.Test1',\n        'DISABLED_FoobarTest.DISABLED_Test2',\n        'DISABLED_FoobarbazTest.TestA',\n        ])\n\n  def testWildcardInTestCaseName(self):\n    \"\"\"Tests using wildcard in the test case name.\"\"\"\n\n    self.RunAndVerify('*a*.*', [\n        'BarTest.TestOne',\n        'BarTest.TestTwo',\n        'BarTest.TestThree',\n\n        'BazTest.TestOne',\n        'BazTest.TestA',\n        'BazTest.TestB', ] + DEATH_TESTS + PARAM_TESTS)\n\n  def testWildcardInTestName(self):\n    \"\"\"Tests using wildcard in the test name.\"\"\"\n\n    self.RunAndVerify('*.*A*', ['FooTest.Abc', 'BazTest.TestA'])\n\n  def testFilterWithoutDot(self):\n    \"\"\"Tests a filter that has no '.' in it.\"\"\"\n\n    self.RunAndVerify('*z*', [\n        'FooTest.Xyz',\n\n        'BazTest.TestOne',\n        'BazTest.TestA',\n        'BazTest.TestB',\n        ])\n\n  def testTwoPatterns(self):\n    \"\"\"Tests filters that consist of two patterns.\"\"\"\n\n    self.RunAndVerify('Foo*.*:*A*', [\n        'FooTest.Abc',\n        'FooTest.Xyz',\n\n        'BazTest.TestA',\n        ])\n\n    # An empty pattern + a non-empty one\n    self.RunAndVerify(':*A*', ['FooTest.Abc', 'BazTest.TestA'])\n\n  def testThreePatterns(self):\n    \"\"\"Tests filters that consist of three patterns.\"\"\"\n\n    self.RunAndVerify('*oo*:*A*:*One', [\n        'FooTest.Abc',\n        'FooTest.Xyz',\n\n        'BarTest.TestOne',\n\n        'BazTest.TestOne',\n        'BazTest.TestA',\n        ])\n\n    # The 2nd pattern is empty.\n    self.RunAndVerify('*oo*::*One', [\n        'FooTest.Abc',\n        'FooTest.Xyz',\n\n        'BarTest.TestOne',\n\n        'BazTest.TestOne',\n        ])\n\n    # The last 2 patterns are empty.\n    self.RunAndVerify('*oo*::', [\n        'FooTest.Abc',\n        'FooTest.Xyz',\n        ])\n\n  def testNegativeFilters(self):\n    self.RunAndVerify('*-BazTest.TestOne', [\n        'FooTest.Abc',\n        'FooTest.Xyz',\n\n        'BarTest.TestOne',\n        'BarTest.TestTwo',\n        'BarTest.TestThree',\n\n        'BazTest.TestA',\n        'BazTest.TestB',\n        ] + DEATH_TESTS + PARAM_TESTS)\n\n    self.RunAndVerify('*-FooTest.Abc:BazTest.*', [\n        'FooTest.Xyz',\n\n        'BarTest.TestOne',\n        'BarTest.TestTwo',\n        'BarTest.TestThree',\n        ] + DEATH_TESTS + PARAM_TESTS)\n\n    self.RunAndVerify('BarTest.*-BarTest.TestOne', [\n        'BarTest.TestTwo',\n        'BarTest.TestThree',\n        ])\n\n    # Tests without leading '*'.\n    self.RunAndVerify('-FooTest.Abc:FooTest.Xyz:BazTest.*', [\n        'BarTest.TestOne',\n        'BarTest.TestTwo',\n        'BarTest.TestThree',\n        ] + DEATH_TESTS + PARAM_TESTS)\n\n    # Value parameterized tests.\n    self.RunAndVerify('*/*', PARAM_TESTS)\n\n    # Value parameterized tests filtering by the sequence name.\n    self.RunAndVerify('SeqP/*', [\n        'SeqP/ParamTest.TestX/0',\n        'SeqP/ParamTest.TestX/1',\n        'SeqP/ParamTest.TestY/0',\n        'SeqP/ParamTest.TestY/1',\n        ])\n\n    # Value parameterized tests filtering by the test name.\n    self.RunAndVerify('*/0', [\n        'SeqP/ParamTest.TestX/0',\n        'SeqP/ParamTest.TestY/0',\n        'SeqQ/ParamTest.TestX/0',\n        'SeqQ/ParamTest.TestY/0',\n        ])\n\n  def testFlagOverridesEnvVar(self):\n    \"\"\"Tests that the filter flag overrides the filtering env. variable.\"\"\"\n\n    SetEnvVar(FILTER_ENV_VAR, 'Foo*')\n    args = ['--%s=%s' % (FILTER_FLAG, '*One')]\n    tests_run = RunAndExtractTestList(args)[0]\n    SetEnvVar(FILTER_ENV_VAR, None)\n\n    self.AssertSetEqual(tests_run, ['BarTest.TestOne', 'BazTest.TestOne'])\n\n  def testShardStatusFileIsCreated(self):\n    \"\"\"Tests that the shard file is created if specified in the environment.\"\"\"\n\n    shard_status_file = os.path.join(gtest_test_utils.GetTempDir(),\n                                     'shard_status_file')\n    self.assert_(not os.path.exists(shard_status_file))\n\n    extra_env = {SHARD_STATUS_FILE_ENV_VAR: shard_status_file}\n    try:\n      InvokeWithModifiedEnv(extra_env, RunAndReturnOutput)\n    finally:\n      self.assert_(os.path.exists(shard_status_file))\n      os.remove(shard_status_file)\n\n  def testShardStatusFileIsCreatedWithListTests(self):\n    \"\"\"Tests that the shard file is created with the \"list_tests\" flag.\"\"\"\n\n    shard_status_file = os.path.join(gtest_test_utils.GetTempDir(),\n                                     'shard_status_file2')\n    self.assert_(not os.path.exists(shard_status_file))\n\n    extra_env = {SHARD_STATUS_FILE_ENV_VAR: shard_status_file}\n    try:\n      output = InvokeWithModifiedEnv(extra_env,\n                                     RunAndReturnOutput,\n                                     [LIST_TESTS_FLAG])\n    finally:\n      # This assertion ensures that Google Test enumerated the tests as\n      # opposed to running them.\n      self.assert_('[==========]' not in output,\n                   'Unexpected output during test enumeration.\\n'\n                   'Please ensure that LIST_TESTS_FLAG is assigned the\\n'\n                   'correct flag value for listing Google Test tests.')\n\n      self.assert_(os.path.exists(shard_status_file))\n      os.remove(shard_status_file)\n\n  def testDisabledBanner(self):\n    \"\"\"Tests that the disabled banner prints only tests that match filter.\"\"\"\n    make_filter = lambda s: ['--%s=%s' % (FILTER_FLAG, s)]\n\n    banners = RunAndExtractDisabledBannerList(make_filter('*'))\n    self.AssertSetEqual(banners, [\n        'BarTest.DISABLED_TestFour', 'BarTest.DISABLED_TestFive',\n        'BazTest.DISABLED_TestC'\n    ])\n\n    banners = RunAndExtractDisabledBannerList(make_filter('Bar*'))\n    self.AssertSetEqual(\n        banners, ['BarTest.DISABLED_TestFour', 'BarTest.DISABLED_TestFive'])\n\n    banners = RunAndExtractDisabledBannerList(make_filter('*-Bar*'))\n    self.AssertSetEqual(banners, ['BazTest.DISABLED_TestC'])\n\n  if SUPPORTS_DEATH_TESTS:\n    def testShardingWorksWithDeathTests(self):\n      \"\"\"Tests integration with death tests and sharding.\"\"\"\n\n      gtest_filter = 'HasDeathTest.*:SeqP/*'\n      expected_tests = [\n          'HasDeathTest.Test1',\n          'HasDeathTest.Test2',\n\n          'SeqP/ParamTest.TestX/0',\n          'SeqP/ParamTest.TestX/1',\n          'SeqP/ParamTest.TestY/0',\n          'SeqP/ParamTest.TestY/1',\n          ]\n\n      for flag in ['--gtest_death_test_style=threadsafe',\n                   '--gtest_death_test_style=fast']:\n        self.RunAndVerifyWithSharding(gtest_filter, 3, expected_tests,\n                                      check_exit_0=True, args=[flag])\n        self.RunAndVerifyWithSharding(gtest_filter, 5, expected_tests,\n                                      check_exit_0=True, args=[flag])\n\nif __name__ == '__main__':\n  gtest_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-filter-unittest_.cc",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Unit test for Google Test test filters.\n//\n// A user can specify which test(s) in a Google Test program to run via\n// either the GTEST_FILTER environment variable or the --gtest_filter\n// flag.  This is used for testing such functionality.\n//\n// The program will be invoked from a Python unit test.  Don't run it\n// directly.\n\n#include \"gtest/gtest.h\"\n\nnamespace {\n\n// Test case FooTest.\n\nclass FooTest : public testing::Test {};\n\nTEST_F(FooTest, Abc) {}\n\nTEST_F(FooTest, Xyz) { FAIL() << \"Expected failure.\"; }\n\n// Test case BarTest.\n\nTEST(BarTest, TestOne) {}\n\nTEST(BarTest, TestTwo) {}\n\nTEST(BarTest, TestThree) {}\n\nTEST(BarTest, DISABLED_TestFour) { FAIL() << \"Expected failure.\"; }\n\nTEST(BarTest, DISABLED_TestFive) { FAIL() << \"Expected failure.\"; }\n\n// Test case BazTest.\n\nTEST(BazTest, TestOne) { FAIL() << \"Expected failure.\"; }\n\nTEST(BazTest, TestA) {}\n\nTEST(BazTest, TestB) {}\n\nTEST(BazTest, DISABLED_TestC) { FAIL() << \"Expected failure.\"; }\n\n// Test case HasDeathTest\n\nTEST(HasDeathTest, Test1) { EXPECT_DEATH_IF_SUPPORTED(exit(1), \".*\"); }\n\n// We need at least two death tests to make sure that the all death tests\n// aren't on the first shard.\nTEST(HasDeathTest, Test2) { EXPECT_DEATH_IF_SUPPORTED(exit(1), \".*\"); }\n\n// Test case FoobarTest\n\nTEST(DISABLED_FoobarTest, Test1) { FAIL() << \"Expected failure.\"; }\n\nTEST(DISABLED_FoobarTest, DISABLED_Test2) { FAIL() << \"Expected failure.\"; }\n\n// Test case FoobarbazTest\n\nTEST(DISABLED_FoobarbazTest, TestA) { FAIL() << \"Expected failure.\"; }\n\nclass ParamTest : public testing::TestWithParam<int> {};\n\nTEST_P(ParamTest, TestX) {}\n\nTEST_P(ParamTest, TestY) {}\n\nINSTANTIATE_TEST_SUITE_P(SeqP, ParamTest, testing::Values(1, 2));\nINSTANTIATE_TEST_SUITE_P(SeqQ, ParamTest, testing::Values(5, 6));\n\n}  // namespace\n\nint main(int argc, char **argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n\n  return RUN_ALL_TESTS();\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-global-environment-unittest.py",
    "content": "# Copyright 2021 Google Inc. All Rights Reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"Unit test for Google Test's global test environment behavior.\n\nA user can specify a global test environment via\ntesting::AddGlobalTestEnvironment. Failures in the global environment should\nresult in all unit tests being skipped.\n\nThis script tests such functionality by invoking\ngoogletest-global-environment-unittest_ (a program written with Google Test).\n\"\"\"\n\nimport re\nfrom googletest.test import gtest_test_utils\n\n\ndef RunAndReturnOutput(args=None):\n  \"\"\"Runs the test program and returns its output.\"\"\"\n\n  return gtest_test_utils.Subprocess([\n      gtest_test_utils.GetTestExecutablePath(\n          'googletest-global-environment-unittest_')\n  ] + (args or [])).output\n\n\nclass GTestGlobalEnvironmentUnitTest(gtest_test_utils.TestCase):\n  \"\"\"Tests global test environment failures.\"\"\"\n\n  def testEnvironmentSetUpFails(self):\n    \"\"\"Tests the behavior of not specifying the fail_fast.\"\"\"\n\n    # Run the test.\n    txt = RunAndReturnOutput()\n\n    # We should see the text of the global environment setup error.\n    self.assertIn('Canned environment setup error', txt)\n\n    # Our test should have been skipped due to the error, and not treated as a\n    # pass.\n    self.assertIn('[  SKIPPED ] 1 test', txt)\n    self.assertIn('[  PASSED  ] 0 tests', txt)\n\n    # The test case shouldn't have been run.\n    self.assertNotIn('Unexpected call', txt)\n\n  def testEnvironmentSetUpAndTornDownForEachRepeat(self):\n    \"\"\"Tests the behavior of test environments and gtest_repeat.\"\"\"\n\n    # When --gtest_recreate_environments_when_repeating is true, the global test\n    # environment should be set up and torn down for each iteration.\n    txt = RunAndReturnOutput([\n        '--gtest_repeat=2',\n        '--gtest_recreate_environments_when_repeating=true',\n    ])\n\n    expected_pattern = ('(.|\\n)*'\n                        r'Repeating all tests \\(iteration 1\\)'\n                        '(.|\\n)*'\n                        'Global test environment set-up.'\n                        '(.|\\n)*'\n                        'SomeTest.DoesFoo'\n                        '(.|\\n)*'\n                        'Global test environment tear-down'\n                        '(.|\\n)*'\n                        r'Repeating all tests \\(iteration 2\\)'\n                        '(.|\\n)*'\n                        'Global test environment set-up.'\n                        '(.|\\n)*'\n                        'SomeTest.DoesFoo'\n                        '(.|\\n)*'\n                        'Global test environment tear-down'\n                        '(.|\\n)*')\n    self.assertRegex(txt, expected_pattern)\n\n  def testEnvironmentSetUpAndTornDownOnce(self):\n    \"\"\"Tests environment and --gtest_recreate_environments_when_repeating.\"\"\"\n\n    # By default the environment should only be set up and torn down once, at\n    # the start and end of the test respectively.\n    txt = RunAndReturnOutput([\n        '--gtest_repeat=2',\n    ])\n\n    expected_pattern = ('(.|\\n)*'\n                        r'Repeating all tests \\(iteration 1\\)'\n                        '(.|\\n)*'\n                        'Global test environment set-up.'\n                        '(.|\\n)*'\n                        'SomeTest.DoesFoo'\n                        '(.|\\n)*'\n                        r'Repeating all tests \\(iteration 2\\)'\n                        '(.|\\n)*'\n                        'SomeTest.DoesFoo'\n                        '(.|\\n)*'\n                        'Global test environment tear-down'\n                        '(.|\\n)*')\n    self.assertRegex(txt, expected_pattern)\n\n    self.assertEqual(len(re.findall('Global test environment set-up', txt)), 1)\n    self.assertEqual(\n        len(re.findall('Global test environment tear-down', txt)), 1)\n\n\nif __name__ == '__main__':\n  gtest_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-global-environment-unittest_.cc",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Unit test for Google Test global test environments.\n//\n// The program will be invoked from a Python unit test.  Don't run it\n// directly.\n\n#include \"gtest/gtest.h\"\n\nnamespace {\n\n// An environment that always fails in its SetUp method.\nclass FailingEnvironment final : public ::testing::Environment {\n public:\n  void SetUp() override { FAIL() << \"Canned environment setup error\"; }\n};\n\n// Register the environment.\nauto* const g_environment_ =\n    ::testing::AddGlobalTestEnvironment(new FailingEnvironment);\n\n// A test that doesn't actually run.\nTEST(SomeTest, DoesFoo) { FAIL() << \"Unexpected call\"; }\n\n}  // namespace\n\nint main(int argc, char** argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n\n  return RUN_ALL_TESTS();\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-json-outfiles-test.py",
    "content": "#!/usr/bin/env python\n# Copyright 2018, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Unit test for the gtest_json_output module.\"\"\"\n\nimport json\nimport os\nfrom googletest.test import gtest_json_test_utils\nfrom googletest.test import gtest_test_utils\n\nGTEST_OUTPUT_SUBDIR = 'json_outfiles'\nGTEST_OUTPUT_1_TEST = 'gtest_xml_outfile1_test_'\nGTEST_OUTPUT_2_TEST = 'gtest_xml_outfile2_test_'\n\nEXPECTED_1 = {\n    u'tests':\n        1,\n    u'failures':\n        0,\n    u'disabled':\n        0,\n    u'errors':\n        0,\n    u'time':\n        u'*',\n    u'timestamp':\n        u'*',\n    u'name':\n        u'AllTests',\n    u'testsuites': [{\n        u'name':\n            u'PropertyOne',\n        u'tests':\n            1,\n        u'failures':\n            0,\n        u'disabled':\n            0,\n        u'errors':\n            0,\n        u'time':\n            u'*',\n        u'timestamp':\n            u'*',\n        u'testsuite': [{\n            u'name': u'TestSomeProperties',\n            u'file': u'gtest_xml_outfile1_test_.cc',\n            u'line': 41,\n            u'status': u'RUN',\n            u'result': u'COMPLETED',\n            u'time': u'*',\n            u'timestamp': u'*',\n            u'classname': u'PropertyOne',\n            u'SetUpProp': u'1',\n            u'TestSomeProperty': u'1',\n            u'TearDownProp': u'1',\n        }],\n    }],\n}\n\nEXPECTED_2 = {\n    u'tests':\n        1,\n    u'failures':\n        0,\n    u'disabled':\n        0,\n    u'errors':\n        0,\n    u'time':\n        u'*',\n    u'timestamp':\n        u'*',\n    u'name':\n        u'AllTests',\n    u'testsuites': [{\n        u'name':\n            u'PropertyTwo',\n        u'tests':\n            1,\n        u'failures':\n            0,\n        u'disabled':\n            0,\n        u'errors':\n            0,\n        u'time':\n            u'*',\n        u'timestamp':\n            u'*',\n        u'testsuite': [{\n            u'name': u'TestSomeProperties',\n            u'file': u'gtest_xml_outfile2_test_.cc',\n            u'line': 41,\n            u'status': u'RUN',\n            u'result': u'COMPLETED',\n            u'timestamp': u'*',\n            u'time': u'*',\n            u'classname': u'PropertyTwo',\n            u'SetUpProp': u'2',\n            u'TestSomeProperty': u'2',\n            u'TearDownProp': u'2',\n        }],\n    }],\n}\n\n\nclass GTestJsonOutFilesTest(gtest_test_utils.TestCase):\n  \"\"\"Unit test for Google Test's JSON output functionality.\"\"\"\n\n  def setUp(self):\n    # We want the trailing '/' that the last \"\" provides in os.path.join, for\n    # telling Google Test to create an output directory instead of a single file\n    # for xml output.\n    self.output_dir_ = os.path.join(gtest_test_utils.GetTempDir(),\n                                    GTEST_OUTPUT_SUBDIR, '')\n    self.DeleteFilesAndDir()\n\n  def tearDown(self):\n    self.DeleteFilesAndDir()\n\n  def DeleteFilesAndDir(self):\n    try:\n      os.remove(os.path.join(self.output_dir_, GTEST_OUTPUT_1_TEST + '.json'))\n    except os.error:\n      pass\n    try:\n      os.remove(os.path.join(self.output_dir_, GTEST_OUTPUT_2_TEST + '.json'))\n    except os.error:\n      pass\n    try:\n      os.rmdir(self.output_dir_)\n    except os.error:\n      pass\n\n  def testOutfile1(self):\n    self._TestOutFile(GTEST_OUTPUT_1_TEST, EXPECTED_1)\n\n  def testOutfile2(self):\n    self._TestOutFile(GTEST_OUTPUT_2_TEST, EXPECTED_2)\n\n  def _TestOutFile(self, test_name, expected):\n    gtest_prog_path = gtest_test_utils.GetTestExecutablePath(test_name)\n    command = [gtest_prog_path, '--gtest_output=json:%s' % self.output_dir_]\n    p = gtest_test_utils.Subprocess(command,\n                                    working_dir=gtest_test_utils.GetTempDir())\n    self.assert_(p.exited)\n    self.assertEquals(0, p.exit_code)\n\n    output_file_name1 = test_name + '.json'\n    output_file1 = os.path.join(self.output_dir_, output_file_name1)\n    output_file_name2 = 'lt-' + output_file_name1\n    output_file2 = os.path.join(self.output_dir_, output_file_name2)\n    self.assert_(os.path.isfile(output_file1) or os.path.isfile(output_file2),\n                 output_file1)\n\n    if os.path.isfile(output_file1):\n      with open(output_file1) as f:\n        actual = json.load(f)\n    else:\n      with open(output_file2) as f:\n        actual = json.load(f)\n    self.assertEqual(expected, gtest_json_test_utils.normalize(actual))\n\n\nif __name__ == '__main__':\n  os.environ['GTEST_STACK_TRACE_DEPTH'] = '0'\n  gtest_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-json-output-unittest.py",
    "content": "#!/usr/bin/env python\n# Copyright 2018, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Unit test for the gtest_json_output module.\"\"\"\n\nimport datetime\nimport errno\nimport json\nimport os\nimport re\nimport sys\n\nfrom googletest.test import gtest_json_test_utils\nfrom googletest.test import gtest_test_utils\n\nGTEST_FILTER_FLAG = '--gtest_filter'\nGTEST_LIST_TESTS_FLAG = '--gtest_list_tests'\nGTEST_OUTPUT_FLAG = '--gtest_output'\nGTEST_DEFAULT_OUTPUT_FILE = 'test_detail.json'\nGTEST_PROGRAM_NAME = 'gtest_xml_output_unittest_'\n\n# The flag indicating stacktraces are not supported\nNO_STACKTRACE_SUPPORT_FLAG = '--no_stacktrace_support'\n\nSUPPORTS_STACK_TRACES = NO_STACKTRACE_SUPPORT_FLAG not in sys.argv\n\nif SUPPORTS_STACK_TRACES:\n  STACK_TRACE_TEMPLATE = '\\nStack trace:\\n*'\nelse:\n  STACK_TRACE_TEMPLATE = ''\n\nEXPECTED_NON_EMPTY = {\n    u'tests':\n        26,\n    u'failures':\n        5,\n    u'disabled':\n        2,\n    u'errors':\n        0,\n    u'timestamp':\n        u'*',\n    u'time':\n        u'*',\n    u'ad_hoc_property':\n        u'42',\n    u'name':\n        u'AllTests',\n    u'testsuites': [{\n        u'name':\n            u'SuccessfulTest',\n        u'tests':\n            1,\n        u'failures':\n            0,\n        u'disabled':\n            0,\n        u'errors':\n            0,\n        u'time':\n            u'*',\n        u'timestamp':\n            u'*',\n        u'testsuite': [{\n            u'name': u'Succeeds',\n            u'file': u'gtest_xml_output_unittest_.cc',\n            u'line': 51,\n            u'status': u'RUN',\n            u'result': u'COMPLETED',\n            u'time': u'*',\n            u'timestamp': u'*',\n            u'classname': u'SuccessfulTest'\n        }]\n    }, {\n        u'name':\n            u'FailedTest',\n        u'tests':\n            1,\n        u'failures':\n            1,\n        u'disabled':\n            0,\n        u'errors':\n            0,\n        u'time':\n            u'*',\n        u'timestamp':\n            u'*',\n        u'testsuite': [{\n            u'name':\n                u'Fails',\n            u'file':\n                u'gtest_xml_output_unittest_.cc',\n            u'line':\n                59,\n            u'status':\n                u'RUN',\n            u'result':\n                u'COMPLETED',\n            u'time':\n                u'*',\n            u'timestamp':\n                u'*',\n            u'classname':\n                u'FailedTest',\n            u'failures': [{\n                u'failure': u'gtest_xml_output_unittest_.cc:*\\n'\n                            u'Expected equality of these values:\\n'\n                            u'  1\\n  2' + STACK_TRACE_TEMPLATE,\n                u'type': u''\n            }]\n        }]\n    }, {\n        u'name':\n            u'DisabledTest',\n        u'tests':\n            1,\n        u'failures':\n            0,\n        u'disabled':\n            1,\n        u'errors':\n            0,\n        u'time':\n            u'*',\n        u'timestamp':\n            u'*',\n        u'testsuite': [{\n            u'name': u'DISABLED_test_not_run',\n            u'file': u'gtest_xml_output_unittest_.cc',\n            u'line': 66,\n            u'status': u'NOTRUN',\n            u'result': u'SUPPRESSED',\n            u'time': u'*',\n            u'timestamp': u'*',\n            u'classname': u'DisabledTest'\n        }]\n    }, {\n        u'name':\n            u'SkippedTest',\n        u'tests':\n            3,\n        u'failures':\n            1,\n        u'disabled':\n            0,\n        u'errors':\n            0,\n        u'time':\n            u'*',\n        u'timestamp':\n            u'*',\n        u'testsuite': [{\n            u'name': u'Skipped',\n            u'file': 'gtest_xml_output_unittest_.cc',\n            u'line': 73,\n            u'status': u'RUN',\n            u'result': u'SKIPPED',\n            u'time': u'*',\n            u'timestamp': u'*',\n            u'classname': u'SkippedTest'\n        }, {\n            u'name': u'SkippedWithMessage',\n            u'file': 'gtest_xml_output_unittest_.cc',\n            u'line': 77,\n            u'status': u'RUN',\n            u'result': u'SKIPPED',\n            u'time': u'*',\n            u'timestamp': u'*',\n            u'classname': u'SkippedTest'\n        }, {\n            u'name':\n                u'SkippedAfterFailure',\n            u'file':\n                'gtest_xml_output_unittest_.cc',\n            u'line':\n                81,\n            u'status':\n                u'RUN',\n            u'result':\n                u'COMPLETED',\n            u'time':\n                u'*',\n            u'timestamp':\n                u'*',\n            u'classname':\n                u'SkippedTest',\n            u'failures': [{\n                u'failure': u'gtest_xml_output_unittest_.cc:*\\n'\n                            u'Expected equality of these values:\\n'\n                            u'  1\\n  2' + STACK_TRACE_TEMPLATE,\n                u'type': u''\n            }]\n        }]\n    }, {\n        u'name':\n            u'MixedResultTest',\n        u'tests':\n            3,\n        u'failures':\n            1,\n        u'disabled':\n            1,\n        u'errors':\n            0,\n        u'time':\n            u'*',\n        u'timestamp':\n            u'*',\n        u'testsuite': [{\n            u'name': u'Succeeds',\n            u'file': 'gtest_xml_output_unittest_.cc',\n            u'line': 86,\n            u'status': u'RUN',\n            u'result': u'COMPLETED',\n            u'time': u'*',\n            u'timestamp': u'*',\n            u'classname': u'MixedResultTest'\n        }, {\n            u'name':\n                u'Fails',\n            u'file':\n                u'gtest_xml_output_unittest_.cc',\n            u'line':\n                91,\n            u'status':\n                u'RUN',\n            u'result':\n                u'COMPLETED',\n            u'time':\n                u'*',\n            u'timestamp':\n                u'*',\n            u'classname':\n                u'MixedResultTest',\n            u'failures': [{\n                u'failure': u'gtest_xml_output_unittest_.cc:*\\n'\n                            u'Expected equality of these values:\\n'\n                            u'  1\\n  2' + STACK_TRACE_TEMPLATE,\n                u'type': u''\n            }, {\n                u'failure': u'gtest_xml_output_unittest_.cc:*\\n'\n                            u'Expected equality of these values:\\n'\n                            u'  2\\n  3' + STACK_TRACE_TEMPLATE,\n                u'type': u''\n            }]\n        }, {\n            u'name': u'DISABLED_test',\n            u'file': u'gtest_xml_output_unittest_.cc',\n            u'line': 96,\n            u'status': u'NOTRUN',\n            u'result': u'SUPPRESSED',\n            u'time': u'*',\n            u'timestamp': u'*',\n            u'classname': u'MixedResultTest'\n        }]\n    }, {\n        u'name':\n            u'XmlQuotingTest',\n        u'tests':\n            1,\n        u'failures':\n            1,\n        u'disabled':\n            0,\n        u'errors':\n            0,\n        u'time':\n            u'*',\n        u'timestamp':\n            u'*',\n        u'testsuite': [{\n            u'name':\n                u'OutputsCData',\n            u'file':\n                u'gtest_xml_output_unittest_.cc',\n            u'line':\n                100,\n            u'status':\n                u'RUN',\n            u'result':\n                u'COMPLETED',\n            u'time':\n                u'*',\n            u'timestamp':\n                u'*',\n            u'classname':\n                u'XmlQuotingTest',\n            u'failures': [{\n                u'failure': u'gtest_xml_output_unittest_.cc:*\\n'\n                            u'Failed\\nXML output: <?xml encoding=\"utf-8\">'\n                            u'<top><![CDATA[cdata text]]></top>' +\n                            STACK_TRACE_TEMPLATE,\n                u'type': u''\n            }]\n        }]\n    }, {\n        u'name':\n            u'InvalidCharactersTest',\n        u'tests':\n            1,\n        u'failures':\n            1,\n        u'disabled':\n            0,\n        u'errors':\n            0,\n        u'time':\n            u'*',\n        u'timestamp':\n            u'*',\n        u'testsuite': [{\n            u'name':\n                u'InvalidCharactersInMessage',\n            u'file':\n                u'gtest_xml_output_unittest_.cc',\n            u'line':\n                107,\n            u'status':\n                u'RUN',\n            u'result':\n                u'COMPLETED',\n            u'time':\n                u'*',\n            u'timestamp':\n                u'*',\n            u'classname':\n                u'InvalidCharactersTest',\n            u'failures': [{\n                u'failure': u'gtest_xml_output_unittest_.cc:*\\n'\n                            u'Failed\\nInvalid characters in brackets'\n                            u' [\\x01\\x02]' + STACK_TRACE_TEMPLATE,\n                u'type': u''\n            }]\n        }]\n    }, {\n        u'name':\n            u'PropertyRecordingTest',\n        u'tests':\n            4,\n        u'failures':\n            0,\n        u'disabled':\n            0,\n        u'errors':\n            0,\n        u'time':\n            u'*',\n        u'timestamp':\n            u'*',\n        u'SetUpTestSuite':\n            u'yes',\n        u'TearDownTestSuite':\n            u'aye',\n        u'testsuite': [{\n            u'name': u'OneProperty',\n            u'file': u'gtest_xml_output_unittest_.cc',\n            u'line': 119,\n            u'status': u'RUN',\n            u'result': u'COMPLETED',\n            u'time': u'*',\n            u'timestamp': u'*',\n            u'classname': u'PropertyRecordingTest',\n            u'key_1': u'1'\n        }, {\n            u'name': u'IntValuedProperty',\n            u'file': u'gtest_xml_output_unittest_.cc',\n            u'line': 123,\n            u'status': u'RUN',\n            u'result': u'COMPLETED',\n            u'time': u'*',\n            u'timestamp': u'*',\n            u'classname': u'PropertyRecordingTest',\n            u'key_int': u'1'\n        }, {\n            u'name': u'ThreeProperties',\n            u'file': u'gtest_xml_output_unittest_.cc',\n            u'line': 127,\n            u'status': u'RUN',\n            u'result': u'COMPLETED',\n            u'time': u'*',\n            u'timestamp': u'*',\n            u'classname': u'PropertyRecordingTest',\n            u'key_1': u'1',\n            u'key_2': u'2',\n            u'key_3': u'3'\n        }, {\n            u'name': u'TwoValuesForOneKeyUsesLastValue',\n            u'file': u'gtest_xml_output_unittest_.cc',\n            u'line': 133,\n            u'status': u'RUN',\n            u'result': u'COMPLETED',\n            u'time': u'*',\n            u'timestamp': u'*',\n            u'classname': u'PropertyRecordingTest',\n            u'key_1': u'2'\n        }]\n    }, {\n        u'name':\n            u'NoFixtureTest',\n        u'tests':\n            3,\n        u'failures':\n            0,\n        u'disabled':\n            0,\n        u'errors':\n            0,\n        u'time':\n            u'*',\n        u'timestamp':\n            u'*',\n        u'testsuite': [{\n            u'name': u'RecordProperty',\n            u'file': u'gtest_xml_output_unittest_.cc',\n            u'line': 138,\n            u'status': u'RUN',\n            u'result': u'COMPLETED',\n            u'time': u'*',\n            u'timestamp': u'*',\n            u'classname': u'NoFixtureTest',\n            u'key': u'1'\n        }, {\n            u'name': u'ExternalUtilityThatCallsRecordIntValuedProperty',\n            u'file': u'gtest_xml_output_unittest_.cc',\n            u'line': 151,\n            u'status': u'RUN',\n            u'result': u'COMPLETED',\n            u'time': u'*',\n            u'timestamp': u'*',\n            u'classname': u'NoFixtureTest',\n            u'key_for_utility_int': u'1'\n        }, {\n            u'name': u'ExternalUtilityThatCallsRecordStringValuedProperty',\n            u'file': u'gtest_xml_output_unittest_.cc',\n            u'line': 155,\n            u'status': u'RUN',\n            u'result': u'COMPLETED',\n            u'time': u'*',\n            u'timestamp': u'*',\n            u'classname': u'NoFixtureTest',\n            u'key_for_utility_string': u'1'\n        }]\n    }, {\n        u'name':\n            u'TypedTest/0',\n        u'tests':\n            1,\n        u'failures':\n            0,\n        u'disabled':\n            0,\n        u'errors':\n            0,\n        u'time':\n            u'*',\n        u'timestamp':\n            u'*',\n        u'testsuite': [{\n            u'name': u'HasTypeParamAttribute',\n            u'type_param': u'int',\n            u'file': u'gtest_xml_output_unittest_.cc',\n            u'line': 171,\n            u'status': u'RUN',\n            u'result': u'COMPLETED',\n            u'time': u'*',\n            u'timestamp': u'*',\n            u'classname': u'TypedTest/0'\n        }]\n    }, {\n        u'name':\n            u'TypedTest/1',\n        u'tests':\n            1,\n        u'failures':\n            0,\n        u'disabled':\n            0,\n        u'errors':\n            0,\n        u'time':\n            u'*',\n        u'timestamp':\n            u'*',\n        u'testsuite': [{\n            u'name': u'HasTypeParamAttribute',\n            u'type_param': u'long',\n            u'file': u'gtest_xml_output_unittest_.cc',\n            u'line': 171,\n            u'status': u'RUN',\n            u'result': u'COMPLETED',\n            u'time': u'*',\n            u'timestamp': u'*',\n            u'classname': u'TypedTest/1'\n        }]\n    }, {\n        u'name':\n            u'Single/TypeParameterizedTestSuite/0',\n        u'tests':\n            1,\n        u'failures':\n            0,\n        u'disabled':\n            0,\n        u'errors':\n            0,\n        u'time':\n            u'*',\n        u'timestamp':\n            u'*',\n        u'testsuite': [{\n            u'name': u'HasTypeParamAttribute',\n            u'type_param': u'int',\n            u'file': u'gtest_xml_output_unittest_.cc',\n            u'line': 178,\n            u'status': u'RUN',\n            u'result': u'COMPLETED',\n            u'time': u'*',\n            u'timestamp': u'*',\n            u'classname': u'Single/TypeParameterizedTestSuite/0'\n        }]\n    }, {\n        u'name':\n            u'Single/TypeParameterizedTestSuite/1',\n        u'tests':\n            1,\n        u'failures':\n            0,\n        u'disabled':\n            0,\n        u'errors':\n            0,\n        u'time':\n            u'*',\n        u'timestamp':\n            u'*',\n        u'testsuite': [{\n            u'name': u'HasTypeParamAttribute',\n            u'type_param': u'long',\n            u'file': u'gtest_xml_output_unittest_.cc',\n            u'line': 178,\n            u'status': u'RUN',\n            u'result': u'COMPLETED',\n            u'time': u'*',\n            u'timestamp': u'*',\n            u'classname': u'Single/TypeParameterizedTestSuite/1'\n        }]\n    }, {\n        u'name':\n            u'Single/ValueParamTest',\n        u'tests':\n            4,\n        u'failures':\n            0,\n        u'disabled':\n            0,\n        u'errors':\n            0,\n        u'time':\n            u'*',\n        u'timestamp':\n            u'*',\n        u'testsuite': [{\n            u'name': u'HasValueParamAttribute/0',\n            u'value_param': u'33',\n            u'file': u'gtest_xml_output_unittest_.cc',\n            u'line': 162,\n            u'status': u'RUN',\n            u'result': u'COMPLETED',\n            u'time': u'*',\n            u'timestamp': u'*',\n            u'classname': u'Single/ValueParamTest'\n        }, {\n            u'name': u'HasValueParamAttribute/1',\n            u'value_param': u'42',\n            u'file': u'gtest_xml_output_unittest_.cc',\n            u'line': 162,\n            u'status': u'RUN',\n            u'result': u'COMPLETED',\n            u'time': u'*',\n            u'timestamp': u'*',\n            u'classname': u'Single/ValueParamTest'\n        }, {\n            u'name': u'AnotherTestThatHasValueParamAttribute/0',\n            u'value_param': u'33',\n            u'file': u'gtest_xml_output_unittest_.cc',\n            u'line': 163,\n            u'status': u'RUN',\n            u'result': u'COMPLETED',\n            u'time': u'*',\n            u'timestamp': u'*',\n            u'classname': u'Single/ValueParamTest'\n        }, {\n            u'name': u'AnotherTestThatHasValueParamAttribute/1',\n            u'value_param': u'42',\n            u'file': u'gtest_xml_output_unittest_.cc',\n            u'line': 163,\n            u'status': u'RUN',\n            u'result': u'COMPLETED',\n            u'time': u'*',\n            u'timestamp': u'*',\n            u'classname': u'Single/ValueParamTest'\n        }]\n    }]\n}\n\nEXPECTED_FILTERED = {\n    u'tests':\n        1,\n    u'failures':\n        0,\n    u'disabled':\n        0,\n    u'errors':\n        0,\n    u'time':\n        u'*',\n    u'timestamp':\n        u'*',\n    u'name':\n        u'AllTests',\n    u'ad_hoc_property':\n        u'42',\n    u'testsuites': [{\n        u'name':\n            u'SuccessfulTest',\n        u'tests':\n            1,\n        u'failures':\n            0,\n        u'disabled':\n            0,\n        u'errors':\n            0,\n        u'time':\n            u'*',\n        u'timestamp':\n            u'*',\n        u'testsuite': [{\n            u'name': u'Succeeds',\n            u'file': u'gtest_xml_output_unittest_.cc',\n            u'line': 51,\n            u'status': u'RUN',\n            u'result': u'COMPLETED',\n            u'time': u'*',\n            u'timestamp': u'*',\n            u'classname': u'SuccessfulTest',\n        }]\n    }],\n}\n\nEXPECTED_NO_TEST = {\n    u'tests':\n        0,\n    u'failures':\n        0,\n    u'disabled':\n        0,\n    u'errors':\n        0,\n    u'time':\n        u'*',\n    u'timestamp':\n        u'*',\n    u'name':\n        u'AllTests',\n    u'testsuites': [{\n        u'name':\n            u'NonTestSuiteFailure',\n        u'tests':\n            1,\n        u'failures':\n            1,\n        u'disabled':\n            0,\n        u'skipped':\n            0,\n        u'errors':\n            0,\n        u'time':\n            u'*',\n        u'timestamp':\n            u'*',\n        u'testsuite': [{\n            u'name':\n                u'',\n            u'status':\n                u'RUN',\n            u'result':\n                u'COMPLETED',\n            u'time':\n                u'*',\n            u'timestamp':\n                u'*',\n            u'classname':\n                u'',\n            u'failures': [{\n                u'failure': u'gtest_no_test_unittest.cc:*\\n'\n                            u'Expected equality of these values:\\n'\n                            u'  1\\n  2' + STACK_TRACE_TEMPLATE,\n                u'type': u'',\n            }]\n        }]\n    }],\n}\n\nGTEST_PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath(GTEST_PROGRAM_NAME)\n\nSUPPORTS_TYPED_TESTS = 'TypedTest' in gtest_test_utils.Subprocess(\n    [GTEST_PROGRAM_PATH, GTEST_LIST_TESTS_FLAG], capture_stderr=False).output\n\n\nclass GTestJsonOutputUnitTest(gtest_test_utils.TestCase):\n  \"\"\"Unit test for Google Test's JSON output functionality.\n  \"\"\"\n\n  # This test currently breaks on platforms that do not support typed and\n  # type-parameterized tests, so we don't run it under them.\n  if SUPPORTS_TYPED_TESTS:\n\n    def testNonEmptyJsonOutput(self):\n      \"\"\"Verifies JSON output for a Google Test binary with non-empty output.\n\n      Runs a test program that generates a non-empty JSON output, and\n      tests that the JSON output is expected.\n      \"\"\"\n      self._TestJsonOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY, 1)\n\n  def testNoTestJsonOutput(self):\n    \"\"\"Verifies JSON output for a Google Test binary without actual tests.\n\n    Runs a test program that generates an JSON output for a binary with no\n    tests, and tests that the JSON output is expected.\n    \"\"\"\n\n    self._TestJsonOutput('gtest_no_test_unittest', EXPECTED_NO_TEST, 0)\n\n  def testTimestampValue(self):\n    \"\"\"Checks whether the timestamp attribute in the JSON output is valid.\n\n    Runs a test program that generates an empty JSON output, and checks if\n    the timestamp attribute in the testsuites tag is valid.\n    \"\"\"\n    actual = self._GetJsonOutput('gtest_no_test_unittest', [], 0)\n    date_time_str = actual['timestamp']\n    # datetime.strptime() is only available in Python 2.5+ so we have to\n    # parse the expected datetime manually.\n    match = re.match(r'(\\d+)-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d):(\\d\\d)', date_time_str)\n    self.assertTrue(\n        re.match,\n        'JSON datettime string %s has incorrect format' % date_time_str)\n    date_time_from_json = datetime.datetime(\n        year=int(match.group(1)), month=int(match.group(2)),\n        day=int(match.group(3)), hour=int(match.group(4)),\n        minute=int(match.group(5)), second=int(match.group(6)))\n\n    time_delta = abs(datetime.datetime.now() - date_time_from_json)\n    # timestamp value should be near the current local time\n    self.assertTrue(time_delta < datetime.timedelta(seconds=600),\n                    'time_delta is %s' % time_delta)\n\n  def testDefaultOutputFile(self):\n    \"\"\"Verifies the default output file name.\n\n    Confirms that Google Test produces an JSON output file with the expected\n    default name if no name is explicitly specified.\n    \"\"\"\n    output_file = os.path.join(gtest_test_utils.GetTempDir(),\n                               GTEST_DEFAULT_OUTPUT_FILE)\n    gtest_prog_path = gtest_test_utils.GetTestExecutablePath(\n        'gtest_no_test_unittest')\n    try:\n      os.remove(output_file)\n    except OSError:\n      e = sys.exc_info()[1]\n      if e.errno != errno.ENOENT:\n        raise\n\n    p = gtest_test_utils.Subprocess(\n        [gtest_prog_path, '%s=json' % GTEST_OUTPUT_FLAG],\n        working_dir=gtest_test_utils.GetTempDir())\n    self.assert_(p.exited)\n    self.assertEquals(0, p.exit_code)\n    self.assert_(os.path.isfile(output_file))\n\n  def testSuppressedJsonOutput(self):\n    \"\"\"Verifies that no JSON output is generated.\n\n    Tests that no JSON file is generated if the default JSON listener is\n    shut down before RUN_ALL_TESTS is invoked.\n    \"\"\"\n\n    json_path = os.path.join(gtest_test_utils.GetTempDir(),\n                             GTEST_PROGRAM_NAME + 'out.json')\n    if os.path.isfile(json_path):\n      os.remove(json_path)\n\n    command = [GTEST_PROGRAM_PATH,\n               '%s=json:%s' % (GTEST_OUTPUT_FLAG, json_path),\n               '--shut_down_xml']\n    p = gtest_test_utils.Subprocess(command)\n    if p.terminated_by_signal:\n      # p.signal is available only if p.terminated_by_signal is True.\n      self.assertFalse(\n          p.terminated_by_signal,\n          '%s was killed by signal %d' % (GTEST_PROGRAM_NAME, p.signal))\n    else:\n      self.assert_(p.exited)\n      self.assertEquals(1, p.exit_code,\n                        \"'%s' exited with code %s, which doesn't match \"\n                        'the expected exit code %s.'\n                        % (command, p.exit_code, 1))\n\n    self.assert_(not os.path.isfile(json_path))\n\n  def testFilteredTestJsonOutput(self):\n    \"\"\"Verifies JSON output when a filter is applied.\n\n    Runs a test program that executes only some tests and verifies that\n    non-selected tests do not show up in the JSON output.\n    \"\"\"\n\n    self._TestJsonOutput(GTEST_PROGRAM_NAME, EXPECTED_FILTERED, 0,\n                         extra_args=['%s=SuccessfulTest.*' % GTEST_FILTER_FLAG])\n\n  def _GetJsonOutput(self, gtest_prog_name, extra_args, expected_exit_code):\n    \"\"\"Returns the JSON output generated by running the program gtest_prog_name.\n\n    Furthermore, the program's exit code must be expected_exit_code.\n\n    Args:\n      gtest_prog_name: Google Test binary name.\n      extra_args: extra arguments to binary invocation.\n      expected_exit_code: program's exit code.\n    \"\"\"\n    json_path = os.path.join(gtest_test_utils.GetTempDir(),\n                             gtest_prog_name + 'out.json')\n    gtest_prog_path = gtest_test_utils.GetTestExecutablePath(gtest_prog_name)\n\n    command = (\n        [gtest_prog_path, '%s=json:%s' % (GTEST_OUTPUT_FLAG, json_path)] +\n        extra_args\n    )\n    p = gtest_test_utils.Subprocess(command)\n    if p.terminated_by_signal:\n      self.assert_(False,\n                   '%s was killed by signal %d' % (gtest_prog_name, p.signal))\n    else:\n      self.assert_(p.exited)\n      self.assertEquals(expected_exit_code, p.exit_code,\n                        \"'%s' exited with code %s, which doesn't match \"\n                        'the expected exit code %s.'\n                        % (command, p.exit_code, expected_exit_code))\n    with open(json_path) as f:\n      actual = json.load(f)\n    return actual\n\n  def _TestJsonOutput(self, gtest_prog_name, expected,\n                      expected_exit_code, extra_args=None):\n    \"\"\"Checks the JSON output generated by the Google Test binary.\n\n    Asserts that the JSON document generated by running the program\n    gtest_prog_name matches expected_json, a string containing another\n    JSON document.  Furthermore, the program's exit code must be\n    expected_exit_code.\n\n    Args:\n      gtest_prog_name: Google Test binary name.\n      expected: expected output.\n      expected_exit_code: program's exit code.\n      extra_args: extra arguments to binary invocation.\n    \"\"\"\n\n    actual = self._GetJsonOutput(gtest_prog_name, extra_args or [],\n                                 expected_exit_code)\n    self.assertEqual(expected, gtest_json_test_utils.normalize(actual))\n\n\nif __name__ == '__main__':\n  if NO_STACKTRACE_SUPPORT_FLAG in sys.argv:\n    # unittest.main() can't handle unknown flags\n    sys.argv.remove(NO_STACKTRACE_SUPPORT_FLAG)\n\n  os.environ['GTEST_STACK_TRACE_DEPTH'] = '1'\n  gtest_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-list-tests-unittest.py",
    "content": "#!/usr/bin/env python\n#\n# Copyright 2006, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Unit test for Google Test's --gtest_list_tests flag.\n\nA user can ask Google Test to list all tests by specifying the\n--gtest_list_tests flag.  This script tests such functionality\nby invoking googletest-list-tests-unittest_ (a program written with\nGoogle Test) the command line flags.\n\"\"\"\n\nimport re\nfrom googletest.test import gtest_test_utils\n\n# Constants.\n\n# The command line flag for enabling/disabling listing all tests.\nLIST_TESTS_FLAG = 'gtest_list_tests'\n\n# Path to the googletest-list-tests-unittest_ program.\nEXE_PATH = gtest_test_utils.GetTestExecutablePath('googletest-list-tests-unittest_')\n\n# The expected output when running googletest-list-tests-unittest_ with\n# --gtest_list_tests\nEXPECTED_OUTPUT_NO_FILTER_RE = re.compile(r\"\"\"FooDeathTest\\.\n  Test1\nFoo\\.\n  Bar1\n  Bar2\n  DISABLED_Bar3\nAbc\\.\n  Xyz\n  Def\nFooBar\\.\n  Baz\nFooTest\\.\n  Test1\n  DISABLED_Test2\n  Test3\nTypedTest/0\\.  # TypeParam = (VeryLo{245}|class VeryLo{239})\\.\\.\\.\n  TestA\n  TestB\nTypedTest/1\\.  # TypeParam = int\\s*\\*( __ptr64)?\n  TestA\n  TestB\nTypedTest/2\\.  # TypeParam = .*MyArray<bool,\\s*42>\n  TestA\n  TestB\nMy/TypeParamTest/0\\.  # TypeParam = (VeryLo{245}|class VeryLo{239})\\.\\.\\.\n  TestA\n  TestB\nMy/TypeParamTest/1\\.  # TypeParam = int\\s*\\*( __ptr64)?\n  TestA\n  TestB\nMy/TypeParamTest/2\\.  # TypeParam = .*MyArray<bool,\\s*42>\n  TestA\n  TestB\nMyInstantiation/ValueParamTest\\.\n  TestA/0  # GetParam\\(\\) = one line\n  TestA/1  # GetParam\\(\\) = two\\\\nlines\n  TestA/2  # GetParam\\(\\) = a very\\\\nlo{241}\\.\\.\\.\n  TestB/0  # GetParam\\(\\) = one line\n  TestB/1  # GetParam\\(\\) = two\\\\nlines\n  TestB/2  # GetParam\\(\\) = a very\\\\nlo{241}\\.\\.\\.\n\"\"\")\n\n# The expected output when running googletest-list-tests-unittest_ with\n# --gtest_list_tests and --gtest_filter=Foo*.\nEXPECTED_OUTPUT_FILTER_FOO_RE = re.compile(r\"\"\"FooDeathTest\\.\n  Test1\nFoo\\.\n  Bar1\n  Bar2\n  DISABLED_Bar3\nFooBar\\.\n  Baz\nFooTest\\.\n  Test1\n  DISABLED_Test2\n  Test3\n\"\"\")\n\n# Utilities.\n\n\ndef Run(args):\n  \"\"\"Runs googletest-list-tests-unittest_ and returns the list of tests printed.\"\"\"\n\n  return gtest_test_utils.Subprocess([EXE_PATH] + args,\n                                     capture_stderr=False).output\n\n\n# The unit test.\n\n\nclass GTestListTestsUnitTest(gtest_test_utils.TestCase):\n  \"\"\"Tests using the --gtest_list_tests flag to list all tests.\"\"\"\n\n  def RunAndVerify(self, flag_value, expected_output_re, other_flag):\n    \"\"\"Runs googletest-list-tests-unittest_ and verifies that it prints\n    the correct tests.\n\n    Args:\n      flag_value:         value of the --gtest_list_tests flag;\n                          None if the flag should not be present.\n      expected_output_re: regular expression that matches the expected\n                          output after running command;\n      other_flag:         a different flag to be passed to command\n                          along with gtest_list_tests;\n                          None if the flag should not be present.\n    \"\"\"\n\n    if flag_value is None:\n      flag = ''\n      flag_expression = 'not set'\n    elif flag_value == '0':\n      flag = '--%s=0' % LIST_TESTS_FLAG\n      flag_expression = '0'\n    else:\n      flag = '--%s' % LIST_TESTS_FLAG\n      flag_expression = '1'\n\n    args = [flag]\n\n    if other_flag is not None:\n      args += [other_flag]\n\n    output = Run(args)\n\n    if expected_output_re:\n      self.assert_(\n          expected_output_re.match(output),\n          ('when %s is %s, the output of \"%s\" is \"%s\",\\n'\n           'which does not match regex \"%s\"' %\n           (LIST_TESTS_FLAG, flag_expression, ' '.join(args), output,\n            expected_output_re.pattern)))\n    else:\n      self.assert_(\n          not EXPECTED_OUTPUT_NO_FILTER_RE.match(output),\n          ('when %s is %s, the output of \"%s\" is \"%s\"'%\n           (LIST_TESTS_FLAG, flag_expression, ' '.join(args), output)))\n\n  def testDefaultBehavior(self):\n    \"\"\"Tests the behavior of the default mode.\"\"\"\n\n    self.RunAndVerify(flag_value=None,\n                      expected_output_re=None,\n                      other_flag=None)\n\n  def testFlag(self):\n    \"\"\"Tests using the --gtest_list_tests flag.\"\"\"\n\n    self.RunAndVerify(flag_value='0',\n                      expected_output_re=None,\n                      other_flag=None)\n    self.RunAndVerify(flag_value='1',\n                      expected_output_re=EXPECTED_OUTPUT_NO_FILTER_RE,\n                      other_flag=None)\n\n  def testOverrideNonFilterFlags(self):\n    \"\"\"Tests that --gtest_list_tests overrides the non-filter flags.\"\"\"\n\n    self.RunAndVerify(flag_value='1',\n                      expected_output_re=EXPECTED_OUTPUT_NO_FILTER_RE,\n                      other_flag='--gtest_break_on_failure')\n\n  def testWithFilterFlags(self):\n    \"\"\"Tests that --gtest_list_tests takes into account the\n    --gtest_filter flag.\"\"\"\n\n    self.RunAndVerify(flag_value='1',\n                      expected_output_re=EXPECTED_OUTPUT_FILTER_FOO_RE,\n                      other_flag='--gtest_filter=Foo*')\n\n\nif __name__ == '__main__':\n  gtest_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-list-tests-unittest_.cc",
    "content": "// Copyright 2006, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Unit test for Google Test's --gtest_list_tests flag.\n//\n// A user can ask Google Test to list all tests that will run\n// so that when using a filter, a user will know what\n// tests to look for. The tests will not be run after listing.\n//\n// This program will be invoked from a Python unit test.\n// Don't run it directly.\n\n#include \"gtest/gtest.h\"\n\n// Several different test cases and tests that will be listed.\nTEST(Foo, Bar1) {}\n\nTEST(Foo, Bar2) {}\n\nTEST(Foo, DISABLED_Bar3) {}\n\nTEST(Abc, Xyz) {}\n\nTEST(Abc, Def) {}\n\nTEST(FooBar, Baz) {}\n\nclass FooTest : public testing::Test {};\n\nTEST_F(FooTest, Test1) {}\n\nTEST_F(FooTest, DISABLED_Test2) {}\n\nTEST_F(FooTest, Test3) {}\n\nTEST(FooDeathTest, Test1) {}\n\n// A group of value-parameterized tests.\n\nclass MyType {\n public:\n  explicit MyType(const std::string& a_value) : value_(a_value) {}\n\n  const std::string& value() const { return value_; }\n\n private:\n  std::string value_;\n};\n\n// Teaches Google Test how to print a MyType.\nvoid PrintTo(const MyType& x, std::ostream* os) { *os << x.value(); }\n\nclass ValueParamTest : public testing::TestWithParam<MyType> {};\n\nTEST_P(ValueParamTest, TestA) {}\n\nTEST_P(ValueParamTest, TestB) {}\n\nINSTANTIATE_TEST_SUITE_P(\n    MyInstantiation, ValueParamTest,\n    testing::Values(\n        MyType(\"one line\"), MyType(\"two\\nlines\"),\n        MyType(\"a \"\n               \"very\\nloooooooooooooooooooooooooooooooooooooooooooooooooooooooo\"\n               \"ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo\"\n               \"ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo\"\n               \"ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo\"\n               \"ooooong line\")));  // NOLINT\n\n// A group of typed tests.\n\n// A deliberately long type name for testing the line-truncating\n// behavior when printing a type parameter.\nclass\n    VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName {  // NOLINT\n};\n\ntemplate <typename T>\nclass TypedTest : public testing::Test {};\n\ntemplate <typename T, int kSize>\nclass MyArray {};\n\ntypedef testing::Types<\n    VeryLoooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooogName,  // NOLINT\n    int*, MyArray<bool, 42> >\n    MyTypes;\n\nTYPED_TEST_SUITE(TypedTest, MyTypes);\n\nTYPED_TEST(TypedTest, TestA) {}\n\nTYPED_TEST(TypedTest, TestB) {}\n\n// A group of type-parameterized tests.\n\ntemplate <typename T>\nclass TypeParamTest : public testing::Test {};\n\nTYPED_TEST_SUITE_P(TypeParamTest);\n\nTYPED_TEST_P(TypeParamTest, TestA) {}\n\nTYPED_TEST_P(TypeParamTest, TestB) {}\n\nREGISTER_TYPED_TEST_SUITE_P(TypeParamTest, TestA, TestB);\n\nINSTANTIATE_TYPED_TEST_SUITE_P(My, TypeParamTest, MyTypes);\n\nint main(int argc, char** argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n\n  return RUN_ALL_TESTS();\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-listener-test.cc",
    "content": "// Copyright 2009 Google Inc. All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// The Google C++ Testing and Mocking Framework (Google Test)\n//\n// This file verifies Google Test event listeners receive events at the\n// right times.\n\n#include <vector>\n\n#include \"gtest/gtest.h\"\n#include \"gtest/internal/custom/gtest.h\"\n\nusing ::testing::AddGlobalTestEnvironment;\nusing ::testing::Environment;\nusing ::testing::InitGoogleTest;\nusing ::testing::Test;\nusing ::testing::TestEventListener;\nusing ::testing::TestInfo;\nusing ::testing::TestPartResult;\nusing ::testing::TestSuite;\nusing ::testing::UnitTest;\n\n// Used by tests to register their events.\nstd::vector<std::string>* g_events = nullptr;\n\nnamespace testing {\nnamespace internal {\n\nclass EventRecordingListener : public TestEventListener {\n public:\n  explicit EventRecordingListener(const char* name) : name_(name) {}\n\n protected:\n  void OnTestProgramStart(const UnitTest& /*unit_test*/) override {\n    g_events->push_back(GetFullMethodName(\"OnTestProgramStart\"));\n  }\n\n  void OnTestIterationStart(const UnitTest& /*unit_test*/,\n                            int iteration) override {\n    Message message;\n    message << GetFullMethodName(\"OnTestIterationStart\") << \"(\" << iteration\n            << \")\";\n    g_events->push_back(message.GetString());\n  }\n\n  void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {\n    g_events->push_back(GetFullMethodName(\"OnEnvironmentsSetUpStart\"));\n  }\n\n  void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {\n    g_events->push_back(GetFullMethodName(\"OnEnvironmentsSetUpEnd\"));\n  }\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  void OnTestCaseStart(const TestCase& /*test_case*/) override {\n    g_events->push_back(GetFullMethodName(\"OnTestCaseStart\"));\n  }\n#endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n  void OnTestStart(const TestInfo& /*test_info*/) override {\n    g_events->push_back(GetFullMethodName(\"OnTestStart\"));\n  }\n\n  void OnTestPartResult(const TestPartResult& /*test_part_result*/) override {\n    g_events->push_back(GetFullMethodName(\"OnTestPartResult\"));\n  }\n\n  void OnTestEnd(const TestInfo& /*test_info*/) override {\n    g_events->push_back(GetFullMethodName(\"OnTestEnd\"));\n  }\n\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n  void OnTestCaseEnd(const TestCase& /*test_case*/) override {\n    g_events->push_back(GetFullMethodName(\"OnTestCaseEnd\"));\n  }\n#endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n  void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {\n    g_events->push_back(GetFullMethodName(\"OnEnvironmentsTearDownStart\"));\n  }\n\n  void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {\n    g_events->push_back(GetFullMethodName(\"OnEnvironmentsTearDownEnd\"));\n  }\n\n  void OnTestIterationEnd(const UnitTest& /*unit_test*/,\n                          int iteration) override {\n    Message message;\n    message << GetFullMethodName(\"OnTestIterationEnd\") << \"(\" << iteration\n            << \")\";\n    g_events->push_back(message.GetString());\n  }\n\n  void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {\n    g_events->push_back(GetFullMethodName(\"OnTestProgramEnd\"));\n  }\n\n private:\n  std::string GetFullMethodName(const char* name) { return name_ + \".\" + name; }\n\n  std::string name_;\n};\n\n// This listener is using OnTestSuiteStart, OnTestSuiteEnd API\nclass EventRecordingListener2 : public TestEventListener {\n public:\n  explicit EventRecordingListener2(const char* name) : name_(name) {}\n\n protected:\n  void OnTestProgramStart(const UnitTest& /*unit_test*/) override {\n    g_events->push_back(GetFullMethodName(\"OnTestProgramStart\"));\n  }\n\n  void OnTestIterationStart(const UnitTest& /*unit_test*/,\n                            int iteration) override {\n    Message message;\n    message << GetFullMethodName(\"OnTestIterationStart\") << \"(\" << iteration\n            << \")\";\n    g_events->push_back(message.GetString());\n  }\n\n  void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) override {\n    g_events->push_back(GetFullMethodName(\"OnEnvironmentsSetUpStart\"));\n  }\n\n  void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) override {\n    g_events->push_back(GetFullMethodName(\"OnEnvironmentsSetUpEnd\"));\n  }\n\n  void OnTestSuiteStart(const TestSuite& /*test_suite*/) override {\n    g_events->push_back(GetFullMethodName(\"OnTestSuiteStart\"));\n  }\n\n  void OnTestStart(const TestInfo& /*test_info*/) override {\n    g_events->push_back(GetFullMethodName(\"OnTestStart\"));\n  }\n\n  void OnTestPartResult(const TestPartResult& /*test_part_result*/) override {\n    g_events->push_back(GetFullMethodName(\"OnTestPartResult\"));\n  }\n\n  void OnTestEnd(const TestInfo& /*test_info*/) override {\n    g_events->push_back(GetFullMethodName(\"OnTestEnd\"));\n  }\n\n  void OnTestSuiteEnd(const TestSuite& /*test_suite*/) override {\n    g_events->push_back(GetFullMethodName(\"OnTestSuiteEnd\"));\n  }\n\n  void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) override {\n    g_events->push_back(GetFullMethodName(\"OnEnvironmentsTearDownStart\"));\n  }\n\n  void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) override {\n    g_events->push_back(GetFullMethodName(\"OnEnvironmentsTearDownEnd\"));\n  }\n\n  void OnTestIterationEnd(const UnitTest& /*unit_test*/,\n                          int iteration) override {\n    Message message;\n    message << GetFullMethodName(\"OnTestIterationEnd\") << \"(\" << iteration\n            << \")\";\n    g_events->push_back(message.GetString());\n  }\n\n  void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {\n    g_events->push_back(GetFullMethodName(\"OnTestProgramEnd\"));\n  }\n\n private:\n  std::string GetFullMethodName(const char* name) { return name_ + \".\" + name; }\n\n  std::string name_;\n};\n\nclass EnvironmentInvocationCatcher : public Environment {\n protected:\n  void SetUp() override { g_events->push_back(\"Environment::SetUp\"); }\n\n  void TearDown() override { g_events->push_back(\"Environment::TearDown\"); }\n};\n\nclass ListenerTest : public Test {\n protected:\n  static void SetUpTestSuite() {\n    g_events->push_back(\"ListenerTest::SetUpTestSuite\");\n  }\n\n  static void TearDownTestSuite() {\n    g_events->push_back(\"ListenerTest::TearDownTestSuite\");\n  }\n\n  void SetUp() override { g_events->push_back(\"ListenerTest::SetUp\"); }\n\n  void TearDown() override { g_events->push_back(\"ListenerTest::TearDown\"); }\n};\n\nTEST_F(ListenerTest, DoesFoo) {\n  // Test execution order within a test case is not guaranteed so we are not\n  // recording the test name.\n  g_events->push_back(\"ListenerTest::* Test Body\");\n  SUCCEED();  // Triggers OnTestPartResult.\n}\n\nTEST_F(ListenerTest, DoesBar) {\n  g_events->push_back(\"ListenerTest::* Test Body\");\n  SUCCEED();  // Triggers OnTestPartResult.\n}\n\n}  // namespace internal\n\n}  // namespace testing\n\nusing ::testing::internal::EnvironmentInvocationCatcher;\nusing ::testing::internal::EventRecordingListener;\nusing ::testing::internal::EventRecordingListener2;\n\nvoid VerifyResults(const std::vector<std::string>& data,\n                   const char* const* expected_data,\n                   size_t expected_data_size) {\n  const size_t actual_size = data.size();\n  // If the following assertion fails, a new entry will be appended to\n  // data.  Hence we save data.size() first.\n  EXPECT_EQ(expected_data_size, actual_size);\n\n  // Compares the common prefix.\n  const size_t shorter_size =\n      expected_data_size <= actual_size ? expected_data_size : actual_size;\n  size_t i = 0;\n  for (; i < shorter_size; ++i) {\n    ASSERT_STREQ(expected_data[i], data[i].c_str()) << \"at position \" << i;\n  }\n\n  // Prints extra elements in the actual data.\n  for (; i < actual_size; ++i) {\n    printf(\"  Actual event #%lu: %s\\n\", static_cast<unsigned long>(i),\n           data[i].c_str());\n  }\n}\n\nint main(int argc, char** argv) {\n  std::vector<std::string> events;\n  g_events = &events;\n  InitGoogleTest(&argc, argv);\n\n  UnitTest::GetInstance()->listeners().Append(\n      new EventRecordingListener(\"1st\"));\n  UnitTest::GetInstance()->listeners().Append(\n      new EventRecordingListener(\"2nd\"));\n  UnitTest::GetInstance()->listeners().Append(\n      new EventRecordingListener2(\"3rd\"));\n\n  AddGlobalTestEnvironment(new EnvironmentInvocationCatcher);\n\n  GTEST_CHECK_(events.size() == 0)\n      << \"AddGlobalTestEnvironment should not generate any events itself.\";\n\n  GTEST_FLAG_SET(repeat, 2);\n  GTEST_FLAG_SET(recreate_environments_when_repeating, true);\n  int ret_val = RUN_ALL_TESTS();\n\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n  // The deprecated OnTestSuiteStart/OnTestCaseStart events are included\n  const char* const expected_events[] = {\"1st.OnTestProgramStart\",\n                                         \"2nd.OnTestProgramStart\",\n                                         \"3rd.OnTestProgramStart\",\n                                         \"1st.OnTestIterationStart(0)\",\n                                         \"2nd.OnTestIterationStart(0)\",\n                                         \"3rd.OnTestIterationStart(0)\",\n                                         \"1st.OnEnvironmentsSetUpStart\",\n                                         \"2nd.OnEnvironmentsSetUpStart\",\n                                         \"3rd.OnEnvironmentsSetUpStart\",\n                                         \"Environment::SetUp\",\n                                         \"3rd.OnEnvironmentsSetUpEnd\",\n                                         \"2nd.OnEnvironmentsSetUpEnd\",\n                                         \"1st.OnEnvironmentsSetUpEnd\",\n                                         \"3rd.OnTestSuiteStart\",\n                                         \"1st.OnTestCaseStart\",\n                                         \"2nd.OnTestCaseStart\",\n                                         \"ListenerTest::SetUpTestSuite\",\n                                         \"1st.OnTestStart\",\n                                         \"2nd.OnTestStart\",\n                                         \"3rd.OnTestStart\",\n                                         \"ListenerTest::SetUp\",\n                                         \"ListenerTest::* Test Body\",\n                                         \"1st.OnTestPartResult\",\n                                         \"2nd.OnTestPartResult\",\n                                         \"3rd.OnTestPartResult\",\n                                         \"ListenerTest::TearDown\",\n                                         \"3rd.OnTestEnd\",\n                                         \"2nd.OnTestEnd\",\n                                         \"1st.OnTestEnd\",\n                                         \"1st.OnTestStart\",\n                                         \"2nd.OnTestStart\",\n                                         \"3rd.OnTestStart\",\n                                         \"ListenerTest::SetUp\",\n                                         \"ListenerTest::* Test Body\",\n                                         \"1st.OnTestPartResult\",\n                                         \"2nd.OnTestPartResult\",\n                                         \"3rd.OnTestPartResult\",\n                                         \"ListenerTest::TearDown\",\n                                         \"3rd.OnTestEnd\",\n                                         \"2nd.OnTestEnd\",\n                                         \"1st.OnTestEnd\",\n                                         \"ListenerTest::TearDownTestSuite\",\n                                         \"3rd.OnTestSuiteEnd\",\n                                         \"2nd.OnTestCaseEnd\",\n                                         \"1st.OnTestCaseEnd\",\n                                         \"1st.OnEnvironmentsTearDownStart\",\n                                         \"2nd.OnEnvironmentsTearDownStart\",\n                                         \"3rd.OnEnvironmentsTearDownStart\",\n                                         \"Environment::TearDown\",\n                                         \"3rd.OnEnvironmentsTearDownEnd\",\n                                         \"2nd.OnEnvironmentsTearDownEnd\",\n                                         \"1st.OnEnvironmentsTearDownEnd\",\n                                         \"3rd.OnTestIterationEnd(0)\",\n                                         \"2nd.OnTestIterationEnd(0)\",\n                                         \"1st.OnTestIterationEnd(0)\",\n                                         \"1st.OnTestIterationStart(1)\",\n                                         \"2nd.OnTestIterationStart(1)\",\n                                         \"3rd.OnTestIterationStart(1)\",\n                                         \"1st.OnEnvironmentsSetUpStart\",\n                                         \"2nd.OnEnvironmentsSetUpStart\",\n                                         \"3rd.OnEnvironmentsSetUpStart\",\n                                         \"Environment::SetUp\",\n                                         \"3rd.OnEnvironmentsSetUpEnd\",\n                                         \"2nd.OnEnvironmentsSetUpEnd\",\n                                         \"1st.OnEnvironmentsSetUpEnd\",\n                                         \"3rd.OnTestSuiteStart\",\n                                         \"1st.OnTestCaseStart\",\n                                         \"2nd.OnTestCaseStart\",\n                                         \"ListenerTest::SetUpTestSuite\",\n                                         \"1st.OnTestStart\",\n                                         \"2nd.OnTestStart\",\n                                         \"3rd.OnTestStart\",\n                                         \"ListenerTest::SetUp\",\n                                         \"ListenerTest::* Test Body\",\n                                         \"1st.OnTestPartResult\",\n                                         \"2nd.OnTestPartResult\",\n                                         \"3rd.OnTestPartResult\",\n                                         \"ListenerTest::TearDown\",\n                                         \"3rd.OnTestEnd\",\n                                         \"2nd.OnTestEnd\",\n                                         \"1st.OnTestEnd\",\n                                         \"1st.OnTestStart\",\n                                         \"2nd.OnTestStart\",\n                                         \"3rd.OnTestStart\",\n                                         \"ListenerTest::SetUp\",\n                                         \"ListenerTest::* Test Body\",\n                                         \"1st.OnTestPartResult\",\n                                         \"2nd.OnTestPartResult\",\n                                         \"3rd.OnTestPartResult\",\n                                         \"ListenerTest::TearDown\",\n                                         \"3rd.OnTestEnd\",\n                                         \"2nd.OnTestEnd\",\n                                         \"1st.OnTestEnd\",\n                                         \"ListenerTest::TearDownTestSuite\",\n                                         \"3rd.OnTestSuiteEnd\",\n                                         \"2nd.OnTestCaseEnd\",\n                                         \"1st.OnTestCaseEnd\",\n                                         \"1st.OnEnvironmentsTearDownStart\",\n                                         \"2nd.OnEnvironmentsTearDownStart\",\n                                         \"3rd.OnEnvironmentsTearDownStart\",\n                                         \"Environment::TearDown\",\n                                         \"3rd.OnEnvironmentsTearDownEnd\",\n                                         \"2nd.OnEnvironmentsTearDownEnd\",\n                                         \"1st.OnEnvironmentsTearDownEnd\",\n                                         \"3rd.OnTestIterationEnd(1)\",\n                                         \"2nd.OnTestIterationEnd(1)\",\n                                         \"1st.OnTestIterationEnd(1)\",\n                                         \"3rd.OnTestProgramEnd\",\n                                         \"2nd.OnTestProgramEnd\",\n                                         \"1st.OnTestProgramEnd\"};\n#else\n  const char* const expected_events[] = {\"1st.OnTestProgramStart\",\n                                         \"2nd.OnTestProgramStart\",\n                                         \"3rd.OnTestProgramStart\",\n                                         \"1st.OnTestIterationStart(0)\",\n                                         \"2nd.OnTestIterationStart(0)\",\n                                         \"3rd.OnTestIterationStart(0)\",\n                                         \"1st.OnEnvironmentsSetUpStart\",\n                                         \"2nd.OnEnvironmentsSetUpStart\",\n                                         \"3rd.OnEnvironmentsSetUpStart\",\n                                         \"Environment::SetUp\",\n                                         \"3rd.OnEnvironmentsSetUpEnd\",\n                                         \"2nd.OnEnvironmentsSetUpEnd\",\n                                         \"1st.OnEnvironmentsSetUpEnd\",\n                                         \"3rd.OnTestSuiteStart\",\n                                         \"ListenerTest::SetUpTestSuite\",\n                                         \"1st.OnTestStart\",\n                                         \"2nd.OnTestStart\",\n                                         \"3rd.OnTestStart\",\n                                         \"ListenerTest::SetUp\",\n                                         \"ListenerTest::* Test Body\",\n                                         \"1st.OnTestPartResult\",\n                                         \"2nd.OnTestPartResult\",\n                                         \"3rd.OnTestPartResult\",\n                                         \"ListenerTest::TearDown\",\n                                         \"3rd.OnTestEnd\",\n                                         \"2nd.OnTestEnd\",\n                                         \"1st.OnTestEnd\",\n                                         \"1st.OnTestStart\",\n                                         \"2nd.OnTestStart\",\n                                         \"3rd.OnTestStart\",\n                                         \"ListenerTest::SetUp\",\n                                         \"ListenerTest::* Test Body\",\n                                         \"1st.OnTestPartResult\",\n                                         \"2nd.OnTestPartResult\",\n                                         \"3rd.OnTestPartResult\",\n                                         \"ListenerTest::TearDown\",\n                                         \"3rd.OnTestEnd\",\n                                         \"2nd.OnTestEnd\",\n                                         \"1st.OnTestEnd\",\n                                         \"ListenerTest::TearDownTestSuite\",\n                                         \"3rd.OnTestSuiteEnd\",\n                                         \"1st.OnEnvironmentsTearDownStart\",\n                                         \"2nd.OnEnvironmentsTearDownStart\",\n                                         \"3rd.OnEnvironmentsTearDownStart\",\n                                         \"Environment::TearDown\",\n                                         \"3rd.OnEnvironmentsTearDownEnd\",\n                                         \"2nd.OnEnvironmentsTearDownEnd\",\n                                         \"1st.OnEnvironmentsTearDownEnd\",\n                                         \"3rd.OnTestIterationEnd(0)\",\n                                         \"2nd.OnTestIterationEnd(0)\",\n                                         \"1st.OnTestIterationEnd(0)\",\n                                         \"1st.OnTestIterationStart(1)\",\n                                         \"2nd.OnTestIterationStart(1)\",\n                                         \"3rd.OnTestIterationStart(1)\",\n                                         \"1st.OnEnvironmentsSetUpStart\",\n                                         \"2nd.OnEnvironmentsSetUpStart\",\n                                         \"3rd.OnEnvironmentsSetUpStart\",\n                                         \"Environment::SetUp\",\n                                         \"3rd.OnEnvironmentsSetUpEnd\",\n                                         \"2nd.OnEnvironmentsSetUpEnd\",\n                                         \"1st.OnEnvironmentsSetUpEnd\",\n                                         \"3rd.OnTestSuiteStart\",\n                                         \"ListenerTest::SetUpTestSuite\",\n                                         \"1st.OnTestStart\",\n                                         \"2nd.OnTestStart\",\n                                         \"3rd.OnTestStart\",\n                                         \"ListenerTest::SetUp\",\n                                         \"ListenerTest::* Test Body\",\n                                         \"1st.OnTestPartResult\",\n                                         \"2nd.OnTestPartResult\",\n                                         \"3rd.OnTestPartResult\",\n                                         \"ListenerTest::TearDown\",\n                                         \"3rd.OnTestEnd\",\n                                         \"2nd.OnTestEnd\",\n                                         \"1st.OnTestEnd\",\n                                         \"1st.OnTestStart\",\n                                         \"2nd.OnTestStart\",\n                                         \"3rd.OnTestStart\",\n                                         \"ListenerTest::SetUp\",\n                                         \"ListenerTest::* Test Body\",\n                                         \"1st.OnTestPartResult\",\n                                         \"2nd.OnTestPartResult\",\n                                         \"3rd.OnTestPartResult\",\n                                         \"ListenerTest::TearDown\",\n                                         \"3rd.OnTestEnd\",\n                                         \"2nd.OnTestEnd\",\n                                         \"1st.OnTestEnd\",\n                                         \"ListenerTest::TearDownTestSuite\",\n                                         \"3rd.OnTestSuiteEnd\",\n                                         \"1st.OnEnvironmentsTearDownStart\",\n                                         \"2nd.OnEnvironmentsTearDownStart\",\n                                         \"3rd.OnEnvironmentsTearDownStart\",\n                                         \"Environment::TearDown\",\n                                         \"3rd.OnEnvironmentsTearDownEnd\",\n                                         \"2nd.OnEnvironmentsTearDownEnd\",\n                                         \"1st.OnEnvironmentsTearDownEnd\",\n                                         \"3rd.OnTestIterationEnd(1)\",\n                                         \"2nd.OnTestIterationEnd(1)\",\n                                         \"1st.OnTestIterationEnd(1)\",\n                                         \"3rd.OnTestProgramEnd\",\n                                         \"2nd.OnTestProgramEnd\",\n                                         \"1st.OnTestProgramEnd\"};\n#endif  // GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n  VerifyResults(events, expected_events,\n                sizeof(expected_events) / sizeof(expected_events[0]));\n\n  // We need to check manually for ad hoc test failures that happen after\n  // RUN_ALL_TESTS finishes.\n  if (UnitTest::GetInstance()->Failed()) ret_val = 1;\n\n  return ret_val;\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-message-test.cc",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// Tests for the Message class.\n\n#include \"gtest/gtest-message.h\"\n#include \"gtest/gtest.h\"\n\nnamespace {\n\nusing ::testing::Message;\n\n// Tests the testing::Message class\n\n// Tests the default constructor.\nTEST(MessageTest, DefaultConstructor) {\n  const Message msg;\n  EXPECT_EQ(\"\", msg.GetString());\n}\n\n// Tests the copy constructor.\nTEST(MessageTest, CopyConstructor) {\n  const Message msg1(\"Hello\");\n  const Message msg2(msg1);\n  EXPECT_EQ(\"Hello\", msg2.GetString());\n}\n\n// Tests constructing a Message from a C-string.\nTEST(MessageTest, ConstructsFromCString) {\n  Message msg(\"Hello\");\n  EXPECT_EQ(\"Hello\", msg.GetString());\n}\n\n// Tests streaming a float.\nTEST(MessageTest, StreamsFloat) {\n  const std::string s = (Message() << 1.23456F << \" \" << 2.34567F).GetString();\n  // Both numbers should be printed with enough precision.\n  EXPECT_PRED_FORMAT2(testing::IsSubstring, \"1.234560\", s.c_str());\n  EXPECT_PRED_FORMAT2(testing::IsSubstring, \" 2.345669\", s.c_str());\n}\n\n// Tests streaming a double.\nTEST(MessageTest, StreamsDouble) {\n  const std::string s =\n      (Message() << 1260570880.4555497 << \" \" << 1260572265.1954534)\n          .GetString();\n  // Both numbers should be printed with enough precision.\n  EXPECT_PRED_FORMAT2(testing::IsSubstring, \"1260570880.45\", s.c_str());\n  EXPECT_PRED_FORMAT2(testing::IsSubstring, \" 1260572265.19\", s.c_str());\n}\n\n// Tests streaming a non-char pointer.\nTEST(MessageTest, StreamsPointer) {\n  int n = 0;\n  int* p = &n;\n  EXPECT_NE(\"(null)\", (Message() << p).GetString());\n}\n\n// Tests streaming a NULL non-char pointer.\nTEST(MessageTest, StreamsNullPointer) {\n  int* p = nullptr;\n  EXPECT_EQ(\"(null)\", (Message() << p).GetString());\n}\n\n// Tests streaming a C string.\nTEST(MessageTest, StreamsCString) {\n  EXPECT_EQ(\"Foo\", (Message() << \"Foo\").GetString());\n}\n\n// Tests streaming a NULL C string.\nTEST(MessageTest, StreamsNullCString) {\n  char* p = nullptr;\n  EXPECT_EQ(\"(null)\", (Message() << p).GetString());\n}\n\n// Tests streaming std::string.\nTEST(MessageTest, StreamsString) {\n  const ::std::string str(\"Hello\");\n  EXPECT_EQ(\"Hello\", (Message() << str).GetString());\n}\n\n// Tests that we can output strings containing embedded NULs.\nTEST(MessageTest, StreamsStringWithEmbeddedNUL) {\n  const char char_array_with_nul[] = \"Here's a NUL\\0 and some more string\";\n  const ::std::string string_with_nul(char_array_with_nul,\n                                      sizeof(char_array_with_nul) - 1);\n  EXPECT_EQ(\"Here's a NUL\\\\0 and some more string\",\n            (Message() << string_with_nul).GetString());\n}\n\n// Tests streaming a NUL char.\nTEST(MessageTest, StreamsNULChar) {\n  EXPECT_EQ(\"\\\\0\", (Message() << '\\0').GetString());\n}\n\n// Tests streaming int.\nTEST(MessageTest, StreamsInt) {\n  EXPECT_EQ(\"123\", (Message() << 123).GetString());\n}\n\n// Tests that basic IO manipulators (endl, ends, and flush) can be\n// streamed to Message.\nTEST(MessageTest, StreamsBasicIoManip) {\n  EXPECT_EQ(\n      \"Line 1.\\nA NUL char \\\\0 in line 2.\",\n      (Message() << \"Line 1.\" << std::endl\n                 << \"A NUL char \" << std::ends << std::flush << \" in line 2.\")\n          .GetString());\n}\n\n// Tests Message::GetString()\nTEST(MessageTest, GetString) {\n  Message msg;\n  msg << 1 << \" lamb\";\n  EXPECT_EQ(\"1 lamb\", msg.GetString());\n}\n\n// Tests streaming a Message object to an ostream.\nTEST(MessageTest, StreamsToOStream) {\n  Message msg(\"Hello\");\n  ::std::stringstream ss;\n  ss << msg;\n  EXPECT_EQ(\"Hello\", testing::internal::StringStreamToString(&ss));\n}\n\n// Tests that a Message object doesn't take up too much stack space.\nTEST(MessageTest, DoesNotTakeUpMuchStackSpace) {\n  EXPECT_LE(sizeof(Message), 16U);\n}\n\n}  // namespace\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-options-test.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Google Test UnitTestOptions tests\n//\n// This file tests classes and functions used internally by\n// Google Test.  They are subject to change without notice.\n//\n// This file is #included from gtest.cc, to avoid changing build or\n// make-files on Windows and other platforms. Do not #include this file\n// anywhere else!\n\n#include \"gtest/gtest.h\"\n\n#if GTEST_OS_WINDOWS_MOBILE\n#include <windows.h>\n#elif GTEST_OS_WINDOWS\n#include <direct.h>\n#elif GTEST_OS_OS2\n// For strcasecmp on OS/2\n#include <strings.h>\n#endif  // GTEST_OS_WINDOWS_MOBILE\n\n#include \"src/gtest-internal-inl.h\"\n\nnamespace testing {\nnamespace internal {\nnamespace {\n\n// Turns the given relative path into an absolute path.\nFilePath GetAbsolutePathOf(const FilePath& relative_path) {\n  return FilePath::ConcatPaths(FilePath::GetCurrentDir(), relative_path);\n}\n\n// Testing UnitTestOptions::GetOutputFormat/GetOutputFile.\n\nTEST(XmlOutputTest, GetOutputFormatDefault) {\n  GTEST_FLAG_SET(output, \"\");\n  EXPECT_STREQ(\"\", UnitTestOptions::GetOutputFormat().c_str());\n}\n\nTEST(XmlOutputTest, GetOutputFormat) {\n  GTEST_FLAG_SET(output, \"xml:filename\");\n  EXPECT_STREQ(\"xml\", UnitTestOptions::GetOutputFormat().c_str());\n}\n\nTEST(XmlOutputTest, GetOutputFileDefault) {\n  GTEST_FLAG_SET(output, \"\");\n  EXPECT_EQ(GetAbsolutePathOf(FilePath(\"test_detail.xml\")).string(),\n            UnitTestOptions::GetAbsolutePathToOutputFile());\n}\n\nTEST(XmlOutputTest, GetOutputFileSingleFile) {\n  GTEST_FLAG_SET(output, \"xml:filename.abc\");\n  EXPECT_EQ(GetAbsolutePathOf(FilePath(\"filename.abc\")).string(),\n            UnitTestOptions::GetAbsolutePathToOutputFile());\n}\n\nTEST(XmlOutputTest, GetOutputFileFromDirectoryPath) {\n  GTEST_FLAG_SET(output, \"xml:path\" GTEST_PATH_SEP_);\n  const std::string expected_output_file =\n      GetAbsolutePathOf(FilePath(std::string(\"path\") + GTEST_PATH_SEP_ +\n                                 GetCurrentExecutableName().string() + \".xml\"))\n          .string();\n  const std::string& output_file =\n      UnitTestOptions::GetAbsolutePathToOutputFile();\n#if GTEST_OS_WINDOWS\n  EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str());\n#else\n  EXPECT_EQ(expected_output_file, output_file.c_str());\n#endif\n}\n\nTEST(OutputFileHelpersTest, GetCurrentExecutableName) {\n  const std::string exe_str = GetCurrentExecutableName().string();\n#if GTEST_OS_WINDOWS\n  const bool success =\n      _strcmpi(\"googletest-options-test\", exe_str.c_str()) == 0 ||\n      _strcmpi(\"gtest-options-ex_test\", exe_str.c_str()) == 0 ||\n      _strcmpi(\"gtest_all_test\", exe_str.c_str()) == 0 ||\n      _strcmpi(\"gtest_dll_test\", exe_str.c_str()) == 0;\n#elif GTEST_OS_OS2\n  const bool success =\n      strcasecmp(\"googletest-options-test\", exe_str.c_str()) == 0 ||\n      strcasecmp(\"gtest-options-ex_test\", exe_str.c_str()) == 0 ||\n      strcasecmp(\"gtest_all_test\", exe_str.c_str()) == 0 ||\n      strcasecmp(\"gtest_dll_test\", exe_str.c_str()) == 0;\n#elif GTEST_OS_FUCHSIA\n  const bool success = exe_str == \"app\";\n#else\n  const bool success =\n      exe_str == \"googletest-options-test\" || exe_str == \"gtest_all_test\" ||\n      exe_str == \"lt-gtest_all_test\" || exe_str == \"gtest_dll_test\";\n#endif  // GTEST_OS_WINDOWS\n  if (!success) FAIL() << \"GetCurrentExecutableName() returns \" << exe_str;\n}\n\n#if !GTEST_OS_FUCHSIA\n\nclass XmlOutputChangeDirTest : public Test {\n protected:\n  void SetUp() override {\n    original_working_dir_ = FilePath::GetCurrentDir();\n    posix::ChDir(\"..\");\n    // This will make the test fail if run from the root directory.\n    EXPECT_NE(original_working_dir_.string(),\n              FilePath::GetCurrentDir().string());\n  }\n\n  void TearDown() override {\n    posix::ChDir(original_working_dir_.string().c_str());\n  }\n\n  FilePath original_working_dir_;\n};\n\nTEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefault) {\n  GTEST_FLAG_SET(output, \"\");\n  EXPECT_EQ(\n      FilePath::ConcatPaths(original_working_dir_, FilePath(\"test_detail.xml\"))\n          .string(),\n      UnitTestOptions::GetAbsolutePathToOutputFile());\n}\n\nTEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithDefaultXML) {\n  GTEST_FLAG_SET(output, \"xml\");\n  EXPECT_EQ(\n      FilePath::ConcatPaths(original_working_dir_, FilePath(\"test_detail.xml\"))\n          .string(),\n      UnitTestOptions::GetAbsolutePathToOutputFile());\n}\n\nTEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativeFile) {\n  GTEST_FLAG_SET(output, \"xml:filename.abc\");\n  EXPECT_EQ(\n      FilePath::ConcatPaths(original_working_dir_, FilePath(\"filename.abc\"))\n          .string(),\n      UnitTestOptions::GetAbsolutePathToOutputFile());\n}\n\nTEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithRelativePath) {\n  GTEST_FLAG_SET(output, \"xml:path\" GTEST_PATH_SEP_);\n  const std::string expected_output_file =\n      FilePath::ConcatPaths(\n          original_working_dir_,\n          FilePath(std::string(\"path\") + GTEST_PATH_SEP_ +\n                   GetCurrentExecutableName().string() + \".xml\"))\n          .string();\n  const std::string& output_file =\n      UnitTestOptions::GetAbsolutePathToOutputFile();\n#if GTEST_OS_WINDOWS\n  EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str());\n#else\n  EXPECT_EQ(expected_output_file, output_file.c_str());\n#endif\n}\n\nTEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsoluteFile) {\n#if GTEST_OS_WINDOWS\n  GTEST_FLAG_SET(output, \"xml:c:\\\\tmp\\\\filename.abc\");\n  EXPECT_EQ(FilePath(\"c:\\\\tmp\\\\filename.abc\").string(),\n            UnitTestOptions::GetAbsolutePathToOutputFile());\n#else\n  GTEST_FLAG_SET(output, \"xml:/tmp/filename.abc\");\n  EXPECT_EQ(FilePath(\"/tmp/filename.abc\").string(),\n            UnitTestOptions::GetAbsolutePathToOutputFile());\n#endif\n}\n\nTEST_F(XmlOutputChangeDirTest, PreserveOriginalWorkingDirWithAbsolutePath) {\n#if GTEST_OS_WINDOWS\n  const std::string path = \"c:\\\\tmp\\\\\";\n#else\n  const std::string path = \"/tmp/\";\n#endif\n\n  GTEST_FLAG_SET(output, \"xml:\" + path);\n  const std::string expected_output_file =\n      path + GetCurrentExecutableName().string() + \".xml\";\n  const std::string& output_file =\n      UnitTestOptions::GetAbsolutePathToOutputFile();\n\n#if GTEST_OS_WINDOWS\n  EXPECT_STRCASEEQ(expected_output_file.c_str(), output_file.c_str());\n#else\n  EXPECT_EQ(expected_output_file, output_file.c_str());\n#endif\n}\n\n#endif  // !GTEST_OS_FUCHSIA\n\n}  // namespace\n}  // namespace internal\n}  // namespace testing\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-output-test-golden-lin.txt",
    "content": "The non-test part of the code is expected to have 2 failures.\n\ngoogletest-output-test_.cc:#: Failure\nValue of: false\n  Actual: false\nExpected: true\nStack trace: (omitted)\n\ngoogletest-output-test_.cc:#: Failure\nExpected equality of these values:\n  2\n  3\nStack trace: (omitted)\n\n\u001b[0;32m[==========] \u001b[mRunning 89 tests from 42 test suites.\n\u001b[0;32m[----------] \u001b[mGlobal test environment set-up.\nFooEnvironment::SetUp() called.\nBarEnvironment::SetUp() called.\n\u001b[0;32m[----------] \u001b[m1 test from ADeathTest\n\u001b[0;32m[ RUN      ] \u001b[mADeathTest.ShouldRunFirst\n\u001b[0;32m[       OK ] \u001b[mADeathTest.ShouldRunFirst\n\u001b[0;32m[----------] \u001b[m1 test from ATypedDeathTest/0, where TypeParam = int\n\u001b[0;32m[ RUN      ] \u001b[mATypedDeathTest/0.ShouldRunFirst\n\u001b[0;32m[       OK ] \u001b[mATypedDeathTest/0.ShouldRunFirst\n\u001b[0;32m[----------] \u001b[m1 test from ATypedDeathTest/1, where TypeParam = double\n\u001b[0;32m[ RUN      ] \u001b[mATypedDeathTest/1.ShouldRunFirst\n\u001b[0;32m[       OK ] \u001b[mATypedDeathTest/1.ShouldRunFirst\n\u001b[0;32m[----------] \u001b[m1 test from My/ATypeParamDeathTest/0, where TypeParam = int\n\u001b[0;32m[ RUN      ] \u001b[mMy/ATypeParamDeathTest/0.ShouldRunFirst\n\u001b[0;32m[       OK ] \u001b[mMy/ATypeParamDeathTest/0.ShouldRunFirst\n\u001b[0;32m[----------] \u001b[m1 test from My/ATypeParamDeathTest/1, where TypeParam = double\n\u001b[0;32m[ RUN      ] \u001b[mMy/ATypeParamDeathTest/1.ShouldRunFirst\n\u001b[0;32m[       OK ] \u001b[mMy/ATypeParamDeathTest/1.ShouldRunFirst\n\u001b[0;32m[----------] \u001b[m2 tests from PassingTest\n\u001b[0;32m[ RUN      ] \u001b[mPassingTest.PassingTest1\n\u001b[0;32m[       OK ] \u001b[mPassingTest.PassingTest1\n\u001b[0;32m[ RUN      ] \u001b[mPassingTest.PassingTest2\n\u001b[0;32m[       OK ] \u001b[mPassingTest.PassingTest2\n\u001b[0;32m[----------] \u001b[m2 tests from NonfatalFailureTest\n\u001b[0;32m[ RUN      ] \u001b[mNonfatalFailureTest.EscapesStringOperands\ngoogletest-output-test_.cc:#: Failure\nExpected equality of these values:\n  kGoldenString\n    Which is: \"\\\"Line\"\n  actual\n    Which is: \"actual \\\"string\\\"\"\nStack trace: (omitted)\n\ngoogletest-output-test_.cc:#: Failure\nExpected equality of these values:\n  golden\n    Which is: \"\\\"Line\"\n  actual\n    Which is: \"actual \\\"string\\\"\"\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mNonfatalFailureTest.EscapesStringOperands\n\u001b[0;32m[ RUN      ] \u001b[mNonfatalFailureTest.DiffForLongStrings\ngoogletest-output-test_.cc:#: Failure\nExpected equality of these values:\n  golden_str\n    Which is: \"\\\"Line\\0 1\\\"\\nLine 2\"\n  \"Line 2\"\nWith diff:\n@@ -1,2 @@\n-\\\"Line\\0 1\\\"\n Line 2\n\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mNonfatalFailureTest.DiffForLongStrings\n\u001b[0;32m[----------] \u001b[m3 tests from FatalFailureTest\n\u001b[0;32m[ RUN      ] \u001b[mFatalFailureTest.FatalFailureInSubroutine\n(expecting a failure that x should be 1)\ngoogletest-output-test_.cc:#: Failure\nExpected equality of these values:\n  1\n  x\n    Which is: 2\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mFatalFailureTest.FatalFailureInSubroutine\n\u001b[0;32m[ RUN      ] \u001b[mFatalFailureTest.FatalFailureInNestedSubroutine\n(expecting a failure that x should be 1)\ngoogletest-output-test_.cc:#: Failure\nExpected equality of these values:\n  1\n  x\n    Which is: 2\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mFatalFailureTest.FatalFailureInNestedSubroutine\n\u001b[0;32m[ RUN      ] \u001b[mFatalFailureTest.NonfatalFailureInSubroutine\n(expecting a failure on false)\ngoogletest-output-test_.cc:#: Failure\nValue of: false\n  Actual: false\nExpected: true\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mFatalFailureTest.NonfatalFailureInSubroutine\n\u001b[0;32m[----------] \u001b[m1 test from LoggingTest\n\u001b[0;32m[ RUN      ] \u001b[mLoggingTest.InterleavingLoggingAndAssertions\n(expecting 2 failures on (3) >= (a[i]))\ni == 0\ni == 1\ngoogletest-output-test_.cc:#: Failure\nExpected: (3) >= (a[i]), actual: 3 vs 9\nStack trace: (omitted)\n\ni == 2\ni == 3\ngoogletest-output-test_.cc:#: Failure\nExpected: (3) >= (a[i]), actual: 3 vs 6\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mLoggingTest.InterleavingLoggingAndAssertions\n\u001b[0;32m[----------] \u001b[m7 tests from SCOPED_TRACETest\n\u001b[0;32m[ RUN      ] \u001b[mSCOPED_TRACETest.AcceptedValues\ngoogletest-output-test_.cc:#: Failure\nFailed\nJust checking that all these values work fine.\nGoogle Test trace:\ngoogletest-output-test_.cc:#: (null)\ngoogletest-output-test_.cc:#: 1337\ngoogletest-output-test_.cc:#: std::string\ngoogletest-output-test_.cc:#: literal string\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mSCOPED_TRACETest.AcceptedValues\n\u001b[0;32m[ RUN      ] \u001b[mSCOPED_TRACETest.ObeysScopes\n(expected to fail)\ngoogletest-output-test_.cc:#: Failure\nFailed\nThis failure is expected, and shouldn't have a trace.\nStack trace: (omitted)\n\ngoogletest-output-test_.cc:#: Failure\nFailed\nThis failure is expected, and should have a trace.\nGoogle Test trace:\ngoogletest-output-test_.cc:#: Expected trace\nStack trace: (omitted)\n\ngoogletest-output-test_.cc:#: Failure\nFailed\nThis failure is expected, and shouldn't have a trace.\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mSCOPED_TRACETest.ObeysScopes\n\u001b[0;32m[ RUN      ] \u001b[mSCOPED_TRACETest.WorksInLoop\n(expected to fail)\ngoogletest-output-test_.cc:#: Failure\nExpected equality of these values:\n  2\n  n\n    Which is: 1\nGoogle Test trace:\ngoogletest-output-test_.cc:#: i = 1\nStack trace: (omitted)\n\ngoogletest-output-test_.cc:#: Failure\nExpected equality of these values:\n  1\n  n\n    Which is: 2\nGoogle Test trace:\ngoogletest-output-test_.cc:#: i = 2\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mSCOPED_TRACETest.WorksInLoop\n\u001b[0;32m[ RUN      ] \u001b[mSCOPED_TRACETest.WorksInSubroutine\n(expected to fail)\ngoogletest-output-test_.cc:#: Failure\nExpected equality of these values:\n  2\n  n\n    Which is: 1\nGoogle Test trace:\ngoogletest-output-test_.cc:#: n = 1\nStack trace: (omitted)\n\ngoogletest-output-test_.cc:#: Failure\nExpected equality of these values:\n  1\n  n\n    Which is: 2\nGoogle Test trace:\ngoogletest-output-test_.cc:#: n = 2\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mSCOPED_TRACETest.WorksInSubroutine\n\u001b[0;32m[ RUN      ] \u001b[mSCOPED_TRACETest.CanBeNested\n(expected to fail)\ngoogletest-output-test_.cc:#: Failure\nExpected equality of these values:\n  1\n  n\n    Which is: 2\nGoogle Test trace:\ngoogletest-output-test_.cc:#: n = 2\ngoogletest-output-test_.cc:#: \nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mSCOPED_TRACETest.CanBeNested\n\u001b[0;32m[ RUN      ] \u001b[mSCOPED_TRACETest.CanBeRepeated\n(expected to fail)\ngoogletest-output-test_.cc:#: Failure\nFailed\nThis failure is expected, and should contain trace point A.\nGoogle Test trace:\ngoogletest-output-test_.cc:#: A\nStack trace: (omitted)\n\ngoogletest-output-test_.cc:#: Failure\nFailed\nThis failure is expected, and should contain trace point A and B.\nGoogle Test trace:\ngoogletest-output-test_.cc:#: B\ngoogletest-output-test_.cc:#: A\nStack trace: (omitted)\n\ngoogletest-output-test_.cc:#: Failure\nFailed\nThis failure is expected, and should contain trace point A, B, and C.\nGoogle Test trace:\ngoogletest-output-test_.cc:#: C\ngoogletest-output-test_.cc:#: B\ngoogletest-output-test_.cc:#: A\nStack trace: (omitted)\n\ngoogletest-output-test_.cc:#: Failure\nFailed\nThis failure is expected, and should contain trace point A, B, and D.\nGoogle Test trace:\ngoogletest-output-test_.cc:#: D\ngoogletest-output-test_.cc:#: B\ngoogletest-output-test_.cc:#: A\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mSCOPED_TRACETest.CanBeRepeated\n\u001b[0;32m[ RUN      ] \u001b[mSCOPED_TRACETest.WorksConcurrently\n(expecting 6 failures)\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected failure #1 (in thread B, only trace B alive).\nGoogle Test trace:\ngoogletest-output-test_.cc:#: Trace B\nStack trace: (omitted)\n\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected failure #2 (in thread A, trace A & B both alive).\nGoogle Test trace:\ngoogletest-output-test_.cc:#: Trace A\nStack trace: (omitted)\n\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected failure #3 (in thread B, trace A & B both alive).\nGoogle Test trace:\ngoogletest-output-test_.cc:#: Trace B\nStack trace: (omitted)\n\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected failure #4 (in thread B, only trace A alive).\nStack trace: (omitted)\n\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected failure #5 (in thread A, only trace A alive).\nGoogle Test trace:\ngoogletest-output-test_.cc:#: Trace A\nStack trace: (omitted)\n\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected failure #6 (in thread A, no trace alive).\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mSCOPED_TRACETest.WorksConcurrently\n\u001b[0;32m[----------] \u001b[m1 test from ScopedTraceTest\n\u001b[0;32m[ RUN      ] \u001b[mScopedTraceTest.WithExplicitFileAndLine\ngoogletest-output-test_.cc:#: Failure\nFailed\nCheck that the trace is attached to a particular location.\nGoogle Test trace:\nexplicit_file.cc:123: expected trace message\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mScopedTraceTest.WithExplicitFileAndLine\n\u001b[0;32m[----------] \u001b[m1 test from NonFatalFailureInFixtureConstructorTest\n\u001b[0;32m[ RUN      ] \u001b[mNonFatalFailureInFixtureConstructorTest.FailureInConstructor\n(expecting 5 failures)\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected failure #1, in the test fixture c'tor.\nStack trace: (omitted)\n\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected failure #2, in SetUp().\nStack trace: (omitted)\n\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected failure #3, in the test body.\nStack trace: (omitted)\n\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected failure #4, in TearDown.\nStack trace: (omitted)\n\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected failure #5, in the test fixture d'tor.\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mNonFatalFailureInFixtureConstructorTest.FailureInConstructor\n\u001b[0;32m[----------] \u001b[m1 test from FatalFailureInFixtureConstructorTest\n\u001b[0;32m[ RUN      ] \u001b[mFatalFailureInFixtureConstructorTest.FailureInConstructor\n(expecting 2 failures)\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected failure #1, in the test fixture c'tor.\nStack trace: (omitted)\n\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected failure #2, in the test fixture d'tor.\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mFatalFailureInFixtureConstructorTest.FailureInConstructor\n\u001b[0;32m[----------] \u001b[m1 test from NonFatalFailureInSetUpTest\n\u001b[0;32m[ RUN      ] \u001b[mNonFatalFailureInSetUpTest.FailureInSetUp\n(expecting 4 failures)\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected failure #1, in SetUp().\nStack trace: (omitted)\n\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected failure #2, in the test function.\nStack trace: (omitted)\n\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected failure #3, in TearDown().\nStack trace: (omitted)\n\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected failure #4, in the test fixture d'tor.\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mNonFatalFailureInSetUpTest.FailureInSetUp\n\u001b[0;32m[----------] \u001b[m1 test from FatalFailureInSetUpTest\n\u001b[0;32m[ RUN      ] \u001b[mFatalFailureInSetUpTest.FailureInSetUp\n(expecting 3 failures)\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected failure #1, in SetUp().\nStack trace: (omitted)\n\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected failure #2, in TearDown().\nStack trace: (omitted)\n\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected failure #3, in the test fixture d'tor.\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mFatalFailureInSetUpTest.FailureInSetUp\n\u001b[0;32m[----------] \u001b[m1 test from AddFailureAtTest\n\u001b[0;32m[ RUN      ] \u001b[mAddFailureAtTest.MessageContainsSpecifiedFileAndLineNumber\nfoo.cc:42: Failure\nFailed\nExpected nonfatal failure in foo.cc\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mAddFailureAtTest.MessageContainsSpecifiedFileAndLineNumber\n\u001b[0;32m[----------] \u001b[m1 test from GtestFailAtTest\n\u001b[0;32m[ RUN      ] \u001b[mGtestFailAtTest.MessageContainsSpecifiedFileAndLineNumber\nfoo.cc:42: Failure\nFailed\nExpected fatal failure in foo.cc\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mGtestFailAtTest.MessageContainsSpecifiedFileAndLineNumber\n\u001b[0;32m[----------] \u001b[m4 tests from MixedUpTestSuiteTest\n\u001b[0;32m[ RUN      ] \u001b[mMixedUpTestSuiteTest.FirstTestFromNamespaceFoo\n\u001b[0;32m[       OK ] \u001b[mMixedUpTestSuiteTest.FirstTestFromNamespaceFoo\n\u001b[0;32m[ RUN      ] \u001b[mMixedUpTestSuiteTest.SecondTestFromNamespaceFoo\n\u001b[0;32m[       OK ] \u001b[mMixedUpTestSuiteTest.SecondTestFromNamespaceFoo\n\u001b[0;32m[ RUN      ] \u001b[mMixedUpTestSuiteTest.ThisShouldFail\ngtest.cc:#: Failure\nFailed\nAll tests in the same test suite must use the same test fixture\nclass.  However, in test suite MixedUpTestSuiteTest,\nyou defined test FirstTestFromNamespaceFoo and test ThisShouldFail\nusing two different test fixture classes.  This can happen if\nthe two classes are from different namespaces or translation\nunits and have the same name.  You should probably rename one\nof the classes to put the tests into different test suites.\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mMixedUpTestSuiteTest.ThisShouldFail\n\u001b[0;32m[ RUN      ] \u001b[mMixedUpTestSuiteTest.ThisShouldFailToo\ngtest.cc:#: Failure\nFailed\nAll tests in the same test suite must use the same test fixture\nclass.  However, in test suite MixedUpTestSuiteTest,\nyou defined test FirstTestFromNamespaceFoo and test ThisShouldFailToo\nusing two different test fixture classes.  This can happen if\nthe two classes are from different namespaces or translation\nunits and have the same name.  You should probably rename one\nof the classes to put the tests into different test suites.\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mMixedUpTestSuiteTest.ThisShouldFailToo\n\u001b[0;32m[----------] \u001b[m2 tests from MixedUpTestSuiteWithSameTestNameTest\n\u001b[0;32m[ RUN      ] \u001b[mMixedUpTestSuiteWithSameTestNameTest.TheSecondTestWithThisNameShouldFail\n\u001b[0;32m[       OK ] \u001b[mMixedUpTestSuiteWithSameTestNameTest.TheSecondTestWithThisNameShouldFail\n\u001b[0;32m[ RUN      ] \u001b[mMixedUpTestSuiteWithSameTestNameTest.TheSecondTestWithThisNameShouldFail\ngtest.cc:#: Failure\nFailed\nAll tests in the same test suite must use the same test fixture\nclass.  However, in test suite MixedUpTestSuiteWithSameTestNameTest,\nyou defined test TheSecondTestWithThisNameShouldFail and test TheSecondTestWithThisNameShouldFail\nusing two different test fixture classes.  This can happen if\nthe two classes are from different namespaces or translation\nunits and have the same name.  You should probably rename one\nof the classes to put the tests into different test suites.\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mMixedUpTestSuiteWithSameTestNameTest.TheSecondTestWithThisNameShouldFail\n\u001b[0;32m[----------] \u001b[m2 tests from TEST_F_before_TEST_in_same_test_case\n\u001b[0;32m[ RUN      ] \u001b[mTEST_F_before_TEST_in_same_test_case.DefinedUsingTEST_F\n\u001b[0;32m[       OK ] \u001b[mTEST_F_before_TEST_in_same_test_case.DefinedUsingTEST_F\n\u001b[0;32m[ RUN      ] \u001b[mTEST_F_before_TEST_in_same_test_case.DefinedUsingTESTAndShouldFail\ngtest.cc:#: Failure\nFailed\nAll tests in the same test suite must use the same test fixture\nclass, so mixing TEST_F and TEST in the same test suite is\nillegal.  In test suite TEST_F_before_TEST_in_same_test_case,\ntest DefinedUsingTEST_F is defined using TEST_F but\ntest DefinedUsingTESTAndShouldFail is defined using TEST.  You probably\nwant to change the TEST to TEST_F or move it to another test\ncase.\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mTEST_F_before_TEST_in_same_test_case.DefinedUsingTESTAndShouldFail\n\u001b[0;32m[----------] \u001b[m2 tests from TEST_before_TEST_F_in_same_test_case\n\u001b[0;32m[ RUN      ] \u001b[mTEST_before_TEST_F_in_same_test_case.DefinedUsingTEST\n\u001b[0;32m[       OK ] \u001b[mTEST_before_TEST_F_in_same_test_case.DefinedUsingTEST\n\u001b[0;32m[ RUN      ] \u001b[mTEST_before_TEST_F_in_same_test_case.DefinedUsingTEST_FAndShouldFail\ngtest.cc:#: Failure\nFailed\nAll tests in the same test suite must use the same test fixture\nclass, so mixing TEST_F and TEST in the same test suite is\nillegal.  In test suite TEST_before_TEST_F_in_same_test_case,\ntest DefinedUsingTEST_FAndShouldFail is defined using TEST_F but\ntest DefinedUsingTEST is defined using TEST.  You probably\nwant to change the TEST to TEST_F or move it to another test\ncase.\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mTEST_before_TEST_F_in_same_test_case.DefinedUsingTEST_FAndShouldFail\n\u001b[0;32m[----------] \u001b[m8 tests from ExpectNonfatalFailureTest\n\u001b[0;32m[ RUN      ] \u001b[mExpectNonfatalFailureTest.CanReferenceGlobalVariables\n\u001b[0;32m[       OK ] \u001b[mExpectNonfatalFailureTest.CanReferenceGlobalVariables\n\u001b[0;32m[ RUN      ] \u001b[mExpectNonfatalFailureTest.CanReferenceLocalVariables\n\u001b[0;32m[       OK ] \u001b[mExpectNonfatalFailureTest.CanReferenceLocalVariables\n\u001b[0;32m[ RUN      ] \u001b[mExpectNonfatalFailureTest.SucceedsWhenThereIsOneNonfatalFailure\n\u001b[0;32m[       OK ] \u001b[mExpectNonfatalFailureTest.SucceedsWhenThereIsOneNonfatalFailure\n\u001b[0;32m[ RUN      ] \u001b[mExpectNonfatalFailureTest.FailsWhenThereIsNoNonfatalFailure\n(expecting a failure)\ngtest.cc:#: Failure\nExpected: 1 non-fatal failure\n  Actual: 0 failures\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mExpectNonfatalFailureTest.FailsWhenThereIsNoNonfatalFailure\n\u001b[0;32m[ RUN      ] \u001b[mExpectNonfatalFailureTest.FailsWhenThereAreTwoNonfatalFailures\n(expecting a failure)\ngtest.cc:#: Failure\nExpected: 1 non-fatal failure\n  Actual: 2 failures\ngoogletest-output-test_.cc:#: Non-fatal failure:\nFailed\nExpected non-fatal failure 1.\nStack trace: (omitted)\n\n\ngoogletest-output-test_.cc:#: Non-fatal failure:\nFailed\nExpected non-fatal failure 2.\nStack trace: (omitted)\n\n\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mExpectNonfatalFailureTest.FailsWhenThereAreTwoNonfatalFailures\n\u001b[0;32m[ RUN      ] \u001b[mExpectNonfatalFailureTest.FailsWhenThereIsOneFatalFailure\n(expecting a failure)\ngtest.cc:#: Failure\nExpected: 1 non-fatal failure\n  Actual:\ngoogletest-output-test_.cc:#: Fatal failure:\nFailed\nExpected fatal failure.\nStack trace: (omitted)\n\n\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mExpectNonfatalFailureTest.FailsWhenThereIsOneFatalFailure\n\u001b[0;32m[ RUN      ] \u001b[mExpectNonfatalFailureTest.FailsWhenStatementReturns\n(expecting a failure)\ngtest.cc:#: Failure\nExpected: 1 non-fatal failure\n  Actual: 0 failures\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mExpectNonfatalFailureTest.FailsWhenStatementReturns\n\u001b[0;32m[ RUN      ] \u001b[mExpectNonfatalFailureTest.FailsWhenStatementThrows\n(expecting a failure)\ngtest.cc:#: Failure\nExpected: 1 non-fatal failure\n  Actual: 0 failures\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mExpectNonfatalFailureTest.FailsWhenStatementThrows\n\u001b[0;32m[----------] \u001b[m8 tests from ExpectFatalFailureTest\n\u001b[0;32m[ RUN      ] \u001b[mExpectFatalFailureTest.CanReferenceGlobalVariables\n\u001b[0;32m[       OK ] \u001b[mExpectFatalFailureTest.CanReferenceGlobalVariables\n\u001b[0;32m[ RUN      ] \u001b[mExpectFatalFailureTest.CanReferenceLocalStaticVariables\n\u001b[0;32m[       OK ] \u001b[mExpectFatalFailureTest.CanReferenceLocalStaticVariables\n\u001b[0;32m[ RUN      ] \u001b[mExpectFatalFailureTest.SucceedsWhenThereIsOneFatalFailure\n\u001b[0;32m[       OK ] \u001b[mExpectFatalFailureTest.SucceedsWhenThereIsOneFatalFailure\n\u001b[0;32m[ RUN      ] \u001b[mExpectFatalFailureTest.FailsWhenThereIsNoFatalFailure\n(expecting a failure)\ngtest.cc:#: Failure\nExpected: 1 fatal failure\n  Actual: 0 failures\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mExpectFatalFailureTest.FailsWhenThereIsNoFatalFailure\n\u001b[0;32m[ RUN      ] \u001b[mExpectFatalFailureTest.FailsWhenThereAreTwoFatalFailures\n(expecting a failure)\ngtest.cc:#: Failure\nExpected: 1 fatal failure\n  Actual: 2 failures\ngoogletest-output-test_.cc:#: Fatal failure:\nFailed\nExpected fatal failure.\nStack trace: (omitted)\n\n\ngoogletest-output-test_.cc:#: Fatal failure:\nFailed\nExpected fatal failure.\nStack trace: (omitted)\n\n\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mExpectFatalFailureTest.FailsWhenThereAreTwoFatalFailures\n\u001b[0;32m[ RUN      ] \u001b[mExpectFatalFailureTest.FailsWhenThereIsOneNonfatalFailure\n(expecting a failure)\ngtest.cc:#: Failure\nExpected: 1 fatal failure\n  Actual:\ngoogletest-output-test_.cc:#: Non-fatal failure:\nFailed\nExpected non-fatal failure.\nStack trace: (omitted)\n\n\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mExpectFatalFailureTest.FailsWhenThereIsOneNonfatalFailure\n\u001b[0;32m[ RUN      ] \u001b[mExpectFatalFailureTest.FailsWhenStatementReturns\n(expecting a failure)\ngtest.cc:#: Failure\nExpected: 1 fatal failure\n  Actual: 0 failures\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mExpectFatalFailureTest.FailsWhenStatementReturns\n\u001b[0;32m[ RUN      ] \u001b[mExpectFatalFailureTest.FailsWhenStatementThrows\n(expecting a failure)\ngtest.cc:#: Failure\nExpected: 1 fatal failure\n  Actual: 0 failures\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mExpectFatalFailureTest.FailsWhenStatementThrows\n\u001b[0;32m[----------] \u001b[m2 tests from TypedTest/0, where TypeParam = int\n\u001b[0;32m[ RUN      ] \u001b[mTypedTest/0.Success\n\u001b[0;32m[       OK ] \u001b[mTypedTest/0.Success\n\u001b[0;32m[ RUN      ] \u001b[mTypedTest/0.Failure\ngoogletest-output-test_.cc:#: Failure\nExpected equality of these values:\n  1\n  TypeParam()\n    Which is: 0\nExpected failure\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mTypedTest/0.Failure, where TypeParam = int\n\u001b[0;32m[----------] \u001b[m2 tests from TypedTestWithNames/char0, where TypeParam = char\n\u001b[0;32m[ RUN      ] \u001b[mTypedTestWithNames/char0.Success\n\u001b[0;32m[       OK ] \u001b[mTypedTestWithNames/char0.Success\n\u001b[0;32m[ RUN      ] \u001b[mTypedTestWithNames/char0.Failure\ngoogletest-output-test_.cc:#: Failure\nFailed\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mTypedTestWithNames/char0.Failure, where TypeParam = char\n\u001b[0;32m[----------] \u001b[m2 tests from TypedTestWithNames/int1, where TypeParam = int\n\u001b[0;32m[ RUN      ] \u001b[mTypedTestWithNames/int1.Success\n\u001b[0;32m[       OK ] \u001b[mTypedTestWithNames/int1.Success\n\u001b[0;32m[ RUN      ] \u001b[mTypedTestWithNames/int1.Failure\ngoogletest-output-test_.cc:#: Failure\nFailed\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mTypedTestWithNames/int1.Failure, where TypeParam = int\n\u001b[0;32m[----------] \u001b[m2 tests from Unsigned/TypedTestP/0, where TypeParam = unsigned char\n\u001b[0;32m[ RUN      ] \u001b[mUnsigned/TypedTestP/0.Success\n\u001b[0;32m[       OK ] \u001b[mUnsigned/TypedTestP/0.Success\n\u001b[0;32m[ RUN      ] \u001b[mUnsigned/TypedTestP/0.Failure\ngoogletest-output-test_.cc:#: Failure\nExpected equality of these values:\n  1U\n    Which is: 1\n  TypeParam()\n    Which is: '\\0'\nExpected failure\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mUnsigned/TypedTestP/0.Failure, where TypeParam = unsigned char\n\u001b[0;32m[----------] \u001b[m2 tests from Unsigned/TypedTestP/1, where TypeParam = unsigned int\n\u001b[0;32m[ RUN      ] \u001b[mUnsigned/TypedTestP/1.Success\n\u001b[0;32m[       OK ] \u001b[mUnsigned/TypedTestP/1.Success\n\u001b[0;32m[ RUN      ] \u001b[mUnsigned/TypedTestP/1.Failure\ngoogletest-output-test_.cc:#: Failure\nExpected equality of these values:\n  1U\n    Which is: 1\n  TypeParam()\n    Which is: 0\nExpected failure\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mUnsigned/TypedTestP/1.Failure, where TypeParam = unsigned int\n\u001b[0;32m[----------] \u001b[m2 tests from UnsignedCustomName/TypedTestP/unsignedChar0, where TypeParam = unsigned char\n\u001b[0;32m[ RUN      ] \u001b[mUnsignedCustomName/TypedTestP/unsignedChar0.Success\n\u001b[0;32m[       OK ] \u001b[mUnsignedCustomName/TypedTestP/unsignedChar0.Success\n\u001b[0;32m[ RUN      ] \u001b[mUnsignedCustomName/TypedTestP/unsignedChar0.Failure\ngoogletest-output-test_.cc:#: Failure\nExpected equality of these values:\n  1U\n    Which is: 1\n  TypeParam()\n    Which is: '\\0'\nExpected failure\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mUnsignedCustomName/TypedTestP/unsignedChar0.Failure, where TypeParam = unsigned char\n\u001b[0;32m[----------] \u001b[m2 tests from UnsignedCustomName/TypedTestP/unsignedInt1, where TypeParam = unsigned int\n\u001b[0;32m[ RUN      ] \u001b[mUnsignedCustomName/TypedTestP/unsignedInt1.Success\n\u001b[0;32m[       OK ] \u001b[mUnsignedCustomName/TypedTestP/unsignedInt1.Success\n\u001b[0;32m[ RUN      ] \u001b[mUnsignedCustomName/TypedTestP/unsignedInt1.Failure\ngoogletest-output-test_.cc:#: Failure\nExpected equality of these values:\n  1U\n    Which is: 1\n  TypeParam()\n    Which is: 0\nExpected failure\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mUnsignedCustomName/TypedTestP/unsignedInt1.Failure, where TypeParam = unsigned int\n\u001b[0;32m[----------] \u001b[m4 tests from ExpectFailureTest\n\u001b[0;32m[ RUN      ] \u001b[mExpectFailureTest.ExpectFatalFailure\n(expecting 1 failure)\ngtest.cc:#: Failure\nExpected: 1 fatal failure\n  Actual:\ngoogletest-output-test_.cc:#: Success:\nSucceeded\nStack trace: (omitted)\n\n\nStack trace: (omitted)\n\n(expecting 1 failure)\ngtest.cc:#: Failure\nExpected: 1 fatal failure\n  Actual:\ngoogletest-output-test_.cc:#: Non-fatal failure:\nFailed\nExpected non-fatal failure.\nStack trace: (omitted)\n\n\nStack trace: (omitted)\n\n(expecting 1 failure)\ngtest.cc:#: Failure\nExpected: 1 fatal failure containing \"Some other fatal failure expected.\"\n  Actual:\ngoogletest-output-test_.cc:#: Fatal failure:\nFailed\nExpected fatal failure.\nStack trace: (omitted)\n\n\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mExpectFailureTest.ExpectFatalFailure\n\u001b[0;32m[ RUN      ] \u001b[mExpectFailureTest.ExpectNonFatalFailure\n(expecting 1 failure)\ngtest.cc:#: Failure\nExpected: 1 non-fatal failure\n  Actual:\ngoogletest-output-test_.cc:#: Success:\nSucceeded\nStack trace: (omitted)\n\n\nStack trace: (omitted)\n\n(expecting 1 failure)\ngtest.cc:#: Failure\nExpected: 1 non-fatal failure\n  Actual:\ngoogletest-output-test_.cc:#: Fatal failure:\nFailed\nExpected fatal failure.\nStack trace: (omitted)\n\n\nStack trace: (omitted)\n\n(expecting 1 failure)\ngtest.cc:#: Failure\nExpected: 1 non-fatal failure containing \"Some other non-fatal failure.\"\n  Actual:\ngoogletest-output-test_.cc:#: Non-fatal failure:\nFailed\nExpected non-fatal failure.\nStack trace: (omitted)\n\n\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mExpectFailureTest.ExpectNonFatalFailure\n\u001b[0;32m[ RUN      ] \u001b[mExpectFailureTest.ExpectFatalFailureOnAllThreads\n(expecting 1 failure)\ngtest.cc:#: Failure\nExpected: 1 fatal failure\n  Actual:\ngoogletest-output-test_.cc:#: Success:\nSucceeded\nStack trace: (omitted)\n\n\nStack trace: (omitted)\n\n(expecting 1 failure)\ngtest.cc:#: Failure\nExpected: 1 fatal failure\n  Actual:\ngoogletest-output-test_.cc:#: Non-fatal failure:\nFailed\nExpected non-fatal failure.\nStack trace: (omitted)\n\n\nStack trace: (omitted)\n\n(expecting 1 failure)\ngtest.cc:#: Failure\nExpected: 1 fatal failure containing \"Some other fatal failure expected.\"\n  Actual:\ngoogletest-output-test_.cc:#: Fatal failure:\nFailed\nExpected fatal failure.\nStack trace: (omitted)\n\n\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mExpectFailureTest.ExpectFatalFailureOnAllThreads\n\u001b[0;32m[ RUN      ] \u001b[mExpectFailureTest.ExpectNonFatalFailureOnAllThreads\n(expecting 1 failure)\ngtest.cc:#: Failure\nExpected: 1 non-fatal failure\n  Actual:\ngoogletest-output-test_.cc:#: Success:\nSucceeded\nStack trace: (omitted)\n\n\nStack trace: (omitted)\n\n(expecting 1 failure)\ngtest.cc:#: Failure\nExpected: 1 non-fatal failure\n  Actual:\ngoogletest-output-test_.cc:#: Fatal failure:\nFailed\nExpected fatal failure.\nStack trace: (omitted)\n\n\nStack trace: (omitted)\n\n(expecting 1 failure)\ngtest.cc:#: Failure\nExpected: 1 non-fatal failure containing \"Some other non-fatal failure.\"\n  Actual:\ngoogletest-output-test_.cc:#: Non-fatal failure:\nFailed\nExpected non-fatal failure.\nStack trace: (omitted)\n\n\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mExpectFailureTest.ExpectNonFatalFailureOnAllThreads\n\u001b[0;32m[----------] \u001b[m2 tests from ExpectFailureWithThreadsTest\n\u001b[0;32m[ RUN      ] \u001b[mExpectFailureWithThreadsTest.ExpectFatalFailure\n(expecting 2 failures)\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected fatal failure.\nStack trace: (omitted)\n\ngtest.cc:#: Failure\nExpected: 1 fatal failure\n  Actual: 0 failures\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mExpectFailureWithThreadsTest.ExpectFatalFailure\n\u001b[0;32m[ RUN      ] \u001b[mExpectFailureWithThreadsTest.ExpectNonFatalFailure\n(expecting 2 failures)\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected non-fatal failure.\nStack trace: (omitted)\n\ngtest.cc:#: Failure\nExpected: 1 non-fatal failure\n  Actual: 0 failures\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mExpectFailureWithThreadsTest.ExpectNonFatalFailure\n\u001b[0;32m[----------] \u001b[m1 test from ScopedFakeTestPartResultReporterTest\n\u001b[0;32m[ RUN      ] \u001b[mScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread\n(expecting 2 failures)\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected fatal failure.\nStack trace: (omitted)\n\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected non-fatal failure.\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread\n\u001b[0;32m[----------] \u001b[m2 tests from DynamicFixture\nDynamicFixture::SetUpTestSuite\n\u001b[0;32m[ RUN      ] \u001b[mDynamicFixture.DynamicTestPass\nDynamicFixture()\nDynamicFixture::SetUp\nDynamicFixture::TearDown\n~DynamicFixture()\n\u001b[0;32m[       OK ] \u001b[mDynamicFixture.DynamicTestPass\n\u001b[0;32m[ RUN      ] \u001b[mDynamicFixture.DynamicTestFail\nDynamicFixture()\nDynamicFixture::SetUp\ngoogletest-output-test_.cc:#: Failure\nValue of: Pass\n  Actual: false\nExpected: true\nStack trace: (omitted)\n\nDynamicFixture::TearDown\n~DynamicFixture()\n\u001b[0;31m[  FAILED  ] \u001b[mDynamicFixture.DynamicTestFail\nDynamicFixture::TearDownTestSuite\n\u001b[0;32m[----------] \u001b[m1 test from DynamicFixtureAnotherName\nDynamicFixture::SetUpTestSuite\n\u001b[0;32m[ RUN      ] \u001b[mDynamicFixtureAnotherName.DynamicTestPass\nDynamicFixture()\nDynamicFixture::SetUp\nDynamicFixture::TearDown\n~DynamicFixture()\n\u001b[0;32m[       OK ] \u001b[mDynamicFixtureAnotherName.DynamicTestPass\nDynamicFixture::TearDownTestSuite\n\u001b[0;32m[----------] \u001b[m2 tests from BadDynamicFixture1\nDynamicFixture::SetUpTestSuite\n\u001b[0;32m[ RUN      ] \u001b[mBadDynamicFixture1.FixtureBase\nDynamicFixture()\nDynamicFixture::SetUp\nDynamicFixture::TearDown\n~DynamicFixture()\n\u001b[0;32m[       OK ] \u001b[mBadDynamicFixture1.FixtureBase\n\u001b[0;32m[ RUN      ] \u001b[mBadDynamicFixture1.TestBase\nDynamicFixture()\ngtest.cc:#: Failure\nFailed\nAll tests in the same test suite must use the same test fixture\nclass, so mixing TEST_F and TEST in the same test suite is\nillegal.  In test suite BadDynamicFixture1,\ntest FixtureBase is defined using TEST_F but\ntest TestBase is defined using TEST.  You probably\nwant to change the TEST to TEST_F or move it to another test\ncase.\nStack trace: (omitted)\n\n~DynamicFixture()\n\u001b[0;31m[  FAILED  ] \u001b[mBadDynamicFixture1.TestBase\nDynamicFixture::TearDownTestSuite\n\u001b[0;32m[----------] \u001b[m2 tests from BadDynamicFixture2\nDynamicFixture::SetUpTestSuite\n\u001b[0;32m[ RUN      ] \u001b[mBadDynamicFixture2.FixtureBase\nDynamicFixture()\nDynamicFixture::SetUp\nDynamicFixture::TearDown\n~DynamicFixture()\n\u001b[0;32m[       OK ] \u001b[mBadDynamicFixture2.FixtureBase\n\u001b[0;32m[ RUN      ] \u001b[mBadDynamicFixture2.Derived\nDynamicFixture()\ngtest.cc:#: Failure\nFailed\nAll tests in the same test suite must use the same test fixture\nclass.  However, in test suite BadDynamicFixture2,\nyou defined test FixtureBase and test Derived\nusing two different test fixture classes.  This can happen if\nthe two classes are from different namespaces or translation\nunits and have the same name.  You should probably rename one\nof the classes to put the tests into different test suites.\nStack trace: (omitted)\n\n~DynamicFixture()\n\u001b[0;31m[  FAILED  ] \u001b[mBadDynamicFixture2.Derived\nDynamicFixture::TearDownTestSuite\n\u001b[0;32m[----------] \u001b[m1 test from TestSuiteThatFailsToSetUp\ngoogletest-output-test_.cc:#: Failure\nValue of: false\n  Actual: false\nExpected: true\nStack trace: (omitted)\n\n\u001b[0;32m[ RUN      ] \u001b[mTestSuiteThatFailsToSetUp.ShouldNotRun\ngoogletest-output-test_.cc:#: Skipped\n\n\u001b[0;32m[  SKIPPED ] \u001b[mTestSuiteThatFailsToSetUp.ShouldNotRun\n\u001b[0;32m[----------] \u001b[m1 test from PrintingFailingParams/FailingParamTest\n\u001b[0;32m[ RUN      ] \u001b[mPrintingFailingParams/FailingParamTest.Fails/0\ngoogletest-output-test_.cc:#: Failure\nExpected equality of these values:\n  1\n  GetParam()\n    Which is: 2\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mPrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2\n\u001b[0;32m[----------] \u001b[m1 test from EmptyBasenameParamInst\n\u001b[0;32m[ RUN      ] \u001b[mEmptyBasenameParamInst.Passes/0\n\u001b[0;32m[       OK ] \u001b[mEmptyBasenameParamInst.Passes/0\n\u001b[0;32m[----------] \u001b[m2 tests from PrintingStrings/ParamTest\n\u001b[0;32m[ RUN      ] \u001b[mPrintingStrings/ParamTest.Success/a\n\u001b[0;32m[       OK ] \u001b[mPrintingStrings/ParamTest.Success/a\n\u001b[0;32m[ RUN      ] \u001b[mPrintingStrings/ParamTest.Failure/a\ngoogletest-output-test_.cc:#: Failure\nExpected equality of these values:\n  \"b\"\n  GetParam()\n    Which is: \"a\"\nExpected failure\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mPrintingStrings/ParamTest.Failure/a, where GetParam() = \"a\"\n\u001b[0;32m[----------] \u001b[m3 tests from GoogleTestVerification\n\u001b[0;32m[ RUN      ] \u001b[mGoogleTestVerification.UninstantiatedParameterizedTestSuite<NoTests>\ngoogletest-output-test_.cc:#: Failure\nParameterized test suite NoTests is instantiated via INSTANTIATE_TEST_SUITE_P, but no tests are defined via TEST_P . No test cases will run.\n\nIdeally, INSTANTIATE_TEST_SUITE_P should only ever be invoked from code that always depend on code that provides TEST_P. Failing to do so is often an indication of dead code, e.g. the last TEST_P was removed but the rest got left behind.\n\nTo suppress this error for this test suite, insert the following line (in a non-header) in the namespace it is defined in:\n\nGTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NoTests);\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mGoogleTestVerification.UninstantiatedParameterizedTestSuite<NoTests>\n\u001b[0;32m[ RUN      ] \u001b[mGoogleTestVerification.UninstantiatedParameterizedTestSuite<DetectNotInstantiatedTest>\ngoogletest-output-test_.cc:#: Failure\nParameterized test suite DetectNotInstantiatedTest is defined via TEST_P, but never instantiated. None of the test cases will run. Either no INSTANTIATE_TEST_SUITE_P is provided or the only ones provided expand to nothing.\n\nIdeally, TEST_P definitions should only ever be included as part of binaries that intend to use them. (As opposed to, for example, being placed in a library that may be linked in to get other utilities.)\n\nTo suppress this error for this test suite, insert the following line (in a non-header) in the namespace it is defined in:\n\nGTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(DetectNotInstantiatedTest);\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mGoogleTestVerification.UninstantiatedParameterizedTestSuite<DetectNotInstantiatedTest>\n\u001b[0;32m[ RUN      ] \u001b[mGoogleTestVerification.UninstantiatedTypeParameterizedTestSuite<DetectNotInstantiatedTypesTest>\ngoogletest-output-test_.cc:#: Failure\nType parameterized test suite DetectNotInstantiatedTypesTest is defined via REGISTER_TYPED_TEST_SUITE_P, but never instantiated via INSTANTIATE_TYPED_TEST_SUITE_P. None of the test cases will run.\n\nIdeally, TYPED_TEST_P definitions should only ever be included as part of binaries that intend to use them. (As opposed to, for example, being placed in a library that may be linked in to get other utilities.)\n\nTo suppress this error for this test suite, insert the following line (in a non-header) in the namespace it is defined in:\n\nGTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(DetectNotInstantiatedTypesTest);\nStack trace: (omitted)\n\n\u001b[0;31m[  FAILED  ] \u001b[mGoogleTestVerification.UninstantiatedTypeParameterizedTestSuite<DetectNotInstantiatedTypesTest>\n\u001b[0;32m[----------] \u001b[mGlobal test environment tear-down\nBarEnvironment::TearDown() called.\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected non-fatal failure.\nStack trace: (omitted)\n\nFooEnvironment::TearDown() called.\ngoogletest-output-test_.cc:#: Failure\nFailed\nExpected fatal failure.\nStack trace: (omitted)\n\n\u001b[0;32m[==========] \u001b[m89 tests from 42 test suites ran.\n\u001b[0;32m[  PASSED  ] \u001b[m31 tests.\n\u001b[0;32m[  SKIPPED ] \u001b[m1 test, listed below:\n\u001b[0;32m[  SKIPPED ] \u001b[mTestSuiteThatFailsToSetUp.ShouldNotRun\n\u001b[0;31m[  FAILED  ] \u001b[m57 tests, listed below:\n\u001b[0;31m[  FAILED  ] \u001b[mNonfatalFailureTest.EscapesStringOperands\n\u001b[0;31m[  FAILED  ] \u001b[mNonfatalFailureTest.DiffForLongStrings\n\u001b[0;31m[  FAILED  ] \u001b[mFatalFailureTest.FatalFailureInSubroutine\n\u001b[0;31m[  FAILED  ] \u001b[mFatalFailureTest.FatalFailureInNestedSubroutine\n\u001b[0;31m[  FAILED  ] \u001b[mFatalFailureTest.NonfatalFailureInSubroutine\n\u001b[0;31m[  FAILED  ] \u001b[mLoggingTest.InterleavingLoggingAndAssertions\n\u001b[0;31m[  FAILED  ] \u001b[mSCOPED_TRACETest.AcceptedValues\n\u001b[0;31m[  FAILED  ] \u001b[mSCOPED_TRACETest.ObeysScopes\n\u001b[0;31m[  FAILED  ] \u001b[mSCOPED_TRACETest.WorksInLoop\n\u001b[0;31m[  FAILED  ] \u001b[mSCOPED_TRACETest.WorksInSubroutine\n\u001b[0;31m[  FAILED  ] \u001b[mSCOPED_TRACETest.CanBeNested\n\u001b[0;31m[  FAILED  ] \u001b[mSCOPED_TRACETest.CanBeRepeated\n\u001b[0;31m[  FAILED  ] \u001b[mSCOPED_TRACETest.WorksConcurrently\n\u001b[0;31m[  FAILED  ] \u001b[mScopedTraceTest.WithExplicitFileAndLine\n\u001b[0;31m[  FAILED  ] \u001b[mNonFatalFailureInFixtureConstructorTest.FailureInConstructor\n\u001b[0;31m[  FAILED  ] \u001b[mFatalFailureInFixtureConstructorTest.FailureInConstructor\n\u001b[0;31m[  FAILED  ] \u001b[mNonFatalFailureInSetUpTest.FailureInSetUp\n\u001b[0;31m[  FAILED  ] \u001b[mFatalFailureInSetUpTest.FailureInSetUp\n\u001b[0;31m[  FAILED  ] \u001b[mAddFailureAtTest.MessageContainsSpecifiedFileAndLineNumber\n\u001b[0;31m[  FAILED  ] \u001b[mGtestFailAtTest.MessageContainsSpecifiedFileAndLineNumber\n\u001b[0;31m[  FAILED  ] \u001b[mMixedUpTestSuiteTest.ThisShouldFail\n\u001b[0;31m[  FAILED  ] \u001b[mMixedUpTestSuiteTest.ThisShouldFailToo\n\u001b[0;31m[  FAILED  ] \u001b[mMixedUpTestSuiteWithSameTestNameTest.TheSecondTestWithThisNameShouldFail\n\u001b[0;31m[  FAILED  ] \u001b[mTEST_F_before_TEST_in_same_test_case.DefinedUsingTESTAndShouldFail\n\u001b[0;31m[  FAILED  ] \u001b[mTEST_before_TEST_F_in_same_test_case.DefinedUsingTEST_FAndShouldFail\n\u001b[0;31m[  FAILED  ] \u001b[mExpectNonfatalFailureTest.FailsWhenThereIsNoNonfatalFailure\n\u001b[0;31m[  FAILED  ] \u001b[mExpectNonfatalFailureTest.FailsWhenThereAreTwoNonfatalFailures\n\u001b[0;31m[  FAILED  ] \u001b[mExpectNonfatalFailureTest.FailsWhenThereIsOneFatalFailure\n\u001b[0;31m[  FAILED  ] \u001b[mExpectNonfatalFailureTest.FailsWhenStatementReturns\n\u001b[0;31m[  FAILED  ] \u001b[mExpectNonfatalFailureTest.FailsWhenStatementThrows\n\u001b[0;31m[  FAILED  ] \u001b[mExpectFatalFailureTest.FailsWhenThereIsNoFatalFailure\n\u001b[0;31m[  FAILED  ] \u001b[mExpectFatalFailureTest.FailsWhenThereAreTwoFatalFailures\n\u001b[0;31m[  FAILED  ] \u001b[mExpectFatalFailureTest.FailsWhenThereIsOneNonfatalFailure\n\u001b[0;31m[  FAILED  ] \u001b[mExpectFatalFailureTest.FailsWhenStatementReturns\n\u001b[0;31m[  FAILED  ] \u001b[mExpectFatalFailureTest.FailsWhenStatementThrows\n\u001b[0;31m[  FAILED  ] \u001b[mTypedTest/0.Failure, where TypeParam = int\n\u001b[0;31m[  FAILED  ] \u001b[mTypedTestWithNames/char0.Failure, where TypeParam = char\n\u001b[0;31m[  FAILED  ] \u001b[mTypedTestWithNames/int1.Failure, where TypeParam = int\n\u001b[0;31m[  FAILED  ] \u001b[mUnsigned/TypedTestP/0.Failure, where TypeParam = unsigned char\n\u001b[0;31m[  FAILED  ] \u001b[mUnsigned/TypedTestP/1.Failure, where TypeParam = unsigned int\n\u001b[0;31m[  FAILED  ] \u001b[mUnsignedCustomName/TypedTestP/unsignedChar0.Failure, where TypeParam = unsigned char\n\u001b[0;31m[  FAILED  ] \u001b[mUnsignedCustomName/TypedTestP/unsignedInt1.Failure, where TypeParam = unsigned int\n\u001b[0;31m[  FAILED  ] \u001b[mExpectFailureTest.ExpectFatalFailure\n\u001b[0;31m[  FAILED  ] \u001b[mExpectFailureTest.ExpectNonFatalFailure\n\u001b[0;31m[  FAILED  ] \u001b[mExpectFailureTest.ExpectFatalFailureOnAllThreads\n\u001b[0;31m[  FAILED  ] \u001b[mExpectFailureTest.ExpectNonFatalFailureOnAllThreads\n\u001b[0;31m[  FAILED  ] \u001b[mExpectFailureWithThreadsTest.ExpectFatalFailure\n\u001b[0;31m[  FAILED  ] \u001b[mExpectFailureWithThreadsTest.ExpectNonFatalFailure\n\u001b[0;31m[  FAILED  ] \u001b[mScopedFakeTestPartResultReporterTest.InterceptOnlyCurrentThread\n\u001b[0;31m[  FAILED  ] \u001b[mDynamicFixture.DynamicTestFail\n\u001b[0;31m[  FAILED  ] \u001b[mBadDynamicFixture1.TestBase\n\u001b[0;31m[  FAILED  ] \u001b[mBadDynamicFixture2.Derived\n\u001b[0;31m[  FAILED  ] \u001b[mPrintingFailingParams/FailingParamTest.Fails/0, where GetParam() = 2\n\u001b[0;31m[  FAILED  ] \u001b[mPrintingStrings/ParamTest.Failure/a, where GetParam() = \"a\"\n\u001b[0;31m[  FAILED  ] \u001b[mGoogleTestVerification.UninstantiatedParameterizedTestSuite<NoTests>\n\u001b[0;31m[  FAILED  ] \u001b[mGoogleTestVerification.UninstantiatedParameterizedTestSuite<DetectNotInstantiatedTest>\n\u001b[0;31m[  FAILED  ] \u001b[mGoogleTestVerification.UninstantiatedTypeParameterizedTestSuite<DetectNotInstantiatedTypesTest>\n\n57 FAILED TESTS\n\u001b[0;31m[  FAILED  ] \u001b[mTestSuiteThatFailsToSetUp: SetUpTestSuite or TearDownTestSuite\n\n 1 FAILED TEST SUITE\n\u001b[0;33m  YOU HAVE 1 DISABLED TEST\n\n\u001b[mNote: Google Test filter = FatalFailureTest.*:LoggingTest.*\n[==========] Running 4 tests from 2 test suites.\n[----------] Global test environment set-up.\n[----------] 3 tests from FatalFailureTest\n[ RUN      ] FatalFailureTest.FatalFailureInSubroutine\n(expecting a failure that x should be 1)\ngoogletest-output-test_.cc:#: Failure\nExpected equality of these values:\n  1\n  x\n    Which is: 2\nStack trace: (omitted)\n\n[  FAILED  ] FatalFailureTest.FatalFailureInSubroutine (? ms)\n[ RUN      ] FatalFailureTest.FatalFailureInNestedSubroutine\n(expecting a failure that x should be 1)\ngoogletest-output-test_.cc:#: Failure\nExpected equality of these values:\n  1\n  x\n    Which is: 2\nStack trace: (omitted)\n\n[  FAILED  ] FatalFailureTest.FatalFailureInNestedSubroutine (? ms)\n[ RUN      ] FatalFailureTest.NonfatalFailureInSubroutine\n(expecting a failure on false)\ngoogletest-output-test_.cc:#: Failure\nValue of: false\n  Actual: false\nExpected: true\nStack trace: (omitted)\n\n[  FAILED  ] FatalFailureTest.NonfatalFailureInSubroutine (? ms)\n[----------] 3 tests from FatalFailureTest (? ms total)\n\n[----------] 1 test from LoggingTest\n[ RUN      ] LoggingTest.InterleavingLoggingAndAssertions\n(expecting 2 failures on (3) >= (a[i]))\ni == 0\ni == 1\ngoogletest-output-test_.cc:#: Failure\nExpected: (3) >= (a[i]), actual: 3 vs 9\nStack trace: (omitted)\n\ni == 2\ni == 3\ngoogletest-output-test_.cc:#: Failure\nExpected: (3) >= (a[i]), actual: 3 vs 6\nStack trace: (omitted)\n\n[  FAILED  ] LoggingTest.InterleavingLoggingAndAssertions (? ms)\n[----------] 1 test from LoggingTest (? ms total)\n\n[----------] Global test environment tear-down\n[==========] 4 tests from 2 test suites ran. (? ms total)\n[  PASSED  ] 0 tests.\n[  FAILED  ] 4 tests, listed below:\n[  FAILED  ] FatalFailureTest.FatalFailureInSubroutine\n[  FAILED  ] FatalFailureTest.FatalFailureInNestedSubroutine\n[  FAILED  ] FatalFailureTest.NonfatalFailureInSubroutine\n[  FAILED  ] LoggingTest.InterleavingLoggingAndAssertions\n\n 4 FAILED TESTS\nNote: Google Test filter = *DISABLED_*\n[==========] Running 1 test from 1 test suite.\n[----------] Global test environment set-up.\n[----------] 1 test from DisabledTestsWarningTest\n[ RUN      ] DisabledTestsWarningTest.DISABLED_AlsoRunDisabledTestsFlagSuppressesWarning\n[       OK ] DisabledTestsWarningTest.DISABLED_AlsoRunDisabledTestsFlagSuppressesWarning\n[----------] Global test environment tear-down\n[==========] 1 test from 1 test suite ran.\n[  PASSED  ] 1 test.\nNote: Google Test filter = PassingTest.*\nNote: This is test shard 2 of 2.\n[==========] Running 1 test from 1 test suite.\n[----------] Global test environment set-up.\n[----------] 1 test from PassingTest\n[ RUN      ] PassingTest.PassingTest2\n[       OK ] PassingTest.PassingTest2\n[----------] Global test environment tear-down\n[==========] 1 test from 1 test suite ran.\n[  PASSED  ] 1 test.\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-output-test.py",
    "content": "#!/usr/bin/env python\n#\n# Copyright 2008, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nr\"\"\"Tests the text output of Google C++ Testing and Mocking Framework.\n\nTo update the golden file:\ngoogletest_output_test.py --build_dir=BUILD/DIR --gengolden\nwhere BUILD/DIR contains the built googletest-output-test_ file.\ngoogletest_output_test.py --gengolden\ngoogletest_output_test.py\n\"\"\"\n\nimport difflib\nimport os\nimport re\nimport sys\nfrom googletest.test import gtest_test_utils\n\n\n# The flag for generating the golden file\nGENGOLDEN_FLAG = '--gengolden'\nCATCH_EXCEPTIONS_ENV_VAR_NAME = 'GTEST_CATCH_EXCEPTIONS'\n\n# The flag indicating stacktraces are not supported\nNO_STACKTRACE_SUPPORT_FLAG = '--no_stacktrace_support'\n\nIS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux'\nIS_WINDOWS = os.name == 'nt'\n\nGOLDEN_NAME = 'googletest-output-test-golden-lin.txt'\n\nPROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('googletest-output-test_')\n\n# At least one command we exercise must not have the\n# 'internal_skip_environment_and_ad_hoc_tests' argument.\nCOMMAND_LIST_TESTS = ({}, [PROGRAM_PATH, '--gtest_list_tests'])\nCOMMAND_WITH_COLOR = ({}, [PROGRAM_PATH, '--gtest_color=yes'])\nCOMMAND_WITH_TIME = ({}, [PROGRAM_PATH,\n                          '--gtest_print_time',\n                          'internal_skip_environment_and_ad_hoc_tests',\n                          '--gtest_filter=FatalFailureTest.*:LoggingTest.*'])\nCOMMAND_WITH_DISABLED = (\n    {}, [PROGRAM_PATH,\n         '--gtest_also_run_disabled_tests',\n         'internal_skip_environment_and_ad_hoc_tests',\n         '--gtest_filter=*DISABLED_*'])\nCOMMAND_WITH_SHARDING = (\n    {'GTEST_SHARD_INDEX': '1', 'GTEST_TOTAL_SHARDS': '2'},\n    [PROGRAM_PATH,\n     'internal_skip_environment_and_ad_hoc_tests',\n     '--gtest_filter=PassingTest.*'])\n\nGOLDEN_PATH = os.path.join(gtest_test_utils.GetSourceDir(), GOLDEN_NAME)\n\n\ndef ToUnixLineEnding(s):\n  \"\"\"Changes all Windows/Mac line endings in s to UNIX line endings.\"\"\"\n\n  return s.replace('\\r\\n', '\\n').replace('\\r', '\\n')\n\n\ndef RemoveLocations(test_output):\n  \"\"\"Removes all file location info from a Google Test program's output.\n\n  Args:\n       test_output:  the output of a Google Test program.\n\n  Returns:\n       output with all file location info (in the form of\n       'DIRECTORY/FILE_NAME:LINE_NUMBER: 'or\n       'DIRECTORY\\\\FILE_NAME(LINE_NUMBER): ') replaced by\n       'FILE_NAME:#: '.\n  \"\"\"\n\n  return re.sub(r'.*[/\\\\]((googletest-output-test_|gtest).cc)(\\:\\d+|\\(\\d+\\))\\: ',\n                r'\\1:#: ', test_output)\n\n\ndef RemoveStackTraceDetails(output):\n  \"\"\"Removes all stack traces from a Google Test program's output.\"\"\"\n\n  # *? means \"find the shortest string that matches\".\n  return re.sub(r'Stack trace:(.|\\n)*?\\n\\n',\n                'Stack trace: (omitted)\\n\\n', output)\n\n\ndef RemoveStackTraces(output):\n  \"\"\"Removes all traces of stack traces from a Google Test program's output.\"\"\"\n\n  # *? means \"find the shortest string that matches\".\n  return re.sub(r'Stack trace:(.|\\n)*?\\n\\n', '', output)\n\n\ndef RemoveTime(output):\n  \"\"\"Removes all time information from a Google Test program's output.\"\"\"\n\n  return re.sub(r'\\(\\d+ ms', '(? ms', output)\n\n\ndef RemoveTypeInfoDetails(test_output):\n  \"\"\"Removes compiler-specific type info from Google Test program's output.\n\n  Args:\n       test_output:  the output of a Google Test program.\n\n  Returns:\n       output with type information normalized to canonical form.\n  \"\"\"\n\n  # some compilers output the name of type 'unsigned int' as 'unsigned'\n  return re.sub(r'unsigned int', 'unsigned', test_output)\n\n\ndef NormalizeToCurrentPlatform(test_output):\n  \"\"\"Normalizes platform specific output details for easier comparison.\"\"\"\n\n  if IS_WINDOWS:\n    # Removes the color information that is not present on Windows.\n    test_output = re.sub('\\x1b\\\\[(0;3\\d)?m', '', test_output)\n    # Changes failure message headers into the Windows format.\n    test_output = re.sub(r': Failure\\n', r': error: ', test_output)\n    # Changes file(line_number) to file:line_number.\n    test_output = re.sub(r'((\\w|\\.)+)\\((\\d+)\\):', r'\\1:\\3:', test_output)\n\n  return test_output\n\n\ndef RemoveTestCounts(output):\n  \"\"\"Removes test counts from a Google Test program's output.\"\"\"\n\n  output = re.sub(r'\\d+ tests?, listed below',\n                  '? tests, listed below', output)\n  output = re.sub(r'\\d+ FAILED TESTS',\n                  '? FAILED TESTS', output)\n  output = re.sub(r'\\d+ tests? from \\d+ test cases?',\n                  '? tests from ? test cases', output)\n  output = re.sub(r'\\d+ tests? from ([a-zA-Z_])',\n                  r'? tests from \\1', output)\n  return re.sub(r'\\d+ tests?\\.', '? tests.', output)\n\n\ndef RemoveMatchingTests(test_output, pattern):\n  \"\"\"Removes output of specified tests from a Google Test program's output.\n\n  This function strips not only the beginning and the end of a test but also\n  all output in between.\n\n  Args:\n    test_output:       A string containing the test output.\n    pattern:           A regex string that matches names of test cases or\n                       tests to remove.\n\n  Returns:\n    Contents of test_output with tests whose names match pattern removed.\n  \"\"\"\n\n  test_output = re.sub(\n      r'.*\\[ RUN      \\] .*%s(.|\\n)*?\\[(  FAILED  |       OK )\\] .*%s.*\\n' % (\n          pattern, pattern),\n      '',\n      test_output)\n  return re.sub(r'.*%s.*\\n' % pattern, '', test_output)\n\n\ndef NormalizeOutput(output):\n  \"\"\"Normalizes output (the output of googletest-output-test_.exe).\"\"\"\n\n  output = ToUnixLineEnding(output)\n  output = RemoveLocations(output)\n  output = RemoveStackTraceDetails(output)\n  output = RemoveTime(output)\n  return output\n\n\ndef GetShellCommandOutput(env_cmd):\n  \"\"\"Runs a command in a sub-process, and returns its output in a string.\n\n  Args:\n    env_cmd: The shell command. A 2-tuple where element 0 is a dict of extra\n             environment variables to set, and element 1 is a string with\n             the command and any flags.\n\n  Returns:\n    A string with the command's combined standard and diagnostic output.\n  \"\"\"\n\n  # Spawns cmd in a sub-process, and gets its standard I/O file objects.\n  # Set and save the environment properly.\n  environ = os.environ.copy()\n  environ.update(env_cmd[0])\n  p = gtest_test_utils.Subprocess(env_cmd[1], env=environ)\n\n  return p.output\n\n\ndef GetCommandOutput(env_cmd):\n  \"\"\"Runs a command and returns its output with all file location\n  info stripped off.\n\n  Args:\n    env_cmd:  The shell command. A 2-tuple where element 0 is a dict of extra\n              environment variables to set, and element 1 is a string with\n              the command and any flags.\n  \"\"\"\n\n  # Disables exception pop-ups on Windows.\n  environ, cmdline = env_cmd\n  environ = dict(environ)  # Ensures we are modifying a copy.\n  environ[CATCH_EXCEPTIONS_ENV_VAR_NAME] = '1'\n  return NormalizeOutput(GetShellCommandOutput((environ, cmdline)))\n\n\ndef GetOutputOfAllCommands():\n  \"\"\"Returns concatenated output from several representative commands.\"\"\"\n\n  return (GetCommandOutput(COMMAND_WITH_COLOR) +\n          GetCommandOutput(COMMAND_WITH_TIME) +\n          GetCommandOutput(COMMAND_WITH_DISABLED) +\n          GetCommandOutput(COMMAND_WITH_SHARDING))\n\n\ntest_list = GetShellCommandOutput(COMMAND_LIST_TESTS)\nSUPPORTS_DEATH_TESTS = 'DeathTest' in test_list\nSUPPORTS_TYPED_TESTS = 'TypedTest' in test_list\nSUPPORTS_THREADS = 'ExpectFailureWithThreadsTest' in test_list\nSUPPORTS_STACK_TRACES = NO_STACKTRACE_SUPPORT_FLAG not in sys.argv\n\nCAN_GENERATE_GOLDEN_FILE = (SUPPORTS_DEATH_TESTS and\n                            SUPPORTS_TYPED_TESTS and\n                            SUPPORTS_THREADS and\n                            SUPPORTS_STACK_TRACES)\n\nclass GTestOutputTest(gtest_test_utils.TestCase):\n  def RemoveUnsupportedTests(self, test_output):\n    if not SUPPORTS_DEATH_TESTS:\n      test_output = RemoveMatchingTests(test_output, 'DeathTest')\n    if not SUPPORTS_TYPED_TESTS:\n      test_output = RemoveMatchingTests(test_output, 'TypedTest')\n      test_output = RemoveMatchingTests(test_output, 'TypedDeathTest')\n      test_output = RemoveMatchingTests(test_output, 'TypeParamDeathTest')\n    if not SUPPORTS_THREADS:\n      test_output = RemoveMatchingTests(test_output,\n                                        'ExpectFailureWithThreadsTest')\n      test_output = RemoveMatchingTests(test_output,\n                                        'ScopedFakeTestPartResultReporterTest')\n      test_output = RemoveMatchingTests(test_output,\n                                        'WorksConcurrently')\n    if not SUPPORTS_STACK_TRACES:\n      test_output = RemoveStackTraces(test_output)\n\n    return test_output\n\n  def testOutput(self):\n    output = GetOutputOfAllCommands()\n\n    golden_file = open(GOLDEN_PATH, 'rb')\n    # A mis-configured source control system can cause \\r appear in EOL\n    # sequences when we read the golden file irrespective of an operating\n    # system used. Therefore, we need to strip those \\r's from newlines\n    # unconditionally.\n    golden = ToUnixLineEnding(golden_file.read().decode())\n    golden_file.close()\n\n    # We want the test to pass regardless of certain features being\n    # supported or not.\n\n    # We still have to remove type name specifics in all cases.\n    normalized_actual = RemoveTypeInfoDetails(output)\n    normalized_golden = RemoveTypeInfoDetails(golden)\n\n    if CAN_GENERATE_GOLDEN_FILE:\n      self.assertEqual(normalized_golden, normalized_actual,\n                       '\\n'.join(difflib.unified_diff(\n                           normalized_golden.split('\\n'),\n                           normalized_actual.split('\\n'),\n                           'golden', 'actual')))\n    else:\n      normalized_actual = NormalizeToCurrentPlatform(\n          RemoveTestCounts(normalized_actual))\n      normalized_golden = NormalizeToCurrentPlatform(\n          RemoveTestCounts(self.RemoveUnsupportedTests(normalized_golden)))\n\n      # This code is very handy when debugging golden file differences:\n      if os.getenv('DEBUG_GTEST_OUTPUT_TEST'):\n        open(os.path.join(\n            gtest_test_utils.GetSourceDir(),\n            '_googletest-output-test_normalized_actual.txt'), 'wb').write(\n                normalized_actual)\n        open(os.path.join(\n            gtest_test_utils.GetSourceDir(),\n            '_googletest-output-test_normalized_golden.txt'), 'wb').write(\n                normalized_golden)\n\n      self.assertEqual(normalized_golden, normalized_actual)\n\n\nif __name__ == '__main__':\n  if NO_STACKTRACE_SUPPORT_FLAG in sys.argv:\n    # unittest.main() can't handle unknown flags\n    sys.argv.remove(NO_STACKTRACE_SUPPORT_FLAG)\n\n  if GENGOLDEN_FLAG in sys.argv:\n    if CAN_GENERATE_GOLDEN_FILE:\n      output = GetOutputOfAllCommands()\n      golden_file = open(GOLDEN_PATH, 'wb')\n      golden_file.write(output.encode())\n      golden_file.close()\n    else:\n      message = (\n          \"\"\"Unable to write a golden file when compiled in an environment\nthat does not support all the required features (death tests,\ntyped tests, stack traces, and multiple threads).\nPlease build this test and generate the golden file using Blaze on Linux.\"\"\")\n\n      sys.stderr.write(message)\n      sys.exit(1)\n  else:\n    gtest_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-output-test_.cc",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// The purpose of this file is to generate Google Test output under\n// various conditions.  The output will then be verified by\n// googletest-output-test.py to ensure that Google Test generates the\n// desired messages.  Therefore, most tests in this file are MEANT TO\n// FAIL.\n\n#include <stdlib.h>\n\n#include \"gtest/gtest-spi.h\"\n#include \"gtest/gtest.h\"\n#include \"src/gtest-internal-inl.h\"\n\n#if _MSC_VER\nGTEST_DISABLE_MSC_WARNINGS_PUSH_(4127 /* conditional expression is constant */)\n#endif  //  _MSC_VER\n\n#if GTEST_IS_THREADSAFE\nusing testing::ScopedFakeTestPartResultReporter;\nusing testing::TestPartResultArray;\n\nusing testing::internal::Notification;\nusing testing::internal::ThreadWithParam;\n#endif\n\nnamespace posix = ::testing::internal::posix;\n\n// Tests catching fatal failures.\n\n// A subroutine used by the following test.\nvoid TestEq1(int x) { ASSERT_EQ(1, x); }\n\n// This function calls a test subroutine, catches the fatal failure it\n// generates, and then returns early.\nvoid TryTestSubroutine() {\n  // Calls a subrountine that yields a fatal failure.\n  TestEq1(2);\n\n  // Catches the fatal failure and aborts the test.\n  //\n  // The testing::Test:: prefix is necessary when calling\n  // HasFatalFailure() outside of a TEST, TEST_F, or test fixture.\n  if (testing::Test::HasFatalFailure()) return;\n\n  // If we get here, something is wrong.\n  FAIL() << \"This should never be reached.\";\n}\n\nTEST(PassingTest, PassingTest1) {}\n\nTEST(PassingTest, PassingTest2) {}\n\n// Tests that parameters of failing parameterized tests are printed in the\n// failing test summary.\nclass FailingParamTest : public testing::TestWithParam<int> {};\n\nTEST_P(FailingParamTest, Fails) { EXPECT_EQ(1, GetParam()); }\n\n// This generates a test which will fail. Google Test is expected to print\n// its parameter when it outputs the list of all failed tests.\nINSTANTIATE_TEST_SUITE_P(PrintingFailingParams, FailingParamTest,\n                         testing::Values(2));\n\n// Tests that an empty value for the test suite basename yields just\n// the test name without any prior /\nclass EmptyBasenameParamInst : public testing::TestWithParam<int> {};\n\nTEST_P(EmptyBasenameParamInst, Passes) { EXPECT_EQ(1, GetParam()); }\n\nINSTANTIATE_TEST_SUITE_P(, EmptyBasenameParamInst, testing::Values(1));\n\nstatic const char kGoldenString[] = \"\\\"Line\\0 1\\\"\\nLine 2\";\n\nTEST(NonfatalFailureTest, EscapesStringOperands) {\n  std::string actual = \"actual \\\"string\\\"\";\n  EXPECT_EQ(kGoldenString, actual);\n\n  const char* golden = kGoldenString;\n  EXPECT_EQ(golden, actual);\n}\n\nTEST(NonfatalFailureTest, DiffForLongStrings) {\n  std::string golden_str(kGoldenString, sizeof(kGoldenString) - 1);\n  EXPECT_EQ(golden_str, \"Line 2\");\n}\n\n// Tests catching a fatal failure in a subroutine.\nTEST(FatalFailureTest, FatalFailureInSubroutine) {\n  printf(\"(expecting a failure that x should be 1)\\n\");\n\n  TryTestSubroutine();\n}\n\n// Tests catching a fatal failure in a nested subroutine.\nTEST(FatalFailureTest, FatalFailureInNestedSubroutine) {\n  printf(\"(expecting a failure that x should be 1)\\n\");\n\n  // Calls a subrountine that yields a fatal failure.\n  TryTestSubroutine();\n\n  // Catches the fatal failure and aborts the test.\n  //\n  // When calling HasFatalFailure() inside a TEST, TEST_F, or test\n  // fixture, the testing::Test:: prefix is not needed.\n  if (HasFatalFailure()) return;\n\n  // If we get here, something is wrong.\n  FAIL() << \"This should never be reached.\";\n}\n\n// Tests HasFatalFailure() after a failed EXPECT check.\nTEST(FatalFailureTest, NonfatalFailureInSubroutine) {\n  printf(\"(expecting a failure on false)\\n\");\n  EXPECT_TRUE(false);               // Generates a nonfatal failure\n  ASSERT_FALSE(HasFatalFailure());  // This should succeed.\n}\n\n// Tests interleaving user logging and Google Test assertions.\nTEST(LoggingTest, InterleavingLoggingAndAssertions) {\n  static const int a[4] = {3, 9, 2, 6};\n\n  printf(\"(expecting 2 failures on (3) >= (a[i]))\\n\");\n  for (int i = 0; i < static_cast<int>(sizeof(a) / sizeof(*a)); i++) {\n    printf(\"i == %d\\n\", i);\n    EXPECT_GE(3, a[i]);\n  }\n}\n\n// Tests the SCOPED_TRACE macro.\n\n// A helper function for testing SCOPED_TRACE.\nvoid SubWithoutTrace(int n) {\n  EXPECT_EQ(1, n);\n  ASSERT_EQ(2, n);\n}\n\n// Another helper function for testing SCOPED_TRACE.\nvoid SubWithTrace(int n) {\n  SCOPED_TRACE(testing::Message() << \"n = \" << n);\n\n  SubWithoutTrace(n);\n}\n\nTEST(SCOPED_TRACETest, AcceptedValues) {\n  SCOPED_TRACE(\"literal string\");\n  SCOPED_TRACE(std::string(\"std::string\"));\n  SCOPED_TRACE(1337);  // streamable type\n  const char* null_value = nullptr;\n  SCOPED_TRACE(null_value);\n\n  ADD_FAILURE() << \"Just checking that all these values work fine.\";\n}\n\n// Tests that SCOPED_TRACE() obeys lexical scopes.\nTEST(SCOPED_TRACETest, ObeysScopes) {\n  printf(\"(expected to fail)\\n\");\n\n  // There should be no trace before SCOPED_TRACE() is invoked.\n  ADD_FAILURE() << \"This failure is expected, and shouldn't have a trace.\";\n\n  {\n    SCOPED_TRACE(\"Expected trace\");\n    // After SCOPED_TRACE(), a failure in the current scope should contain\n    // the trace.\n    ADD_FAILURE() << \"This failure is expected, and should have a trace.\";\n  }\n\n  // Once the control leaves the scope of the SCOPED_TRACE(), there\n  // should be no trace again.\n  ADD_FAILURE() << \"This failure is expected, and shouldn't have a trace.\";\n}\n\n// Tests that SCOPED_TRACE works inside a loop.\nTEST(SCOPED_TRACETest, WorksInLoop) {\n  printf(\"(expected to fail)\\n\");\n\n  for (int i = 1; i <= 2; i++) {\n    SCOPED_TRACE(testing::Message() << \"i = \" << i);\n\n    SubWithoutTrace(i);\n  }\n}\n\n// Tests that SCOPED_TRACE works in a subroutine.\nTEST(SCOPED_TRACETest, WorksInSubroutine) {\n  printf(\"(expected to fail)\\n\");\n\n  SubWithTrace(1);\n  SubWithTrace(2);\n}\n\n// Tests that SCOPED_TRACE can be nested.\nTEST(SCOPED_TRACETest, CanBeNested) {\n  printf(\"(expected to fail)\\n\");\n\n  SCOPED_TRACE(\"\");  // A trace without a message.\n\n  SubWithTrace(2);\n}\n\n// Tests that multiple SCOPED_TRACEs can be used in the same scope.\nTEST(SCOPED_TRACETest, CanBeRepeated) {\n  printf(\"(expected to fail)\\n\");\n\n  SCOPED_TRACE(\"A\");\n  ADD_FAILURE()\n      << \"This failure is expected, and should contain trace point A.\";\n\n  SCOPED_TRACE(\"B\");\n  ADD_FAILURE()\n      << \"This failure is expected, and should contain trace point A and B.\";\n\n  {\n    SCOPED_TRACE(\"C\");\n    ADD_FAILURE() << \"This failure is expected, and should \"\n                  << \"contain trace point A, B, and C.\";\n  }\n\n  SCOPED_TRACE(\"D\");\n  ADD_FAILURE() << \"This failure is expected, and should \"\n                << \"contain trace point A, B, and D.\";\n}\n\n#if GTEST_IS_THREADSAFE\n// Tests that SCOPED_TRACE()s can be used concurrently from multiple\n// threads.  Namely, an assertion should be affected by\n// SCOPED_TRACE()s in its own thread only.\n\n// Here's the sequence of actions that happen in the test:\n//\n//   Thread A (main)                | Thread B (spawned)\n//   ===============================|================================\n//   spawns thread B                |\n//   -------------------------------+--------------------------------\n//   waits for n1                   | SCOPED_TRACE(\"Trace B\");\n//                                  | generates failure #1\n//                                  | notifies n1\n//   -------------------------------+--------------------------------\n//   SCOPED_TRACE(\"Trace A\");       | waits for n2\n//   generates failure #2           |\n//   notifies n2                    |\n//   -------------------------------|--------------------------------\n//   waits for n3                   | generates failure #3\n//                                  | trace B dies\n//                                  | generates failure #4\n//                                  | notifies n3\n//   -------------------------------|--------------------------------\n//   generates failure #5           | finishes\n//   trace A dies                   |\n//   generates failure #6           |\n//   -------------------------------|--------------------------------\n//   waits for thread B to finish   |\n\nstruct CheckPoints {\n  Notification n1;\n  Notification n2;\n  Notification n3;\n};\n\nstatic void ThreadWithScopedTrace(CheckPoints* check_points) {\n  {\n    SCOPED_TRACE(\"Trace B\");\n    ADD_FAILURE() << \"Expected failure #1 (in thread B, only trace B alive).\";\n    check_points->n1.Notify();\n    check_points->n2.WaitForNotification();\n\n    ADD_FAILURE()\n        << \"Expected failure #3 (in thread B, trace A & B both alive).\";\n  }  // Trace B dies here.\n  ADD_FAILURE() << \"Expected failure #4 (in thread B, only trace A alive).\";\n  check_points->n3.Notify();\n}\n\nTEST(SCOPED_TRACETest, WorksConcurrently) {\n  printf(\"(expecting 6 failures)\\n\");\n\n  CheckPoints check_points;\n  ThreadWithParam<CheckPoints*> thread(&ThreadWithScopedTrace, &check_points,\n                                       nullptr);\n  check_points.n1.WaitForNotification();\n\n  {\n    SCOPED_TRACE(\"Trace A\");\n    ADD_FAILURE()\n        << \"Expected failure #2 (in thread A, trace A & B both alive).\";\n    check_points.n2.Notify();\n    check_points.n3.WaitForNotification();\n\n    ADD_FAILURE() << \"Expected failure #5 (in thread A, only trace A alive).\";\n  }  // Trace A dies here.\n  ADD_FAILURE() << \"Expected failure #6 (in thread A, no trace alive).\";\n  thread.Join();\n}\n#endif  // GTEST_IS_THREADSAFE\n\n// Tests basic functionality of the ScopedTrace utility (most of its features\n// are already tested in SCOPED_TRACETest).\nTEST(ScopedTraceTest, WithExplicitFileAndLine) {\n  testing::ScopedTrace trace(\"explicit_file.cc\", 123, \"expected trace message\");\n  ADD_FAILURE() << \"Check that the trace is attached to a particular location.\";\n}\n\nTEST(DisabledTestsWarningTest,\n     DISABLED_AlsoRunDisabledTestsFlagSuppressesWarning) {\n  // This test body is intentionally empty.  Its sole purpose is for\n  // verifying that the --gtest_also_run_disabled_tests flag\n  // suppresses the \"YOU HAVE 12 DISABLED TESTS\" warning at the end of\n  // the test output.\n}\n\n// Tests using assertions outside of TEST and TEST_F.\n//\n// This function creates two failures intentionally.\nvoid AdHocTest() {\n  printf(\"The non-test part of the code is expected to have 2 failures.\\n\\n\");\n  EXPECT_TRUE(false);\n  EXPECT_EQ(2, 3);\n}\n\n// Runs all TESTs, all TEST_Fs, and the ad hoc test.\nint RunAllTests() {\n  AdHocTest();\n  return RUN_ALL_TESTS();\n}\n\n// Tests non-fatal failures in the fixture constructor.\nclass NonFatalFailureInFixtureConstructorTest : public testing::Test {\n protected:\n  NonFatalFailureInFixtureConstructorTest() {\n    printf(\"(expecting 5 failures)\\n\");\n    ADD_FAILURE() << \"Expected failure #1, in the test fixture c'tor.\";\n  }\n\n  ~NonFatalFailureInFixtureConstructorTest() override {\n    ADD_FAILURE() << \"Expected failure #5, in the test fixture d'tor.\";\n  }\n\n  void SetUp() override { ADD_FAILURE() << \"Expected failure #2, in SetUp().\"; }\n\n  void TearDown() override {\n    ADD_FAILURE() << \"Expected failure #4, in TearDown.\";\n  }\n};\n\nTEST_F(NonFatalFailureInFixtureConstructorTest, FailureInConstructor) {\n  ADD_FAILURE() << \"Expected failure #3, in the test body.\";\n}\n\n// Tests fatal failures in the fixture constructor.\nclass FatalFailureInFixtureConstructorTest : public testing::Test {\n protected:\n  FatalFailureInFixtureConstructorTest() {\n    printf(\"(expecting 2 failures)\\n\");\n    Init();\n  }\n\n  ~FatalFailureInFixtureConstructorTest() override {\n    ADD_FAILURE() << \"Expected failure #2, in the test fixture d'tor.\";\n  }\n\n  void SetUp() override {\n    ADD_FAILURE() << \"UNEXPECTED failure in SetUp().  \"\n                  << \"We should never get here, as the test fixture c'tor \"\n                  << \"had a fatal failure.\";\n  }\n\n  void TearDown() override {\n    ADD_FAILURE() << \"UNEXPECTED failure in TearDown().  \"\n                  << \"We should never get here, as the test fixture c'tor \"\n                  << \"had a fatal failure.\";\n  }\n\n private:\n  void Init() { FAIL() << \"Expected failure #1, in the test fixture c'tor.\"; }\n};\n\nTEST_F(FatalFailureInFixtureConstructorTest, FailureInConstructor) {\n  ADD_FAILURE() << \"UNEXPECTED failure in the test body.  \"\n                << \"We should never get here, as the test fixture c'tor \"\n                << \"had a fatal failure.\";\n}\n\n// Tests non-fatal failures in SetUp().\nclass NonFatalFailureInSetUpTest : public testing::Test {\n protected:\n  ~NonFatalFailureInSetUpTest() override { Deinit(); }\n\n  void SetUp() override {\n    printf(\"(expecting 4 failures)\\n\");\n    ADD_FAILURE() << \"Expected failure #1, in SetUp().\";\n  }\n\n  void TearDown() override { FAIL() << \"Expected failure #3, in TearDown().\"; }\n\n private:\n  void Deinit() { FAIL() << \"Expected failure #4, in the test fixture d'tor.\"; }\n};\n\nTEST_F(NonFatalFailureInSetUpTest, FailureInSetUp) {\n  FAIL() << \"Expected failure #2, in the test function.\";\n}\n\n// Tests fatal failures in SetUp().\nclass FatalFailureInSetUpTest : public testing::Test {\n protected:\n  ~FatalFailureInSetUpTest() override { Deinit(); }\n\n  void SetUp() override {\n    printf(\"(expecting 3 failures)\\n\");\n    FAIL() << \"Expected failure #1, in SetUp().\";\n  }\n\n  void TearDown() override { FAIL() << \"Expected failure #2, in TearDown().\"; }\n\n private:\n  void Deinit() { FAIL() << \"Expected failure #3, in the test fixture d'tor.\"; }\n};\n\nTEST_F(FatalFailureInSetUpTest, FailureInSetUp) {\n  FAIL() << \"UNEXPECTED failure in the test function.  \"\n         << \"We should never get here, as SetUp() failed.\";\n}\n\nTEST(AddFailureAtTest, MessageContainsSpecifiedFileAndLineNumber) {\n  ADD_FAILURE_AT(\"foo.cc\", 42) << \"Expected nonfatal failure in foo.cc\";\n}\n\nTEST(GtestFailAtTest, MessageContainsSpecifiedFileAndLineNumber) {\n  GTEST_FAIL_AT(\"foo.cc\", 42) << \"Expected fatal failure in foo.cc\";\n}\n\n// The MixedUpTestSuiteTest test case verifies that Google Test will fail a\n// test if it uses a different fixture class than what other tests in\n// the same test case use.  It deliberately contains two fixture\n// classes with the same name but defined in different namespaces.\n\n// The MixedUpTestSuiteWithSameTestNameTest test case verifies that\n// when the user defines two tests with the same test case name AND\n// same test name (but in different namespaces), the second test will\n// fail.\n\nnamespace foo {\n\nclass MixedUpTestSuiteTest : public testing::Test {};\n\nTEST_F(MixedUpTestSuiteTest, FirstTestFromNamespaceFoo) {}\nTEST_F(MixedUpTestSuiteTest, SecondTestFromNamespaceFoo) {}\n\nclass MixedUpTestSuiteWithSameTestNameTest : public testing::Test {};\n\nTEST_F(MixedUpTestSuiteWithSameTestNameTest,\n       TheSecondTestWithThisNameShouldFail) {}\n\n}  // namespace foo\n\nnamespace bar {\n\nclass MixedUpTestSuiteTest : public testing::Test {};\n\n// The following two tests are expected to fail.  We rely on the\n// golden file to check that Google Test generates the right error message.\nTEST_F(MixedUpTestSuiteTest, ThisShouldFail) {}\nTEST_F(MixedUpTestSuiteTest, ThisShouldFailToo) {}\n\nclass MixedUpTestSuiteWithSameTestNameTest : public testing::Test {};\n\n// Expected to fail.  We rely on the golden file to check that Google Test\n// generates the right error message.\nTEST_F(MixedUpTestSuiteWithSameTestNameTest,\n       TheSecondTestWithThisNameShouldFail) {}\n\n}  // namespace bar\n\n// The following two test cases verify that Google Test catches the user\n// error of mixing TEST and TEST_F in the same test case.  The first\n// test case checks the scenario where TEST_F appears before TEST, and\n// the second one checks where TEST appears before TEST_F.\n\nclass TEST_F_before_TEST_in_same_test_case : public testing::Test {};\n\nTEST_F(TEST_F_before_TEST_in_same_test_case, DefinedUsingTEST_F) {}\n\n// Expected to fail.  We rely on the golden file to check that Google Test\n// generates the right error message.\nTEST(TEST_F_before_TEST_in_same_test_case, DefinedUsingTESTAndShouldFail) {}\n\nclass TEST_before_TEST_F_in_same_test_case : public testing::Test {};\n\nTEST(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST) {}\n\n// Expected to fail.  We rely on the golden file to check that Google Test\n// generates the right error message.\nTEST_F(TEST_before_TEST_F_in_same_test_case, DefinedUsingTEST_FAndShouldFail) {}\n\n// Used for testing EXPECT_NONFATAL_FAILURE() and EXPECT_FATAL_FAILURE().\nint global_integer = 0;\n\n// Tests that EXPECT_NONFATAL_FAILURE() can reference global variables.\nTEST(ExpectNonfatalFailureTest, CanReferenceGlobalVariables) {\n  global_integer = 0;\n  EXPECT_NONFATAL_FAILURE(\n      { EXPECT_EQ(1, global_integer) << \"Expected non-fatal failure.\"; },\n      \"Expected non-fatal failure.\");\n}\n\n// Tests that EXPECT_NONFATAL_FAILURE() can reference local variables\n// (static or not).\nTEST(ExpectNonfatalFailureTest, CanReferenceLocalVariables) {\n  int m = 0;\n  static int n;\n  n = 1;\n  EXPECT_NONFATAL_FAILURE({ EXPECT_EQ(m, n) << \"Expected non-fatal failure.\"; },\n                          \"Expected non-fatal failure.\");\n}\n\n// Tests that EXPECT_NONFATAL_FAILURE() succeeds when there is exactly\n// one non-fatal failure and no fatal failure.\nTEST(ExpectNonfatalFailureTest, SucceedsWhenThereIsOneNonfatalFailure) {\n  EXPECT_NONFATAL_FAILURE({ ADD_FAILURE() << \"Expected non-fatal failure.\"; },\n                          \"Expected non-fatal failure.\");\n}\n\n// Tests that EXPECT_NONFATAL_FAILURE() fails when there is no\n// non-fatal failure.\nTEST(ExpectNonfatalFailureTest, FailsWhenThereIsNoNonfatalFailure) {\n  printf(\"(expecting a failure)\\n\");\n  EXPECT_NONFATAL_FAILURE({}, \"\");\n}\n\n// Tests that EXPECT_NONFATAL_FAILURE() fails when there are two\n// non-fatal failures.\nTEST(ExpectNonfatalFailureTest, FailsWhenThereAreTwoNonfatalFailures) {\n  printf(\"(expecting a failure)\\n\");\n  EXPECT_NONFATAL_FAILURE(\n      {\n        ADD_FAILURE() << \"Expected non-fatal failure 1.\";\n        ADD_FAILURE() << \"Expected non-fatal failure 2.\";\n      },\n      \"\");\n}\n\n// Tests that EXPECT_NONFATAL_FAILURE() fails when there is one fatal\n// failure.\nTEST(ExpectNonfatalFailureTest, FailsWhenThereIsOneFatalFailure) {\n  printf(\"(expecting a failure)\\n\");\n  EXPECT_NONFATAL_FAILURE({ FAIL() << \"Expected fatal failure.\"; }, \"\");\n}\n\n// Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being\n// tested returns.\nTEST(ExpectNonfatalFailureTest, FailsWhenStatementReturns) {\n  printf(\"(expecting a failure)\\n\");\n  EXPECT_NONFATAL_FAILURE({ return; }, \"\");\n}\n\n#if GTEST_HAS_EXCEPTIONS\n\n// Tests that EXPECT_NONFATAL_FAILURE() fails when the statement being\n// tested throws.\nTEST(ExpectNonfatalFailureTest, FailsWhenStatementThrows) {\n  printf(\"(expecting a failure)\\n\");\n  try {\n    EXPECT_NONFATAL_FAILURE({ throw 0; }, \"\");\n  } catch (int) {  // NOLINT\n  }\n}\n\n#endif  // GTEST_HAS_EXCEPTIONS\n\n// Tests that EXPECT_FATAL_FAILURE() can reference global variables.\nTEST(ExpectFatalFailureTest, CanReferenceGlobalVariables) {\n  global_integer = 0;\n  EXPECT_FATAL_FAILURE(\n      { ASSERT_EQ(1, global_integer) << \"Expected fatal failure.\"; },\n      \"Expected fatal failure.\");\n}\n\n// Tests that EXPECT_FATAL_FAILURE() can reference local static\n// variables.\nTEST(ExpectFatalFailureTest, CanReferenceLocalStaticVariables) {\n  static int n;\n  n = 1;\n  EXPECT_FATAL_FAILURE({ ASSERT_EQ(0, n) << \"Expected fatal failure.\"; },\n                       \"Expected fatal failure.\");\n}\n\n// Tests that EXPECT_FATAL_FAILURE() succeeds when there is exactly\n// one fatal failure and no non-fatal failure.\nTEST(ExpectFatalFailureTest, SucceedsWhenThereIsOneFatalFailure) {\n  EXPECT_FATAL_FAILURE({ FAIL() << \"Expected fatal failure.\"; },\n                       \"Expected fatal failure.\");\n}\n\n// Tests that EXPECT_FATAL_FAILURE() fails when there is no fatal\n// failure.\nTEST(ExpectFatalFailureTest, FailsWhenThereIsNoFatalFailure) {\n  printf(\"(expecting a failure)\\n\");\n  EXPECT_FATAL_FAILURE({}, \"\");\n}\n\n// A helper for generating a fatal failure.\nvoid FatalFailure() { FAIL() << \"Expected fatal failure.\"; }\n\n// Tests that EXPECT_FATAL_FAILURE() fails when there are two\n// fatal failures.\nTEST(ExpectFatalFailureTest, FailsWhenThereAreTwoFatalFailures) {\n  printf(\"(expecting a failure)\\n\");\n  EXPECT_FATAL_FAILURE(\n      {\n        FatalFailure();\n        FatalFailure();\n      },\n      \"\");\n}\n\n// Tests that EXPECT_FATAL_FAILURE() fails when there is one non-fatal\n// failure.\nTEST(ExpectFatalFailureTest, FailsWhenThereIsOneNonfatalFailure) {\n  printf(\"(expecting a failure)\\n\");\n  EXPECT_FATAL_FAILURE({ ADD_FAILURE() << \"Expected non-fatal failure.\"; }, \"\");\n}\n\n// Tests that EXPECT_FATAL_FAILURE() fails when the statement being\n// tested returns.\nTEST(ExpectFatalFailureTest, FailsWhenStatementReturns) {\n  printf(\"(expecting a failure)\\n\");\n  EXPECT_FATAL_FAILURE({ return; }, \"\");\n}\n\n#if GTEST_HAS_EXCEPTIONS\n\n// Tests that EXPECT_FATAL_FAILURE() fails when the statement being\n// tested throws.\nTEST(ExpectFatalFailureTest, FailsWhenStatementThrows) {\n  printf(\"(expecting a failure)\\n\");\n  try {\n    EXPECT_FATAL_FAILURE({ throw 0; }, \"\");\n  } catch (int) {  // NOLINT\n  }\n}\n\n#endif  // GTEST_HAS_EXCEPTIONS\n\n// This #ifdef block tests the output of value-parameterized tests.\n\nstd::string ParamNameFunc(const testing::TestParamInfo<std::string>& info) {\n  return info.param;\n}\n\nclass ParamTest : public testing::TestWithParam<std::string> {};\n\nTEST_P(ParamTest, Success) { EXPECT_EQ(\"a\", GetParam()); }\n\nTEST_P(ParamTest, Failure) { EXPECT_EQ(\"b\", GetParam()) << \"Expected failure\"; }\n\nINSTANTIATE_TEST_SUITE_P(PrintingStrings, ParamTest,\n                         testing::Values(std::string(\"a\")), ParamNameFunc);\n\n// The case where a suite has INSTANTIATE_TEST_SUITE_P but not TEST_P.\nusing NoTests = ParamTest;\nINSTANTIATE_TEST_SUITE_P(ThisIsOdd, NoTests, ::testing::Values(\"Hello\"));\n\n// fails under kErrorOnUninstantiatedParameterizedTest=true\nclass DetectNotInstantiatedTest : public testing::TestWithParam<int> {};\nTEST_P(DetectNotInstantiatedTest, Used) {}\n\n// This would make the test failure from the above go away.\n// INSTANTIATE_TEST_SUITE_P(Fix, DetectNotInstantiatedTest, testing::Values(1));\n\ntemplate <typename T>\nclass TypedTest : public testing::Test {};\n\nTYPED_TEST_SUITE(TypedTest, testing::Types<int>);\n\nTYPED_TEST(TypedTest, Success) { EXPECT_EQ(0, TypeParam()); }\n\nTYPED_TEST(TypedTest, Failure) {\n  EXPECT_EQ(1, TypeParam()) << \"Expected failure\";\n}\n\ntypedef testing::Types<char, int> TypesForTestWithNames;\n\ntemplate <typename T>\nclass TypedTestWithNames : public testing::Test {};\n\nclass TypedTestNames {\n public:\n  template <typename T>\n  static std::string GetName(int i) {\n    if (std::is_same<T, char>::value)\n      return std::string(\"char\") + ::testing::PrintToString(i);\n    if (std::is_same<T, int>::value)\n      return std::string(\"int\") + ::testing::PrintToString(i);\n  }\n};\n\nTYPED_TEST_SUITE(TypedTestWithNames, TypesForTestWithNames, TypedTestNames);\n\nTYPED_TEST(TypedTestWithNames, Success) {}\n\nTYPED_TEST(TypedTestWithNames, Failure) { FAIL(); }\n\ntemplate <typename T>\nclass TypedTestP : public testing::Test {};\n\nTYPED_TEST_SUITE_P(TypedTestP);\n\nTYPED_TEST_P(TypedTestP, Success) { EXPECT_EQ(0U, TypeParam()); }\n\nTYPED_TEST_P(TypedTestP, Failure) {\n  EXPECT_EQ(1U, TypeParam()) << \"Expected failure\";\n}\n\nREGISTER_TYPED_TEST_SUITE_P(TypedTestP, Success, Failure);\n\ntypedef testing::Types<unsigned char, unsigned int> UnsignedTypes;\nINSTANTIATE_TYPED_TEST_SUITE_P(Unsigned, TypedTestP, UnsignedTypes);\n\nclass TypedTestPNames {\n public:\n  template <typename T>\n  static std::string GetName(int i) {\n    if (std::is_same<T, unsigned char>::value) {\n      return std::string(\"unsignedChar\") + ::testing::PrintToString(i);\n    }\n    if (std::is_same<T, unsigned int>::value) {\n      return std::string(\"unsignedInt\") + ::testing::PrintToString(i);\n    }\n  }\n};\n\nINSTANTIATE_TYPED_TEST_SUITE_P(UnsignedCustomName, TypedTestP, UnsignedTypes,\n                               TypedTestPNames);\n\ntemplate <typename T>\nclass DetectNotInstantiatedTypesTest : public testing::Test {};\nTYPED_TEST_SUITE_P(DetectNotInstantiatedTypesTest);\nTYPED_TEST_P(DetectNotInstantiatedTypesTest, Used) {\n  TypeParam instantiate;\n  (void)instantiate;\n}\nREGISTER_TYPED_TEST_SUITE_P(DetectNotInstantiatedTypesTest, Used);\n\n// kErrorOnUninstantiatedTypeParameterizedTest=true would make the above fail.\n// Adding the following would make that test failure go away.\n//\n// typedef ::testing::Types<char, int, unsigned int> MyTypes;\n// INSTANTIATE_TYPED_TEST_SUITE_P(All, DetectNotInstantiatedTypesTest, MyTypes);\n\n#if GTEST_HAS_DEATH_TEST\n\n// We rely on the golden file to verify that tests whose test case\n// name ends with DeathTest are run first.\n\nTEST(ADeathTest, ShouldRunFirst) {}\n\n// We rely on the golden file to verify that typed tests whose test\n// case name ends with DeathTest are run first.\n\ntemplate <typename T>\nclass ATypedDeathTest : public testing::Test {};\n\ntypedef testing::Types<int, double> NumericTypes;\nTYPED_TEST_SUITE(ATypedDeathTest, NumericTypes);\n\nTYPED_TEST(ATypedDeathTest, ShouldRunFirst) {}\n\n// We rely on the golden file to verify that type-parameterized tests\n// whose test case name ends with DeathTest are run first.\n\ntemplate <typename T>\nclass ATypeParamDeathTest : public testing::Test {};\n\nTYPED_TEST_SUITE_P(ATypeParamDeathTest);\n\nTYPED_TEST_P(ATypeParamDeathTest, ShouldRunFirst) {}\n\nREGISTER_TYPED_TEST_SUITE_P(ATypeParamDeathTest, ShouldRunFirst);\n\nINSTANTIATE_TYPED_TEST_SUITE_P(My, ATypeParamDeathTest, NumericTypes);\n\n#endif  // GTEST_HAS_DEATH_TEST\n\n// Tests various failure conditions of\n// EXPECT_{,NON}FATAL_FAILURE{,_ON_ALL_THREADS}.\nclass ExpectFailureTest : public testing::Test {\n public:  // Must be public and not protected due to a bug in g++ 3.4.2.\n  enum FailureMode { FATAL_FAILURE, NONFATAL_FAILURE };\n  static void AddFailure(FailureMode failure) {\n    if (failure == FATAL_FAILURE) {\n      FAIL() << \"Expected fatal failure.\";\n    } else {\n      ADD_FAILURE() << \"Expected non-fatal failure.\";\n    }\n  }\n};\n\nTEST_F(ExpectFailureTest, ExpectFatalFailure) {\n  // Expected fatal failure, but succeeds.\n  printf(\"(expecting 1 failure)\\n\");\n  EXPECT_FATAL_FAILURE(SUCCEED(), \"Expected fatal failure.\");\n  // Expected fatal failure, but got a non-fatal failure.\n  printf(\"(expecting 1 failure)\\n\");\n  EXPECT_FATAL_FAILURE(AddFailure(NONFATAL_FAILURE),\n                       \"Expected non-fatal \"\n                       \"failure.\");\n  // Wrong message.\n  printf(\"(expecting 1 failure)\\n\");\n  EXPECT_FATAL_FAILURE(AddFailure(FATAL_FAILURE),\n                       \"Some other fatal failure \"\n                       \"expected.\");\n}\n\nTEST_F(ExpectFailureTest, ExpectNonFatalFailure) {\n  // Expected non-fatal failure, but succeeds.\n  printf(\"(expecting 1 failure)\\n\");\n  EXPECT_NONFATAL_FAILURE(SUCCEED(), \"Expected non-fatal failure.\");\n  // Expected non-fatal failure, but got a fatal failure.\n  printf(\"(expecting 1 failure)\\n\");\n  EXPECT_NONFATAL_FAILURE(AddFailure(FATAL_FAILURE), \"Expected fatal failure.\");\n  // Wrong message.\n  printf(\"(expecting 1 failure)\\n\");\n  EXPECT_NONFATAL_FAILURE(AddFailure(NONFATAL_FAILURE),\n                          \"Some other non-fatal \"\n                          \"failure.\");\n}\n\n#if GTEST_IS_THREADSAFE\n\nclass ExpectFailureWithThreadsTest : public ExpectFailureTest {\n protected:\n  static void AddFailureInOtherThread(FailureMode failure) {\n    ThreadWithParam<FailureMode> thread(&AddFailure, failure, nullptr);\n    thread.Join();\n  }\n};\n\nTEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailure) {\n  // We only intercept the current thread.\n  printf(\"(expecting 2 failures)\\n\");\n  EXPECT_FATAL_FAILURE(AddFailureInOtherThread(FATAL_FAILURE),\n                       \"Expected fatal failure.\");\n}\n\nTEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailure) {\n  // We only intercept the current thread.\n  printf(\"(expecting 2 failures)\\n\");\n  EXPECT_NONFATAL_FAILURE(AddFailureInOtherThread(NONFATAL_FAILURE),\n                          \"Expected non-fatal failure.\");\n}\n\ntypedef ExpectFailureWithThreadsTest ScopedFakeTestPartResultReporterTest;\n\n// Tests that the ScopedFakeTestPartResultReporter only catches failures from\n// the current thread if it is instantiated with INTERCEPT_ONLY_CURRENT_THREAD.\nTEST_F(ScopedFakeTestPartResultReporterTest, InterceptOnlyCurrentThread) {\n  printf(\"(expecting 2 failures)\\n\");\n  TestPartResultArray results;\n  {\n    ScopedFakeTestPartResultReporter reporter(\n        ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,\n        &results);\n    AddFailureInOtherThread(FATAL_FAILURE);\n    AddFailureInOtherThread(NONFATAL_FAILURE);\n  }\n  // The two failures should not have been intercepted.\n  EXPECT_EQ(0, results.size()) << \"This shouldn't fail.\";\n}\n\n#endif  // GTEST_IS_THREADSAFE\n\nTEST_F(ExpectFailureTest, ExpectFatalFailureOnAllThreads) {\n  // Expected fatal failure, but succeeds.\n  printf(\"(expecting 1 failure)\\n\");\n  EXPECT_FATAL_FAILURE_ON_ALL_THREADS(SUCCEED(), \"Expected fatal failure.\");\n  // Expected fatal failure, but got a non-fatal failure.\n  printf(\"(expecting 1 failure)\\n\");\n  EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE),\n                                      \"Expected non-fatal failure.\");\n  // Wrong message.\n  printf(\"(expecting 1 failure)\\n\");\n  EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE),\n                                      \"Some other fatal failure expected.\");\n}\n\nTEST_F(ExpectFailureTest, ExpectNonFatalFailureOnAllThreads) {\n  // Expected non-fatal failure, but succeeds.\n  printf(\"(expecting 1 failure)\\n\");\n  EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(SUCCEED(),\n                                         \"Expected non-fatal \"\n                                         \"failure.\");\n  // Expected non-fatal failure, but got a fatal failure.\n  printf(\"(expecting 1 failure)\\n\");\n  EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(FATAL_FAILURE),\n                                         \"Expected fatal failure.\");\n  // Wrong message.\n  printf(\"(expecting 1 failure)\\n\");\n  EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddFailure(NONFATAL_FAILURE),\n                                         \"Some other non-fatal failure.\");\n}\n\nclass DynamicFixture : public testing::Test {\n protected:\n  DynamicFixture() { printf(\"DynamicFixture()\\n\"); }\n  ~DynamicFixture() override { printf(\"~DynamicFixture()\\n\"); }\n  void SetUp() override { printf(\"DynamicFixture::SetUp\\n\"); }\n  void TearDown() override { printf(\"DynamicFixture::TearDown\\n\"); }\n\n  static void SetUpTestSuite() { printf(\"DynamicFixture::SetUpTestSuite\\n\"); }\n  static void TearDownTestSuite() {\n    printf(\"DynamicFixture::TearDownTestSuite\\n\");\n  }\n};\n\ntemplate <bool Pass>\nclass DynamicTest : public DynamicFixture {\n public:\n  void TestBody() override { EXPECT_TRUE(Pass); }\n};\n\nauto dynamic_test = (\n    // Register two tests with the same fixture correctly.\n    testing::RegisterTest(\n        \"DynamicFixture\", \"DynamicTestPass\", nullptr, nullptr, __FILE__,\n        __LINE__, []() -> DynamicFixture* { return new DynamicTest<true>; }),\n    testing::RegisterTest(\n        \"DynamicFixture\", \"DynamicTestFail\", nullptr, nullptr, __FILE__,\n        __LINE__, []() -> DynamicFixture* { return new DynamicTest<false>; }),\n\n    // Register the same fixture with another name. That's fine.\n    testing::RegisterTest(\n        \"DynamicFixtureAnotherName\", \"DynamicTestPass\", nullptr, nullptr,\n        __FILE__, __LINE__,\n        []() -> DynamicFixture* { return new DynamicTest<true>; }),\n\n    // Register two tests with the same fixture incorrectly.\n    testing::RegisterTest(\n        \"BadDynamicFixture1\", \"FixtureBase\", nullptr, nullptr, __FILE__,\n        __LINE__, []() -> DynamicFixture* { return new DynamicTest<true>; }),\n    testing::RegisterTest(\n        \"BadDynamicFixture1\", \"TestBase\", nullptr, nullptr, __FILE__, __LINE__,\n        []() -> testing::Test* { return new DynamicTest<true>; }),\n\n    // Register two tests with the same fixture incorrectly by omitting the\n    // return type.\n    testing::RegisterTest(\n        \"BadDynamicFixture2\", \"FixtureBase\", nullptr, nullptr, __FILE__,\n        __LINE__, []() -> DynamicFixture* { return new DynamicTest<true>; }),\n    testing::RegisterTest(\"BadDynamicFixture2\", \"Derived\", nullptr, nullptr,\n                          __FILE__, __LINE__,\n                          []() { return new DynamicTest<true>; }));\n\n// Two test environments for testing testing::AddGlobalTestEnvironment().\n\nclass FooEnvironment : public testing::Environment {\n public:\n  void SetUp() override { printf(\"%s\", \"FooEnvironment::SetUp() called.\\n\"); }\n\n  void TearDown() override {\n    printf(\"%s\", \"FooEnvironment::TearDown() called.\\n\");\n    FAIL() << \"Expected fatal failure.\";\n  }\n};\n\nclass BarEnvironment : public testing::Environment {\n public:\n  void SetUp() override { printf(\"%s\", \"BarEnvironment::SetUp() called.\\n\"); }\n\n  void TearDown() override {\n    printf(\"%s\", \"BarEnvironment::TearDown() called.\\n\");\n    ADD_FAILURE() << \"Expected non-fatal failure.\";\n  }\n};\n\nclass TestSuiteThatFailsToSetUp : public testing::Test {\n public:\n  static void SetUpTestSuite() { EXPECT_TRUE(false); }\n};\nTEST_F(TestSuiteThatFailsToSetUp, ShouldNotRun) { std::abort(); }\n\n// The main function.\n//\n// The idea is to use Google Test to run all the tests we have defined (some\n// of them are intended to fail), and then compare the test results\n// with the \"golden\" file.\nint main(int argc, char** argv) {\n  GTEST_FLAG_SET(print_time, false);\n\n  // We just run the tests, knowing some of them are intended to fail.\n  // We will use a separate Python script to compare the output of\n  // this program with the golden file.\n\n  // It's hard to test InitGoogleTest() directly, as it has many\n  // global side effects.  The following line serves as a test\n  // for it.\n  testing::InitGoogleTest(&argc, argv);\n  bool internal_skip_environment_and_ad_hoc_tests =\n      std::count(argv, argv + argc,\n                 std::string(\"internal_skip_environment_and_ad_hoc_tests\")) > 0;\n\n#if GTEST_HAS_DEATH_TEST\n  if (GTEST_FLAG_GET(internal_run_death_test) != \"\") {\n    // Skip the usual output capturing if we're running as the child\n    // process of an threadsafe-style death test.\n#if GTEST_OS_WINDOWS\n    posix::FReopen(\"nul:\", \"w\", stdout);\n#else\n    posix::FReopen(\"/dev/null\", \"w\", stdout);\n#endif  // GTEST_OS_WINDOWS\n    return RUN_ALL_TESTS();\n  }\n#endif  // GTEST_HAS_DEATH_TEST\n\n  if (internal_skip_environment_and_ad_hoc_tests) return RUN_ALL_TESTS();\n\n  // Registers two global test environments.\n  // The golden file verifies that they are set up in the order they\n  // are registered, and torn down in the reverse order.\n  testing::AddGlobalTestEnvironment(new FooEnvironment);\n  testing::AddGlobalTestEnvironment(new BarEnvironment);\n#if _MSC_VER\n  GTEST_DISABLE_MSC_WARNINGS_POP_()  //  4127\n#endif                               //  _MSC_VER\n  return RunAllTests();\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-param-test-invalid-name1-test.py",
    "content": "#!/usr/bin/env python\n#\n# Copyright 2015 Google Inc. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Verifies that Google Test warns the user when not initialized properly.\"\"\"\n\nfrom googletest.test import gtest_test_utils\n\nbinary_name = 'googletest-param-test-invalid-name1-test_'\nCOMMAND = gtest_test_utils.GetTestExecutablePath(binary_name)\n\n\ndef Assert(condition):\n  if not condition:\n    raise AssertionError\n\n\ndef TestExitCodeAndOutput(command):\n  \"\"\"Runs the given command and verifies its exit code and output.\"\"\"\n\n  err = ('Parameterized test name \\'\"InvalidWithQuotes\"\\' is invalid')\n\n  p = gtest_test_utils.Subprocess(command)\n  Assert(p.terminated_by_signal)\n\n  # Verify the output message contains appropriate output\n  Assert(err in p.output)\n\n\nclass GTestParamTestInvalidName1Test(gtest_test_utils.TestCase):\n\n  def testExitCodeAndOutput(self):\n    TestExitCodeAndOutput(COMMAND)\n\n\nif __name__ == '__main__':\n  gtest_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-param-test-invalid-name1-test_.cc",
    "content": "// Copyright 2015, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"gtest/gtest.h\"\n\nnamespace {\nclass DummyTest : public ::testing::TestWithParam<const char *> {};\n\nTEST_P(DummyTest, Dummy) {}\n\nINSTANTIATE_TEST_SUITE_P(InvalidTestName, DummyTest,\n                         ::testing::Values(\"InvalidWithQuotes\"),\n                         ::testing::PrintToStringParamName());\n\n}  // namespace\n\nint main(int argc, char *argv[]) {\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-param-test-invalid-name2-test.py",
    "content": "#!/usr/bin/env python\n#\n# Copyright 2015 Google Inc. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Verifies that Google Test warns the user when not initialized properly.\"\"\"\n\nfrom googletest.test import gtest_test_utils\n\nbinary_name = 'googletest-param-test-invalid-name2-test_'\nCOMMAND = gtest_test_utils.GetTestExecutablePath(binary_name)\n\n\ndef Assert(condition):\n  if not condition:\n    raise AssertionError\n\n\ndef TestExitCodeAndOutput(command):\n  \"\"\"Runs the given command and verifies its exit code and output.\"\"\"\n\n  err = ('Duplicate parameterized test name \\'a\\'')\n\n  p = gtest_test_utils.Subprocess(command)\n  Assert(p.terminated_by_signal)\n\n  # Check for appropriate output\n  Assert(err in p.output)\n\n\nclass GTestParamTestInvalidName2Test(gtest_test_utils.TestCase):\n\n  def testExitCodeAndOutput(self):\n    TestExitCodeAndOutput(COMMAND)\n\nif __name__ == '__main__':\n  gtest_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-param-test-invalid-name2-test_.cc",
    "content": "// Copyright 2015, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"gtest/gtest.h\"\n\nnamespace {\nclass DummyTest : public ::testing::TestWithParam<const char *> {};\n\nstd::string StringParamTestSuffix(\n    const testing::TestParamInfo<const char *> &info) {\n  return std::string(info.param);\n}\n\nTEST_P(DummyTest, Dummy) {}\n\nINSTANTIATE_TEST_SUITE_P(DuplicateTestNames, DummyTest,\n                         ::testing::Values(\"a\", \"b\", \"a\", \"c\"),\n                         StringParamTestSuffix);\n}  // namespace\n\nint main(int argc, char *argv[]) {\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-param-test-test.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// Tests for Google Test itself. This file verifies that the parameter\n// generators objects produce correct parameter sequences and that\n// Google Test runtime instantiates correct tests from those sequences.\n\n#include \"test/googletest-param-test-test.h\"\n\n#include <algorithm>\n#include <iostream>\n#include <list>\n#include <set>\n#include <sstream>\n#include <string>\n#include <vector>\n\n#include \"gtest/gtest.h\"\n#include \"src/gtest-internal-inl.h\"  // for UnitTestOptions\n\nusing ::std::sort;\nusing ::std::vector;\n\nusing ::testing::AddGlobalTestEnvironment;\nusing ::testing::Bool;\nusing ::testing::Combine;\nusing ::testing::Message;\nusing ::testing::Range;\nusing ::testing::TestWithParam;\nusing ::testing::Values;\nusing ::testing::ValuesIn;\n\nusing ::testing::internal::ParamGenerator;\nusing ::testing::internal::UnitTestOptions;\n\n// Prints a value to a string.\n//\n// FIXME: remove PrintValue() when we move matchers and\n// EXPECT_THAT() from Google Mock to Google Test.  At that time, we\n// can write EXPECT_THAT(x, Eq(y)) to compare two tuples x and y, as\n// EXPECT_THAT() and the matchers know how to print tuples.\ntemplate <typename T>\n::std::string PrintValue(const T& value) {\n  return testing::PrintToString(value);\n}\n\n// Verifies that a sequence generated by the generator and accessed\n// via the iterator object matches the expected one using Google Test\n// assertions.\ntemplate <typename T, size_t N>\nvoid VerifyGenerator(const ParamGenerator<T>& generator,\n                     const T (&expected_values)[N]) {\n  typename ParamGenerator<T>::iterator it = generator.begin();\n  for (size_t i = 0; i < N; ++i) {\n    ASSERT_FALSE(it == generator.end())\n        << \"At element \" << i << \" when accessing via an iterator \"\n        << \"created with the copy constructor.\\n\";\n    // We cannot use EXPECT_EQ() here as the values may be tuples,\n    // which don't support <<.\n    EXPECT_TRUE(expected_values[i] == *it)\n        << \"where i is \" << i << \", expected_values[i] is \"\n        << PrintValue(expected_values[i]) << \", *it is \" << PrintValue(*it)\n        << \", and 'it' is an iterator created with the copy constructor.\\n\";\n    ++it;\n  }\n  EXPECT_TRUE(it == generator.end())\n      << \"At the presumed end of sequence when accessing via an iterator \"\n      << \"created with the copy constructor.\\n\";\n\n  // Test the iterator assignment. The following lines verify that\n  // the sequence accessed via an iterator initialized via the\n  // assignment operator (as opposed to a copy constructor) matches\n  // just the same.\n  it = generator.begin();\n  for (size_t i = 0; i < N; ++i) {\n    ASSERT_FALSE(it == generator.end())\n        << \"At element \" << i << \" when accessing via an iterator \"\n        << \"created with the assignment operator.\\n\";\n    EXPECT_TRUE(expected_values[i] == *it)\n        << \"where i is \" << i << \", expected_values[i] is \"\n        << PrintValue(expected_values[i]) << \", *it is \" << PrintValue(*it)\n        << \", and 'it' is an iterator created with the copy constructor.\\n\";\n    ++it;\n  }\n  EXPECT_TRUE(it == generator.end())\n      << \"At the presumed end of sequence when accessing via an iterator \"\n      << \"created with the assignment operator.\\n\";\n}\n\ntemplate <typename T>\nvoid VerifyGeneratorIsEmpty(const ParamGenerator<T>& generator) {\n  typename ParamGenerator<T>::iterator it = generator.begin();\n  EXPECT_TRUE(it == generator.end());\n\n  it = generator.begin();\n  EXPECT_TRUE(it == generator.end());\n}\n\n// Generator tests. They test that each of the provided generator functions\n// generates an expected sequence of values. The general test pattern\n// instantiates a generator using one of the generator functions,\n// checks the sequence produced by the generator using its iterator API,\n// and then resets the iterator back to the beginning of the sequence\n// and checks the sequence again.\n\n// Tests that iterators produced by generator functions conform to the\n// ForwardIterator concept.\nTEST(IteratorTest, ParamIteratorConformsToForwardIteratorConcept) {\n  const ParamGenerator<int> gen = Range(0, 10);\n  ParamGenerator<int>::iterator it = gen.begin();\n\n  // Verifies that iterator initialization works as expected.\n  ParamGenerator<int>::iterator it2 = it;\n  EXPECT_TRUE(*it == *it2) << \"Initialized iterators must point to the \"\n                           << \"element same as its source points to\";\n\n  // Verifies that iterator assignment works as expected.\n  ++it;\n  EXPECT_FALSE(*it == *it2);\n  it2 = it;\n  EXPECT_TRUE(*it == *it2) << \"Assigned iterators must point to the \"\n                           << \"element same as its source points to\";\n\n  // Verifies that prefix operator++() returns *this.\n  EXPECT_EQ(&it, &(++it)) << \"Result of the prefix operator++ must be \"\n                          << \"refer to the original object\";\n\n  // Verifies that the result of the postfix operator++ points to the value\n  // pointed to by the original iterator.\n  int original_value = *it;  // Have to compute it outside of macro call to be\n                             // unaffected by the parameter evaluation order.\n  EXPECT_EQ(original_value, *(it++));\n\n  // Verifies that prefix and postfix operator++() advance an iterator\n  // all the same.\n  it2 = it;\n  ++it;\n  ++it2;\n  EXPECT_TRUE(*it == *it2);\n}\n\n// Tests that Range() generates the expected sequence.\nTEST(RangeTest, IntRangeWithDefaultStep) {\n  const ParamGenerator<int> gen = Range(0, 3);\n  const int expected_values[] = {0, 1, 2};\n  VerifyGenerator(gen, expected_values);\n}\n\n// Edge case. Tests that Range() generates the single element sequence\n// as expected when provided with range limits that are equal.\nTEST(RangeTest, IntRangeSingleValue) {\n  const ParamGenerator<int> gen = Range(0, 1);\n  const int expected_values[] = {0};\n  VerifyGenerator(gen, expected_values);\n}\n\n// Edge case. Tests that Range() with generates empty sequence when\n// supplied with an empty range.\nTEST(RangeTest, IntRangeEmpty) {\n  const ParamGenerator<int> gen = Range(0, 0);\n  VerifyGeneratorIsEmpty(gen);\n}\n\n// Tests that Range() with custom step (greater then one) generates\n// the expected sequence.\nTEST(RangeTest, IntRangeWithCustomStep) {\n  const ParamGenerator<int> gen = Range(0, 9, 3);\n  const int expected_values[] = {0, 3, 6};\n  VerifyGenerator(gen, expected_values);\n}\n\n// Tests that Range() with custom step (greater then one) generates\n// the expected sequence when the last element does not fall on the\n// upper range limit. Sequences generated by Range() must not have\n// elements beyond the range limits.\nTEST(RangeTest, IntRangeWithCustomStepOverUpperBound) {\n  const ParamGenerator<int> gen = Range(0, 4, 3);\n  const int expected_values[] = {0, 3};\n  VerifyGenerator(gen, expected_values);\n}\n\n// Verifies that Range works with user-defined types that define\n// copy constructor, operator=(), operator+(), and operator<().\nclass DogAdder {\n public:\n  explicit DogAdder(const char* a_value) : value_(a_value) {}\n  DogAdder(const DogAdder& other) : value_(other.value_.c_str()) {}\n\n  DogAdder operator=(const DogAdder& other) {\n    if (this != &other) value_ = other.value_;\n    return *this;\n  }\n  DogAdder operator+(const DogAdder& other) const {\n    Message msg;\n    msg << value_.c_str() << other.value_.c_str();\n    return DogAdder(msg.GetString().c_str());\n  }\n  bool operator<(const DogAdder& other) const { return value_ < other.value_; }\n  const std::string& value() const { return value_; }\n\n private:\n  std::string value_;\n};\n\nTEST(RangeTest, WorksWithACustomType) {\n  const ParamGenerator<DogAdder> gen =\n      Range(DogAdder(\"cat\"), DogAdder(\"catdogdog\"), DogAdder(\"dog\"));\n  ParamGenerator<DogAdder>::iterator it = gen.begin();\n\n  ASSERT_FALSE(it == gen.end());\n  EXPECT_STREQ(\"cat\", it->value().c_str());\n\n  ASSERT_FALSE(++it == gen.end());\n  EXPECT_STREQ(\"catdog\", it->value().c_str());\n\n  EXPECT_TRUE(++it == gen.end());\n}\n\nclass IntWrapper {\n public:\n  explicit IntWrapper(int a_value) : value_(a_value) {}\n  IntWrapper(const IntWrapper& other) : value_(other.value_) {}\n\n  IntWrapper operator=(const IntWrapper& other) {\n    value_ = other.value_;\n    return *this;\n  }\n  // operator+() adds a different type.\n  IntWrapper operator+(int other) const { return IntWrapper(value_ + other); }\n  bool operator<(const IntWrapper& other) const {\n    return value_ < other.value_;\n  }\n  int value() const { return value_; }\n\n private:\n  int value_;\n};\n\nTEST(RangeTest, WorksWithACustomTypeWithDifferentIncrementType) {\n  const ParamGenerator<IntWrapper> gen = Range(IntWrapper(0), IntWrapper(2));\n  ParamGenerator<IntWrapper>::iterator it = gen.begin();\n\n  ASSERT_FALSE(it == gen.end());\n  EXPECT_EQ(0, it->value());\n\n  ASSERT_FALSE(++it == gen.end());\n  EXPECT_EQ(1, it->value());\n\n  EXPECT_TRUE(++it == gen.end());\n}\n\n// Tests that ValuesIn() with an array parameter generates\n// the expected sequence.\nTEST(ValuesInTest, ValuesInArray) {\n  int array[] = {3, 5, 8};\n  const ParamGenerator<int> gen = ValuesIn(array);\n  VerifyGenerator(gen, array);\n}\n\n// Tests that ValuesIn() with a const array parameter generates\n// the expected sequence.\nTEST(ValuesInTest, ValuesInConstArray) {\n  const int array[] = {3, 5, 8};\n  const ParamGenerator<int> gen = ValuesIn(array);\n  VerifyGenerator(gen, array);\n}\n\n// Edge case. Tests that ValuesIn() with an array parameter containing a\n// single element generates the single element sequence.\nTEST(ValuesInTest, ValuesInSingleElementArray) {\n  int array[] = {42};\n  const ParamGenerator<int> gen = ValuesIn(array);\n  VerifyGenerator(gen, array);\n}\n\n// Tests that ValuesIn() generates the expected sequence for an STL\n// container (vector).\nTEST(ValuesInTest, ValuesInVector) {\n  typedef ::std::vector<int> ContainerType;\n  ContainerType values;\n  values.push_back(3);\n  values.push_back(5);\n  values.push_back(8);\n  const ParamGenerator<int> gen = ValuesIn(values);\n\n  const int expected_values[] = {3, 5, 8};\n  VerifyGenerator(gen, expected_values);\n}\n\n// Tests that ValuesIn() generates the expected sequence.\nTEST(ValuesInTest, ValuesInIteratorRange) {\n  typedef ::std::vector<int> ContainerType;\n  ContainerType values;\n  values.push_back(3);\n  values.push_back(5);\n  values.push_back(8);\n  const ParamGenerator<int> gen = ValuesIn(values.begin(), values.end());\n\n  const int expected_values[] = {3, 5, 8};\n  VerifyGenerator(gen, expected_values);\n}\n\n// Edge case. Tests that ValuesIn() provided with an iterator range specifying a\n// single value generates a single-element sequence.\nTEST(ValuesInTest, ValuesInSingleElementIteratorRange) {\n  typedef ::std::vector<int> ContainerType;\n  ContainerType values;\n  values.push_back(42);\n  const ParamGenerator<int> gen = ValuesIn(values.begin(), values.end());\n\n  const int expected_values[] = {42};\n  VerifyGenerator(gen, expected_values);\n}\n\n// Edge case. Tests that ValuesIn() provided with an empty iterator range\n// generates an empty sequence.\nTEST(ValuesInTest, ValuesInEmptyIteratorRange) {\n  typedef ::std::vector<int> ContainerType;\n  ContainerType values;\n  const ParamGenerator<int> gen = ValuesIn(values.begin(), values.end());\n\n  VerifyGeneratorIsEmpty(gen);\n}\n\n// Tests that the Values() generates the expected sequence.\nTEST(ValuesTest, ValuesWorks) {\n  const ParamGenerator<int> gen = Values(3, 5, 8);\n\n  const int expected_values[] = {3, 5, 8};\n  VerifyGenerator(gen, expected_values);\n}\n\n// Tests that Values() generates the expected sequences from elements of\n// different types convertible to ParamGenerator's parameter type.\nTEST(ValuesTest, ValuesWorksForValuesOfCompatibleTypes) {\n  const ParamGenerator<double> gen = Values(3, 5.0f, 8.0);\n\n  const double expected_values[] = {3.0, 5.0, 8.0};\n  VerifyGenerator(gen, expected_values);\n}\n\nTEST(ValuesTest, ValuesWorksForMaxLengthList) {\n  const ParamGenerator<int> gen =\n      Values(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150,\n             160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280,\n             290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390, 400, 410,\n             420, 430, 440, 450, 460, 470, 480, 490, 500);\n\n  const int expected_values[] = {\n      10,  20,  30,  40,  50,  60,  70,  80,  90,  100, 110, 120, 130,\n      140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260,\n      270, 280, 290, 300, 310, 320, 330, 340, 350, 360, 370, 380, 390,\n      400, 410, 420, 430, 440, 450, 460, 470, 480, 490, 500};\n  VerifyGenerator(gen, expected_values);\n}\n\n// Edge case test. Tests that single-parameter Values() generates the sequence\n// with the single value.\nTEST(ValuesTest, ValuesWithSingleParameter) {\n  const ParamGenerator<int> gen = Values(42);\n\n  const int expected_values[] = {42};\n  VerifyGenerator(gen, expected_values);\n}\n\n// Tests that Bool() generates sequence (false, true).\nTEST(BoolTest, BoolWorks) {\n  const ParamGenerator<bool> gen = Bool();\n\n  const bool expected_values[] = {false, true};\n  VerifyGenerator(gen, expected_values);\n}\n\n// Tests that Combine() with two parameters generates the expected sequence.\nTEST(CombineTest, CombineWithTwoParameters) {\n  const char* foo = \"foo\";\n  const char* bar = \"bar\";\n  const ParamGenerator<std::tuple<const char*, int> > gen =\n      Combine(Values(foo, bar), Values(3, 4));\n\n  std::tuple<const char*, int> expected_values[] = {\n      std::make_tuple(foo, 3), std::make_tuple(foo, 4), std::make_tuple(bar, 3),\n      std::make_tuple(bar, 4)};\n  VerifyGenerator(gen, expected_values);\n}\n\n// Tests that Combine() with three parameters generates the expected sequence.\nTEST(CombineTest, CombineWithThreeParameters) {\n  const ParamGenerator<std::tuple<int, int, int> > gen =\n      Combine(Values(0, 1), Values(3, 4), Values(5, 6));\n  std::tuple<int, int, int> expected_values[] = {\n      std::make_tuple(0, 3, 5), std::make_tuple(0, 3, 6),\n      std::make_tuple(0, 4, 5), std::make_tuple(0, 4, 6),\n      std::make_tuple(1, 3, 5), std::make_tuple(1, 3, 6),\n      std::make_tuple(1, 4, 5), std::make_tuple(1, 4, 6)};\n  VerifyGenerator(gen, expected_values);\n}\n\n// Tests that the Combine() with the first parameter generating a single value\n// sequence generates a sequence with the number of elements equal to the\n// number of elements in the sequence generated by the second parameter.\nTEST(CombineTest, CombineWithFirstParameterSingleValue) {\n  const ParamGenerator<std::tuple<int, int> > gen =\n      Combine(Values(42), Values(0, 1));\n\n  std::tuple<int, int> expected_values[] = {std::make_tuple(42, 0),\n                                            std::make_tuple(42, 1)};\n  VerifyGenerator(gen, expected_values);\n}\n\n// Tests that the Combine() with the second parameter generating a single value\n// sequence generates a sequence with the number of elements equal to the\n// number of elements in the sequence generated by the first parameter.\nTEST(CombineTest, CombineWithSecondParameterSingleValue) {\n  const ParamGenerator<std::tuple<int, int> > gen =\n      Combine(Values(0, 1), Values(42));\n\n  std::tuple<int, int> expected_values[] = {std::make_tuple(0, 42),\n                                            std::make_tuple(1, 42)};\n  VerifyGenerator(gen, expected_values);\n}\n\n// Tests that when the first parameter produces an empty sequence,\n// Combine() produces an empty sequence, too.\nTEST(CombineTest, CombineWithFirstParameterEmptyRange) {\n  const ParamGenerator<std::tuple<int, int> > gen =\n      Combine(Range(0, 0), Values(0, 1));\n  VerifyGeneratorIsEmpty(gen);\n}\n\n// Tests that when the second parameter produces an empty sequence,\n// Combine() produces an empty sequence, too.\nTEST(CombineTest, CombineWithSecondParameterEmptyRange) {\n  const ParamGenerator<std::tuple<int, int> > gen =\n      Combine(Values(0, 1), Range(1, 1));\n  VerifyGeneratorIsEmpty(gen);\n}\n\n// Edge case. Tests that combine works with the maximum number\n// of parameters supported by Google Test (currently 10).\nTEST(CombineTest, CombineWithMaxNumberOfParameters) {\n  const char* foo = \"foo\";\n  const char* bar = \"bar\";\n  const ParamGenerator<\n      std::tuple<const char*, int, int, int, int, int, int, int, int, int> >\n      gen =\n          Combine(Values(foo, bar), Values(1), Values(2), Values(3), Values(4),\n                  Values(5), Values(6), Values(7), Values(8), Values(9));\n\n  std::tuple<const char*, int, int, int, int, int, int, int, int, int>\n      expected_values[] = {std::make_tuple(foo, 1, 2, 3, 4, 5, 6, 7, 8, 9),\n                           std::make_tuple(bar, 1, 2, 3, 4, 5, 6, 7, 8, 9)};\n  VerifyGenerator(gen, expected_values);\n}\n\nclass NonDefaultConstructAssignString {\n public:\n  NonDefaultConstructAssignString(const std::string& s) : str_(s) {}\n  NonDefaultConstructAssignString() = delete;\n  NonDefaultConstructAssignString(const NonDefaultConstructAssignString&) =\n      default;\n  NonDefaultConstructAssignString& operator=(\n      const NonDefaultConstructAssignString&) = delete;\n  ~NonDefaultConstructAssignString() = default;\n\n  const std::string& str() const { return str_; }\n\n private:\n  std::string str_;\n};\n\nTEST(CombineTest, NonDefaultConstructAssign) {\n  const ParamGenerator<std::tuple<int, NonDefaultConstructAssignString> > gen =\n      Combine(Values(0, 1), Values(NonDefaultConstructAssignString(\"A\"),\n                                   NonDefaultConstructAssignString(\"B\")));\n\n  ParamGenerator<std::tuple<int, NonDefaultConstructAssignString> >::iterator\n      it = gen.begin();\n\n  EXPECT_EQ(0, std::get<0>(*it));\n  EXPECT_EQ(\"A\", std::get<1>(*it).str());\n  ++it;\n\n  EXPECT_EQ(0, std::get<0>(*it));\n  EXPECT_EQ(\"B\", std::get<1>(*it).str());\n  ++it;\n\n  EXPECT_EQ(1, std::get<0>(*it));\n  EXPECT_EQ(\"A\", std::get<1>(*it).str());\n  ++it;\n\n  EXPECT_EQ(1, std::get<0>(*it));\n  EXPECT_EQ(\"B\", std::get<1>(*it).str());\n  ++it;\n\n  EXPECT_TRUE(it == gen.end());\n}\n\n// Tests that an generator produces correct sequence after being\n// assigned from another generator.\nTEST(ParamGeneratorTest, AssignmentWorks) {\n  ParamGenerator<int> gen = Values(1, 2);\n  const ParamGenerator<int> gen2 = Values(3, 4);\n  gen = gen2;\n\n  const int expected_values[] = {3, 4};\n  VerifyGenerator(gen, expected_values);\n}\n\n// This test verifies that the tests are expanded and run as specified:\n// one test per element from the sequence produced by the generator\n// specified in INSTANTIATE_TEST_SUITE_P. It also verifies that the test's\n// fixture constructor, SetUp(), and TearDown() have run and have been\n// supplied with the correct parameters.\n\n// The use of environment object allows detection of the case where no test\n// case functionality is run at all. In this case TearDownTestSuite will not\n// be able to detect missing tests, naturally.\ntemplate <int kExpectedCalls>\nclass TestGenerationEnvironment : public ::testing::Environment {\n public:\n  static TestGenerationEnvironment* Instance() {\n    static TestGenerationEnvironment* instance = new TestGenerationEnvironment;\n    return instance;\n  }\n\n  void FixtureConstructorExecuted() { fixture_constructor_count_++; }\n  void SetUpExecuted() { set_up_count_++; }\n  void TearDownExecuted() { tear_down_count_++; }\n  void TestBodyExecuted() { test_body_count_++; }\n\n  void TearDown() override {\n    // If all MultipleTestGenerationTest tests have been de-selected\n    // by the filter flag, the following checks make no sense.\n    bool perform_check = false;\n\n    for (int i = 0; i < kExpectedCalls; ++i) {\n      Message msg;\n      msg << \"TestsExpandedAndRun/\" << i;\n      if (UnitTestOptions::FilterMatchesTest(\n              \"TestExpansionModule/MultipleTestGenerationTest\",\n              msg.GetString().c_str())) {\n        perform_check = true;\n      }\n    }\n    if (perform_check) {\n      EXPECT_EQ(kExpectedCalls, fixture_constructor_count_)\n          << \"Fixture constructor of ParamTestGenerationTest test case \"\n          << \"has not been run as expected.\";\n      EXPECT_EQ(kExpectedCalls, set_up_count_)\n          << \"Fixture SetUp method of ParamTestGenerationTest test case \"\n          << \"has not been run as expected.\";\n      EXPECT_EQ(kExpectedCalls, tear_down_count_)\n          << \"Fixture TearDown method of ParamTestGenerationTest test case \"\n          << \"has not been run as expected.\";\n      EXPECT_EQ(kExpectedCalls, test_body_count_)\n          << \"Test in ParamTestGenerationTest test case \"\n          << \"has not been run as expected.\";\n    }\n  }\n\n private:\n  TestGenerationEnvironment()\n      : fixture_constructor_count_(0),\n        set_up_count_(0),\n        tear_down_count_(0),\n        test_body_count_(0) {}\n\n  int fixture_constructor_count_;\n  int set_up_count_;\n  int tear_down_count_;\n  int test_body_count_;\n\n  TestGenerationEnvironment(const TestGenerationEnvironment&) = delete;\n  TestGenerationEnvironment& operator=(const TestGenerationEnvironment&) =\n      delete;\n};\n\nconst int test_generation_params[] = {36, 42, 72};\n\nclass TestGenerationTest : public TestWithParam<int> {\n public:\n  enum {\n    PARAMETER_COUNT =\n        sizeof(test_generation_params) / sizeof(test_generation_params[0])\n  };\n\n  typedef TestGenerationEnvironment<PARAMETER_COUNT> Environment;\n\n  TestGenerationTest() {\n    Environment::Instance()->FixtureConstructorExecuted();\n    current_parameter_ = GetParam();\n  }\n  void SetUp() override {\n    Environment::Instance()->SetUpExecuted();\n    EXPECT_EQ(current_parameter_, GetParam());\n  }\n  void TearDown() override {\n    Environment::Instance()->TearDownExecuted();\n    EXPECT_EQ(current_parameter_, GetParam());\n  }\n\n  static void SetUpTestSuite() {\n    bool all_tests_in_test_case_selected = true;\n\n    for (int i = 0; i < PARAMETER_COUNT; ++i) {\n      Message test_name;\n      test_name << \"TestsExpandedAndRun/\" << i;\n      if (!UnitTestOptions::FilterMatchesTest(\n              \"TestExpansionModule/MultipleTestGenerationTest\",\n              test_name.GetString())) {\n        all_tests_in_test_case_selected = false;\n      }\n    }\n    EXPECT_TRUE(all_tests_in_test_case_selected)\n        << \"When running the TestGenerationTest test case all of its tests\\n\"\n        << \"must be selected by the filter flag for the test case to pass.\\n\"\n        << \"If not all of them are enabled, we can't reliably conclude\\n\"\n        << \"that the correct number of tests have been generated.\";\n\n    collected_parameters_.clear();\n  }\n\n  static void TearDownTestSuite() {\n    vector<int> expected_values(test_generation_params,\n                                test_generation_params + PARAMETER_COUNT);\n    // Test execution order is not guaranteed by Google Test,\n    // so the order of values in collected_parameters_ can be\n    // different and we have to sort to compare.\n    sort(expected_values.begin(), expected_values.end());\n    sort(collected_parameters_.begin(), collected_parameters_.end());\n\n    EXPECT_TRUE(collected_parameters_ == expected_values);\n  }\n\n protected:\n  int current_parameter_;\n  static vector<int> collected_parameters_;\n\n private:\n  TestGenerationTest(const TestGenerationTest&) = delete;\n  TestGenerationTest& operator=(const TestGenerationTest&) = delete;\n};\nvector<int> TestGenerationTest::collected_parameters_;\n\nTEST_P(TestGenerationTest, TestsExpandedAndRun) {\n  Environment::Instance()->TestBodyExecuted();\n  EXPECT_EQ(current_parameter_, GetParam());\n  collected_parameters_.push_back(GetParam());\n}\nINSTANTIATE_TEST_SUITE_P(TestExpansionModule, TestGenerationTest,\n                         ValuesIn(test_generation_params));\n\n// This test verifies that the element sequence (third parameter of\n// INSTANTIATE_TEST_SUITE_P) is evaluated in InitGoogleTest() and neither at\n// the call site of INSTANTIATE_TEST_SUITE_P nor in RUN_ALL_TESTS().  For\n// that, we declare param_value_ to be a static member of\n// GeneratorEvaluationTest and initialize it to 0.  We set it to 1 in\n// main(), just before invocation of InitGoogleTest().  After calling\n// InitGoogleTest(), we set the value to 2.  If the sequence is evaluated\n// before or after InitGoogleTest, INSTANTIATE_TEST_SUITE_P will create a\n// test with parameter other than 1, and the test body will fail the\n// assertion.\nclass GeneratorEvaluationTest : public TestWithParam<int> {\n public:\n  static int param_value() { return param_value_; }\n  static void set_param_value(int param_value) { param_value_ = param_value; }\n\n private:\n  static int param_value_;\n};\nint GeneratorEvaluationTest::param_value_ = 0;\n\nTEST_P(GeneratorEvaluationTest, GeneratorsEvaluatedInMain) {\n  EXPECT_EQ(1, GetParam());\n}\nINSTANTIATE_TEST_SUITE_P(GenEvalModule, GeneratorEvaluationTest,\n                         Values(GeneratorEvaluationTest::param_value()));\n\n// Tests that generators defined in a different translation unit are\n// functional. Generator extern_gen is defined in gtest-param-test_test2.cc.\nextern ParamGenerator<int> extern_gen;\nclass ExternalGeneratorTest : public TestWithParam<int> {};\nTEST_P(ExternalGeneratorTest, ExternalGenerator) {\n  // Sequence produced by extern_gen contains only a single value\n  // which we verify here.\n  EXPECT_EQ(GetParam(), 33);\n}\nINSTANTIATE_TEST_SUITE_P(ExternalGeneratorModule, ExternalGeneratorTest,\n                         extern_gen);\n\n// Tests that a parameterized test case can be defined in one translation\n// unit and instantiated in another. This test will be instantiated in\n// gtest-param-test_test2.cc. ExternalInstantiationTest fixture class is\n// defined in gtest-param-test_test.h.\nTEST_P(ExternalInstantiationTest, IsMultipleOf33) {\n  EXPECT_EQ(0, GetParam() % 33);\n}\n\n// Tests that a parameterized test case can be instantiated with multiple\n// generators.\nclass MultipleInstantiationTest : public TestWithParam<int> {};\nTEST_P(MultipleInstantiationTest, AllowsMultipleInstances) {}\nINSTANTIATE_TEST_SUITE_P(Sequence1, MultipleInstantiationTest, Values(1, 2));\nINSTANTIATE_TEST_SUITE_P(Sequence2, MultipleInstantiationTest, Range(3, 5));\n\n// Tests that a parameterized test case can be instantiated\n// in multiple translation units. This test will be instantiated\n// here and in gtest-param-test_test2.cc.\n// InstantiationInMultipleTranslationUnitsTest fixture class\n// is defined in gtest-param-test_test.h.\nTEST_P(InstantiationInMultipleTranslationUnitsTest, IsMultipleOf42) {\n  EXPECT_EQ(0, GetParam() % 42);\n}\nINSTANTIATE_TEST_SUITE_P(Sequence1, InstantiationInMultipleTranslationUnitsTest,\n                         Values(42, 42 * 2));\n\n// Tests that each iteration of parameterized test runs in a separate test\n// object.\nclass SeparateInstanceTest : public TestWithParam<int> {\n public:\n  SeparateInstanceTest() : count_(0) {}\n\n  static void TearDownTestSuite() {\n    EXPECT_GE(global_count_, 2)\n        << \"If some (but not all) SeparateInstanceTest tests have been \"\n        << \"filtered out this test will fail. Make sure that all \"\n        << \"GeneratorEvaluationTest are selected or de-selected together \"\n        << \"by the test filter.\";\n  }\n\n protected:\n  int count_;\n  static int global_count_;\n};\nint SeparateInstanceTest::global_count_ = 0;\n\nTEST_P(SeparateInstanceTest, TestsRunInSeparateInstances) {\n  EXPECT_EQ(0, count_++);\n  global_count_++;\n}\nINSTANTIATE_TEST_SUITE_P(FourElemSequence, SeparateInstanceTest, Range(1, 4));\n\n// Tests that all instantiations of a test have named appropriately. Test\n// defined with TEST_P(TestSuiteName, TestName) and instantiated with\n// INSTANTIATE_TEST_SUITE_P(SequenceName, TestSuiteName, generator) must be\n// named SequenceName/TestSuiteName.TestName/i, where i is the 0-based index of\n// the sequence element used to instantiate the test.\nclass NamingTest : public TestWithParam<int> {};\n\nTEST_P(NamingTest, TestsReportCorrectNamesAndParameters) {\n  const ::testing::TestInfo* const test_info =\n      ::testing::UnitTest::GetInstance()->current_test_info();\n\n  EXPECT_STREQ(\"ZeroToFiveSequence/NamingTest\", test_info->test_suite_name());\n\n  Message index_stream;\n  index_stream << \"TestsReportCorrectNamesAndParameters/\" << GetParam();\n  EXPECT_STREQ(index_stream.GetString().c_str(), test_info->name());\n\n  EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param());\n}\n\nINSTANTIATE_TEST_SUITE_P(ZeroToFiveSequence, NamingTest, Range(0, 5));\n\n// Tests that macros in test names are expanded correctly.\nclass MacroNamingTest : public TestWithParam<int> {};\n\n#define PREFIX_WITH_FOO(test_name) Foo##test_name\n#define PREFIX_WITH_MACRO(test_name) Macro##test_name\n\nTEST_P(PREFIX_WITH_MACRO(NamingTest), PREFIX_WITH_FOO(SomeTestName)) {\n  const ::testing::TestInfo* const test_info =\n      ::testing::UnitTest::GetInstance()->current_test_info();\n\n  EXPECT_STREQ(\"FortyTwo/MacroNamingTest\", test_info->test_suite_name());\n  EXPECT_STREQ(\"FooSomeTestName/0\", test_info->name());\n}\n\nINSTANTIATE_TEST_SUITE_P(FortyTwo, MacroNamingTest, Values(42));\n\n// Tests the same thing for non-parametrized tests.\nclass MacroNamingTestNonParametrized : public ::testing::Test {};\n\nTEST_F(PREFIX_WITH_MACRO(NamingTestNonParametrized),\n       PREFIX_WITH_FOO(SomeTestName)) {\n  const ::testing::TestInfo* const test_info =\n      ::testing::UnitTest::GetInstance()->current_test_info();\n\n  EXPECT_STREQ(\"MacroNamingTestNonParametrized\", test_info->test_suite_name());\n  EXPECT_STREQ(\"FooSomeTestName\", test_info->name());\n}\n\nTEST(MacroNameing, LookupNames) {\n  std::set<std::string> know_suite_names, know_test_names;\n\n  auto ins = testing::UnitTest::GetInstance();\n  int ts = 0;\n  while (const testing::TestSuite* suite = ins->GetTestSuite(ts++)) {\n    know_suite_names.insert(suite->name());\n\n    int ti = 0;\n    while (const testing::TestInfo* info = suite->GetTestInfo(ti++)) {\n      know_test_names.insert(std::string(suite->name()) + \".\" + info->name());\n    }\n  }\n\n  // Check that the expected form of the test suit name actually exists.\n  EXPECT_NE(  //\n      know_suite_names.find(\"FortyTwo/MacroNamingTest\"),\n      know_suite_names.end());\n  EXPECT_NE(know_suite_names.find(\"MacroNamingTestNonParametrized\"),\n            know_suite_names.end());\n  // Check that the expected form of the test name actually exists.\n  EXPECT_NE(  //\n      know_test_names.find(\"FortyTwo/MacroNamingTest.FooSomeTestName/0\"),\n      know_test_names.end());\n  EXPECT_NE(\n      know_test_names.find(\"MacroNamingTestNonParametrized.FooSomeTestName\"),\n      know_test_names.end());\n}\n\n// Tests that user supplied custom parameter names are working correctly.\n// Runs the test with a builtin helper method which uses PrintToString,\n// as well as a custom function and custom functor to ensure all possible\n// uses work correctly.\nclass CustomFunctorNamingTest : public TestWithParam<std::string> {};\nTEST_P(CustomFunctorNamingTest, CustomTestNames) {}\n\nstruct CustomParamNameFunctor {\n  std::string operator()(const ::testing::TestParamInfo<std::string>& inf) {\n    return inf.param;\n  }\n};\n\nINSTANTIATE_TEST_SUITE_P(CustomParamNameFunctor, CustomFunctorNamingTest,\n                         Values(std::string(\"FunctorName\")),\n                         CustomParamNameFunctor());\n\nINSTANTIATE_TEST_SUITE_P(AllAllowedCharacters, CustomFunctorNamingTest,\n                         Values(\"abcdefghijklmnopqrstuvwxyz\",\n                                \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", \"01234567890_\"),\n                         CustomParamNameFunctor());\n\ninline std::string CustomParamNameFunction(\n    const ::testing::TestParamInfo<std::string>& inf) {\n  return inf.param;\n}\n\nclass CustomFunctionNamingTest : public TestWithParam<std::string> {};\nTEST_P(CustomFunctionNamingTest, CustomTestNames) {}\n\nINSTANTIATE_TEST_SUITE_P(CustomParamNameFunction, CustomFunctionNamingTest,\n                         Values(std::string(\"FunctionName\")),\n                         CustomParamNameFunction);\n\nINSTANTIATE_TEST_SUITE_P(CustomParamNameFunctionP, CustomFunctionNamingTest,\n                         Values(std::string(\"FunctionNameP\")),\n                         &CustomParamNameFunction);\n\n// Test custom naming with a lambda\n\nclass CustomLambdaNamingTest : public TestWithParam<std::string> {};\nTEST_P(CustomLambdaNamingTest, CustomTestNames) {}\n\nINSTANTIATE_TEST_SUITE_P(CustomParamNameLambda, CustomLambdaNamingTest,\n                         Values(std::string(\"LambdaName\")),\n                         [](const ::testing::TestParamInfo<std::string>& inf) {\n                           return inf.param;\n                         });\n\nTEST(CustomNamingTest, CheckNameRegistry) {\n  ::testing::UnitTest* unit_test = ::testing::UnitTest::GetInstance();\n  std::set<std::string> test_names;\n  for (int suite_num = 0; suite_num < unit_test->total_test_suite_count();\n       ++suite_num) {\n    const ::testing::TestSuite* test_suite = unit_test->GetTestSuite(suite_num);\n    for (int test_num = 0; test_num < test_suite->total_test_count();\n         ++test_num) {\n      const ::testing::TestInfo* test_info = test_suite->GetTestInfo(test_num);\n      test_names.insert(std::string(test_info->name()));\n    }\n  }\n  EXPECT_EQ(1u, test_names.count(\"CustomTestNames/FunctorName\"));\n  EXPECT_EQ(1u, test_names.count(\"CustomTestNames/FunctionName\"));\n  EXPECT_EQ(1u, test_names.count(\"CustomTestNames/FunctionNameP\"));\n  EXPECT_EQ(1u, test_names.count(\"CustomTestNames/LambdaName\"));\n}\n\n// Test a numeric name to ensure PrintToStringParamName works correctly.\n\nclass CustomIntegerNamingTest : public TestWithParam<int> {};\n\nTEST_P(CustomIntegerNamingTest, TestsReportCorrectNames) {\n  const ::testing::TestInfo* const test_info =\n      ::testing::UnitTest::GetInstance()->current_test_info();\n  Message test_name_stream;\n  test_name_stream << \"TestsReportCorrectNames/\" << GetParam();\n  EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name());\n}\n\nINSTANTIATE_TEST_SUITE_P(PrintToString, CustomIntegerNamingTest, Range(0, 5),\n                         ::testing::PrintToStringParamName());\n\n// Test a custom struct with PrintToString.\n\nstruct CustomStruct {\n  explicit CustomStruct(int value) : x(value) {}\n  int x;\n};\n\nstd::ostream& operator<<(std::ostream& stream, const CustomStruct& val) {\n  stream << val.x;\n  return stream;\n}\n\nclass CustomStructNamingTest : public TestWithParam<CustomStruct> {};\n\nTEST_P(CustomStructNamingTest, TestsReportCorrectNames) {\n  const ::testing::TestInfo* const test_info =\n      ::testing::UnitTest::GetInstance()->current_test_info();\n  Message test_name_stream;\n  test_name_stream << \"TestsReportCorrectNames/\" << GetParam();\n  EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name());\n}\n\nINSTANTIATE_TEST_SUITE_P(PrintToString, CustomStructNamingTest,\n                         Values(CustomStruct(0), CustomStruct(1)),\n                         ::testing::PrintToStringParamName());\n\n// Test that using a stateful parameter naming function works as expected.\n\nstruct StatefulNamingFunctor {\n  StatefulNamingFunctor() : sum(0) {}\n  std::string operator()(const ::testing::TestParamInfo<int>& info) {\n    int value = info.param + sum;\n    sum += info.param;\n    return ::testing::PrintToString(value);\n  }\n  int sum;\n};\n\nclass StatefulNamingTest : public ::testing::TestWithParam<int> {\n protected:\n  StatefulNamingTest() : sum_(0) {}\n  int sum_;\n};\n\nTEST_P(StatefulNamingTest, TestsReportCorrectNames) {\n  const ::testing::TestInfo* const test_info =\n      ::testing::UnitTest::GetInstance()->current_test_info();\n  sum_ += GetParam();\n  Message test_name_stream;\n  test_name_stream << \"TestsReportCorrectNames/\" << sum_;\n  EXPECT_STREQ(test_name_stream.GetString().c_str(), test_info->name());\n}\n\nINSTANTIATE_TEST_SUITE_P(StatefulNamingFunctor, StatefulNamingTest, Range(0, 5),\n                         StatefulNamingFunctor());\n\n// Class that cannot be streamed into an ostream.  It needs to be copyable\n// (and, in case of MSVC, also assignable) in order to be a test parameter\n// type.  Its default copy constructor and assignment operator do exactly\n// what we need.\nclass Unstreamable {\n public:\n  explicit Unstreamable(int value) : value_(value) {}\n  // -Wunused-private-field: dummy accessor for `value_`.\n  const int& dummy_value() const { return value_; }\n\n private:\n  int value_;\n};\n\nclass CommentTest : public TestWithParam<Unstreamable> {};\n\nTEST_P(CommentTest, TestsCorrectlyReportUnstreamableParams) {\n  const ::testing::TestInfo* const test_info =\n      ::testing::UnitTest::GetInstance()->current_test_info();\n\n  EXPECT_EQ(::testing::PrintToString(GetParam()), test_info->value_param());\n}\n\nINSTANTIATE_TEST_SUITE_P(InstantiationWithComments, CommentTest,\n                         Values(Unstreamable(1)));\n\n// Verify that we can create a hierarchy of test fixtures, where the base\n// class fixture is not parameterized and the derived class is. In this case\n// ParameterizedDerivedTest inherits from NonParameterizedBaseTest.  We\n// perform simple tests on both.\nclass NonParameterizedBaseTest : public ::testing::Test {\n public:\n  NonParameterizedBaseTest() : n_(17) {}\n\n protected:\n  int n_;\n};\n\nclass ParameterizedDerivedTest : public NonParameterizedBaseTest,\n                                 public ::testing::WithParamInterface<int> {\n protected:\n  ParameterizedDerivedTest() : count_(0) {}\n  int count_;\n  static int global_count_;\n};\n\nint ParameterizedDerivedTest::global_count_ = 0;\n\nTEST_F(NonParameterizedBaseTest, FixtureIsInitialized) { EXPECT_EQ(17, n_); }\n\nTEST_P(ParameterizedDerivedTest, SeesSequence) {\n  EXPECT_EQ(17, n_);\n  EXPECT_EQ(0, count_++);\n  EXPECT_EQ(GetParam(), global_count_++);\n}\n\nclass ParameterizedDeathTest : public ::testing::TestWithParam<int> {};\n\nTEST_F(ParameterizedDeathTest, GetParamDiesFromTestF) {\n  EXPECT_DEATH_IF_SUPPORTED(GetParam(), \".* value-parameterized test .*\");\n}\n\nINSTANTIATE_TEST_SUITE_P(RangeZeroToFive, ParameterizedDerivedTest,\n                         Range(0, 5));\n\n// Tests param generator working with Enums\nenum MyEnums {\n  ENUM1 = 1,\n  ENUM2 = 3,\n  ENUM3 = 8,\n};\n\nclass MyEnumTest : public testing::TestWithParam<MyEnums> {};\n\nTEST_P(MyEnumTest, ChecksParamMoreThanZero) { EXPECT_GE(10, GetParam()); }\nINSTANTIATE_TEST_SUITE_P(MyEnumTests, MyEnumTest,\n                         ::testing::Values(ENUM1, ENUM2, 0));\n\nnamespace works_here {\n// Never used not instantiated, this should work.\nclass NotUsedTest : public testing::TestWithParam<int> {};\n\n///////\n// Never used not instantiated, this should work.\ntemplate <typename T>\nclass NotUsedTypeTest : public testing::Test {};\nTYPED_TEST_SUITE_P(NotUsedTypeTest);\n\n// Used but not instantiated, this would fail. but...\nclass NotInstantiatedTest : public testing::TestWithParam<int> {};\n// ... we mark is as allowed.\nGTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTest);\n\nTEST_P(NotInstantiatedTest, Used) {}\n\nusing OtherName = NotInstantiatedTest;\nGTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(OtherName);\nTEST_P(OtherName, Used) {}\n\n// Used but not instantiated, this would fail. but...\ntemplate <typename T>\nclass NotInstantiatedTypeTest : public testing::Test {};\nTYPED_TEST_SUITE_P(NotInstantiatedTypeTest);\n// ... we mark is as allowed.\nGTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(NotInstantiatedTypeTest);\n\nTYPED_TEST_P(NotInstantiatedTypeTest, Used) {}\nREGISTER_TYPED_TEST_SUITE_P(NotInstantiatedTypeTest, Used);\n}  // namespace works_here\n\nint main(int argc, char** argv) {\n  // Used in TestGenerationTest test suite.\n  AddGlobalTestEnvironment(TestGenerationTest::Environment::Instance());\n  // Used in GeneratorEvaluationTest test suite. Tests that the updated value\n  // will be picked up for instantiating tests in GeneratorEvaluationTest.\n  GeneratorEvaluationTest::set_param_value(1);\n\n  ::testing::InitGoogleTest(&argc, argv);\n\n  // Used in GeneratorEvaluationTest test suite. Tests that value updated\n  // here will NOT be used for instantiating tests in\n  // GeneratorEvaluationTest.\n  GeneratorEvaluationTest::set_param_value(2);\n\n  return RUN_ALL_TESTS();\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-param-test-test.h",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// The Google C++ Testing and Mocking Framework (Google Test)\n//\n// This header file provides classes and functions used internally\n// for testing Google Test itself.\n\n#ifndef GOOGLETEST_TEST_GOOGLETEST_PARAM_TEST_TEST_H_\n#define GOOGLETEST_TEST_GOOGLETEST_PARAM_TEST_TEST_H_\n\n#include \"gtest/gtest.h\"\n\n// Test fixture for testing definition and instantiation of a test\n// in separate translation units.\nclass ExternalInstantiationTest : public ::testing::TestWithParam<int> {};\n\n// Test fixture for testing instantiation of a test in multiple\n// translation units.\nclass InstantiationInMultipleTranslationUnitsTest\n    : public ::testing::TestWithParam<int> {};\n\n#endif  // GOOGLETEST_TEST_GOOGLETEST_PARAM_TEST_TEST_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-param-test2-test.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// Tests for Google Test itself.  This verifies that the basic constructs of\n// Google Test work.\n\n#include \"gtest/gtest.h\"\n#include \"test/googletest-param-test-test.h\"\n\nusing ::testing::Values;\nusing ::testing::internal::ParamGenerator;\n\n// Tests that generators defined in a different translation unit\n// are functional. The test using extern_gen is defined\n// in googletest-param-test-test.cc.\nParamGenerator<int> extern_gen = Values(33);\n\n// Tests that a parameterized test case can be defined in one translation unit\n// and instantiated in another. The test is defined in\n// googletest-param-test-test.cc and ExternalInstantiationTest fixture class is\n// defined in gtest-param-test_test.h.\nINSTANTIATE_TEST_SUITE_P(MultiplesOf33, ExternalInstantiationTest,\n                         Values(33, 66));\n\n// Tests that a parameterized test case can be instantiated\n// in multiple translation units. Another instantiation is defined\n// in googletest-param-test-test.cc and\n// InstantiationInMultipleTranslationUnitsTest fixture is defined in\n// gtest-param-test_test.h\nINSTANTIATE_TEST_SUITE_P(Sequence2, InstantiationInMultipleTranslationUnitsTest,\n                         Values(42 * 3, 42 * 4, 42 * 5));\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-port-test.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// This file tests the internal cross-platform support utilities.\n#include <stdio.h>\n\n#include \"gtest/internal/gtest-port.h\"\n\n#if GTEST_OS_MAC\n#include <time.h>\n#endif  // GTEST_OS_MAC\n\n#include <chrono>  // NOLINT\n#include <list>\n#include <memory>\n#include <thread>   // NOLINT\n#include <utility>  // For std::pair and std::make_pair.\n#include <vector>\n\n#include \"gtest/gtest-spi.h\"\n#include \"gtest/gtest.h\"\n#include \"src/gtest-internal-inl.h\"\n\nusing std::make_pair;\nusing std::pair;\n\nnamespace testing {\nnamespace internal {\n\nTEST(IsXDigitTest, WorksForNarrowAscii) {\n  EXPECT_TRUE(IsXDigit('0'));\n  EXPECT_TRUE(IsXDigit('9'));\n  EXPECT_TRUE(IsXDigit('A'));\n  EXPECT_TRUE(IsXDigit('F'));\n  EXPECT_TRUE(IsXDigit('a'));\n  EXPECT_TRUE(IsXDigit('f'));\n\n  EXPECT_FALSE(IsXDigit('-'));\n  EXPECT_FALSE(IsXDigit('g'));\n  EXPECT_FALSE(IsXDigit('G'));\n}\n\nTEST(IsXDigitTest, ReturnsFalseForNarrowNonAscii) {\n  EXPECT_FALSE(IsXDigit(static_cast<char>('\\x80')));\n  EXPECT_FALSE(IsXDigit(static_cast<char>('0' | '\\x80')));\n}\n\nTEST(IsXDigitTest, WorksForWideAscii) {\n  EXPECT_TRUE(IsXDigit(L'0'));\n  EXPECT_TRUE(IsXDigit(L'9'));\n  EXPECT_TRUE(IsXDigit(L'A'));\n  EXPECT_TRUE(IsXDigit(L'F'));\n  EXPECT_TRUE(IsXDigit(L'a'));\n  EXPECT_TRUE(IsXDigit(L'f'));\n\n  EXPECT_FALSE(IsXDigit(L'-'));\n  EXPECT_FALSE(IsXDigit(L'g'));\n  EXPECT_FALSE(IsXDigit(L'G'));\n}\n\nTEST(IsXDigitTest, ReturnsFalseForWideNonAscii) {\n  EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(0x80)));\n  EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(L'0' | 0x80)));\n  EXPECT_FALSE(IsXDigit(static_cast<wchar_t>(L'0' | 0x100)));\n}\n\nclass Base {\n public:\n  Base() : member_(0) {}\n  explicit Base(int n) : member_(n) {}\n  Base(const Base&) = default;\n  Base& operator=(const Base&) = default;\n  virtual ~Base() {}\n  int member() { return member_; }\n\n private:\n  int member_;\n};\n\nclass Derived : public Base {\n public:\n  explicit Derived(int n) : Base(n) {}\n};\n\nTEST(ImplicitCastTest, ConvertsPointers) {\n  Derived derived(0);\n  EXPECT_TRUE(&derived == ::testing::internal::ImplicitCast_<Base*>(&derived));\n}\n\nTEST(ImplicitCastTest, CanUseInheritance) {\n  Derived derived(1);\n  Base base = ::testing::internal::ImplicitCast_<Base>(derived);\n  EXPECT_EQ(derived.member(), base.member());\n}\n\nclass Castable {\n public:\n  explicit Castable(bool* converted) : converted_(converted) {}\n  operator Base() {\n    *converted_ = true;\n    return Base();\n  }\n\n private:\n  bool* converted_;\n};\n\nTEST(ImplicitCastTest, CanUseNonConstCastOperator) {\n  bool converted = false;\n  Castable castable(&converted);\n  Base base = ::testing::internal::ImplicitCast_<Base>(castable);\n  EXPECT_TRUE(converted);\n}\n\nclass ConstCastable {\n public:\n  explicit ConstCastable(bool* converted) : converted_(converted) {}\n  operator Base() const {\n    *converted_ = true;\n    return Base();\n  }\n\n private:\n  bool* converted_;\n};\n\nTEST(ImplicitCastTest, CanUseConstCastOperatorOnConstValues) {\n  bool converted = false;\n  const ConstCastable const_castable(&converted);\n  Base base = ::testing::internal::ImplicitCast_<Base>(const_castable);\n  EXPECT_TRUE(converted);\n}\n\nclass ConstAndNonConstCastable {\n public:\n  ConstAndNonConstCastable(bool* converted, bool* const_converted)\n      : converted_(converted), const_converted_(const_converted) {}\n  operator Base() {\n    *converted_ = true;\n    return Base();\n  }\n  operator Base() const {\n    *const_converted_ = true;\n    return Base();\n  }\n\n private:\n  bool* converted_;\n  bool* const_converted_;\n};\n\nTEST(ImplicitCastTest, CanSelectBetweenConstAndNonConstCasrAppropriately) {\n  bool converted = false;\n  bool const_converted = false;\n  ConstAndNonConstCastable castable(&converted, &const_converted);\n  Base base = ::testing::internal::ImplicitCast_<Base>(castable);\n  EXPECT_TRUE(converted);\n  EXPECT_FALSE(const_converted);\n\n  converted = false;\n  const_converted = false;\n  const ConstAndNonConstCastable const_castable(&converted, &const_converted);\n  base = ::testing::internal::ImplicitCast_<Base>(const_castable);\n  EXPECT_FALSE(converted);\n  EXPECT_TRUE(const_converted);\n}\n\nclass To {\n public:\n  To(bool* converted) { *converted = true; }  // NOLINT\n};\n\nTEST(ImplicitCastTest, CanUseImplicitConstructor) {\n  bool converted = false;\n  To to = ::testing::internal::ImplicitCast_<To>(&converted);\n  (void)to;\n  EXPECT_TRUE(converted);\n}\n\n// The following code intentionally tests a suboptimal syntax.\n#ifdef __GNUC__\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wdangling-else\"\n#pragma GCC diagnostic ignored \"-Wempty-body\"\n#pragma GCC diagnostic ignored \"-Wpragmas\"\n#endif\nTEST(GtestCheckSyntaxTest, BehavesLikeASingleStatement) {\n  if (AlwaysFalse())\n    GTEST_CHECK_(false) << \"This should never be executed; \"\n                           \"It's a compilation test only.\";\n\n  if (AlwaysTrue())\n    GTEST_CHECK_(true);\n  else\n    ;  // NOLINT\n\n  if (AlwaysFalse())\n    ;  // NOLINT\n  else\n    GTEST_CHECK_(true) << \"\";\n}\n#ifdef __GNUC__\n#pragma GCC diagnostic pop\n#endif\n\nTEST(GtestCheckSyntaxTest, WorksWithSwitch) {\n  switch (0) {\n    case 1:\n      break;\n    default:\n      GTEST_CHECK_(true);\n  }\n\n  switch (0)\n  case 0:\n    GTEST_CHECK_(true) << \"Check failed in switch case\";\n}\n\n// Verifies behavior of FormatFileLocation.\nTEST(FormatFileLocationTest, FormatsFileLocation) {\n  EXPECT_PRED_FORMAT2(IsSubstring, \"foo.cc\", FormatFileLocation(\"foo.cc\", 42));\n  EXPECT_PRED_FORMAT2(IsSubstring, \"42\", FormatFileLocation(\"foo.cc\", 42));\n}\n\nTEST(FormatFileLocationTest, FormatsUnknownFile) {\n  EXPECT_PRED_FORMAT2(IsSubstring, \"unknown file\",\n                      FormatFileLocation(nullptr, 42));\n  EXPECT_PRED_FORMAT2(IsSubstring, \"42\", FormatFileLocation(nullptr, 42));\n}\n\nTEST(FormatFileLocationTest, FormatsUknownLine) {\n  EXPECT_EQ(\"foo.cc:\", FormatFileLocation(\"foo.cc\", -1));\n}\n\nTEST(FormatFileLocationTest, FormatsUknownFileAndLine) {\n  EXPECT_EQ(\"unknown file:\", FormatFileLocation(nullptr, -1));\n}\n\n// Verifies behavior of FormatCompilerIndependentFileLocation.\nTEST(FormatCompilerIndependentFileLocationTest, FormatsFileLocation) {\n  EXPECT_EQ(\"foo.cc:42\", FormatCompilerIndependentFileLocation(\"foo.cc\", 42));\n}\n\nTEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFile) {\n  EXPECT_EQ(\"unknown file:42\",\n            FormatCompilerIndependentFileLocation(nullptr, 42));\n}\n\nTEST(FormatCompilerIndependentFileLocationTest, FormatsUknownLine) {\n  EXPECT_EQ(\"foo.cc\", FormatCompilerIndependentFileLocation(\"foo.cc\", -1));\n}\n\nTEST(FormatCompilerIndependentFileLocationTest, FormatsUknownFileAndLine) {\n  EXPECT_EQ(\"unknown file\", FormatCompilerIndependentFileLocation(nullptr, -1));\n}\n\n#if GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA || \\\n    GTEST_OS_DRAGONFLY || GTEST_OS_FREEBSD || GTEST_OS_GNU_KFREEBSD ||    \\\n    GTEST_OS_NETBSD || GTEST_OS_OPENBSD || GTEST_OS_GNU_HURD\nvoid* ThreadFunc(void* data) {\n  internal::Mutex* mutex = static_cast<internal::Mutex*>(data);\n  mutex->Lock();\n  mutex->Unlock();\n  return nullptr;\n}\n\nTEST(GetThreadCountTest, ReturnsCorrectValue) {\n  size_t starting_count;\n  size_t thread_count_after_create;\n  size_t thread_count_after_join;\n\n  // We can't guarantee that no other thread was created or destroyed between\n  // any two calls to GetThreadCount(). We make multiple attempts, hoping that\n  // background noise is not constant and we would see the \"right\" values at\n  // some point.\n  for (int attempt = 0; attempt < 20; ++attempt) {\n    starting_count = GetThreadCount();\n    pthread_t thread_id;\n\n    internal::Mutex mutex;\n    {\n      internal::MutexLock lock(&mutex);\n      pthread_attr_t attr;\n      ASSERT_EQ(0, pthread_attr_init(&attr));\n      ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE));\n\n      const int status = pthread_create(&thread_id, &attr, &ThreadFunc, &mutex);\n      ASSERT_EQ(0, pthread_attr_destroy(&attr));\n      ASSERT_EQ(0, status);\n    }\n\n    thread_count_after_create = GetThreadCount();\n\n    void* dummy;\n    ASSERT_EQ(0, pthread_join(thread_id, &dummy));\n\n    // Join before we decide whether we need to retry the test. Retry if an\n    // arbitrary other thread was created or destroyed in the meantime.\n    if (thread_count_after_create != starting_count + 1) continue;\n\n    // The OS may not immediately report the updated thread count after\n    // joining a thread, causing flakiness in this test. To counter that, we\n    // wait for up to .5 seconds for the OS to report the correct value.\n    bool thread_count_matches = false;\n    for (int i = 0; i < 5; ++i) {\n      thread_count_after_join = GetThreadCount();\n      if (thread_count_after_join == starting_count) {\n        thread_count_matches = true;\n        break;\n      }\n\n      std::this_thread::sleep_for(std::chrono::milliseconds(100));\n    }\n\n    // Retry if an arbitrary other thread was created or destroyed.\n    if (!thread_count_matches) continue;\n\n    break;\n  }\n\n  EXPECT_EQ(thread_count_after_create, starting_count + 1);\n  EXPECT_EQ(thread_count_after_join, starting_count);\n}\n#else\nTEST(GetThreadCountTest, ReturnsZeroWhenUnableToCountThreads) {\n  EXPECT_EQ(0U, GetThreadCount());\n}\n#endif  // GTEST_OS_LINUX || GTEST_OS_MAC || GTEST_OS_QNX || GTEST_OS_FUCHSIA\n\nTEST(GtestCheckDeathTest, DiesWithCorrectOutputOnFailure) {\n  const bool a_false_condition = false;\n  const char regex[] =\n#ifdef _MSC_VER\n      \"googletest-port-test\\\\.cc\\\\(\\\\d+\\\\):\"\n#elif GTEST_USES_POSIX_RE\n      \"googletest-port-test\\\\.cc:[0-9]+\"\n#else\n      \"googletest-port-test\\\\.cc:\\\\d+\"\n#endif  // _MSC_VER\n      \".*a_false_condition.*Extra info.*\";\n\n  EXPECT_DEATH_IF_SUPPORTED(GTEST_CHECK_(a_false_condition) << \"Extra info\",\n                            regex);\n}\n\n#if GTEST_HAS_DEATH_TEST\n\nTEST(GtestCheckDeathTest, LivesSilentlyOnSuccess) {\n  EXPECT_EXIT(\n      {\n        GTEST_CHECK_(true) << \"Extra info\";\n        ::std::cerr << \"Success\\n\";\n        exit(0);\n      },\n      ::testing::ExitedWithCode(0), \"Success\");\n}\n\n#endif  // GTEST_HAS_DEATH_TEST\n\n// Verifies that Google Test choose regular expression engine appropriate to\n// the platform. The test will produce compiler errors in case of failure.\n// For simplicity, we only cover the most important platforms here.\nTEST(RegexEngineSelectionTest, SelectsCorrectRegexEngine) {\n#if GTEST_HAS_ABSL\n  EXPECT_TRUE(GTEST_USES_RE2);\n#elif GTEST_HAS_POSIX_RE\n  EXPECT_TRUE(GTEST_USES_POSIX_RE);\n#else\n  EXPECT_TRUE(GTEST_USES_SIMPLE_RE);\n#endif\n}\n\n#if GTEST_USES_POSIX_RE\n\ntemplate <typename Str>\nclass RETest : public ::testing::Test {};\n\n// Defines StringTypes as the list of all string types that class RE\n// supports.\ntypedef testing::Types< ::std::string, const char*> StringTypes;\n\nTYPED_TEST_SUITE(RETest, StringTypes);\n\n// Tests RE's implicit constructors.\nTYPED_TEST(RETest, ImplicitConstructorWorks) {\n  const RE empty(TypeParam(\"\"));\n  EXPECT_STREQ(\"\", empty.pattern());\n\n  const RE simple(TypeParam(\"hello\"));\n  EXPECT_STREQ(\"hello\", simple.pattern());\n\n  const RE normal(TypeParam(\".*(\\\\w+)\"));\n  EXPECT_STREQ(\".*(\\\\w+)\", normal.pattern());\n}\n\n// Tests that RE's constructors reject invalid regular expressions.\nTYPED_TEST(RETest, RejectsInvalidRegex) {\n  EXPECT_NONFATAL_FAILURE(\n      { const RE invalid(TypeParam(\"?\")); },\n      \"\\\"?\\\" is not a valid POSIX Extended regular expression.\");\n}\n\n// Tests RE::FullMatch().\nTYPED_TEST(RETest, FullMatchWorks) {\n  const RE empty(TypeParam(\"\"));\n  EXPECT_TRUE(RE::FullMatch(TypeParam(\"\"), empty));\n  EXPECT_FALSE(RE::FullMatch(TypeParam(\"a\"), empty));\n\n  const RE re(TypeParam(\"a.*z\"));\n  EXPECT_TRUE(RE::FullMatch(TypeParam(\"az\"), re));\n  EXPECT_TRUE(RE::FullMatch(TypeParam(\"axyz\"), re));\n  EXPECT_FALSE(RE::FullMatch(TypeParam(\"baz\"), re));\n  EXPECT_FALSE(RE::FullMatch(TypeParam(\"azy\"), re));\n}\n\n// Tests RE::PartialMatch().\nTYPED_TEST(RETest, PartialMatchWorks) {\n  const RE empty(TypeParam(\"\"));\n  EXPECT_TRUE(RE::PartialMatch(TypeParam(\"\"), empty));\n  EXPECT_TRUE(RE::PartialMatch(TypeParam(\"a\"), empty));\n\n  const RE re(TypeParam(\"a.*z\"));\n  EXPECT_TRUE(RE::PartialMatch(TypeParam(\"az\"), re));\n  EXPECT_TRUE(RE::PartialMatch(TypeParam(\"axyz\"), re));\n  EXPECT_TRUE(RE::PartialMatch(TypeParam(\"baz\"), re));\n  EXPECT_TRUE(RE::PartialMatch(TypeParam(\"azy\"), re));\n  EXPECT_FALSE(RE::PartialMatch(TypeParam(\"zza\"), re));\n}\n\n#elif GTEST_USES_SIMPLE_RE\n\nTEST(IsInSetTest, NulCharIsNotInAnySet) {\n  EXPECT_FALSE(IsInSet('\\0', \"\"));\n  EXPECT_FALSE(IsInSet('\\0', \"\\0\"));\n  EXPECT_FALSE(IsInSet('\\0', \"a\"));\n}\n\nTEST(IsInSetTest, WorksForNonNulChars) {\n  EXPECT_FALSE(IsInSet('a', \"Ab\"));\n  EXPECT_FALSE(IsInSet('c', \"\"));\n\n  EXPECT_TRUE(IsInSet('b', \"bcd\"));\n  EXPECT_TRUE(IsInSet('b', \"ab\"));\n}\n\nTEST(IsAsciiDigitTest, IsFalseForNonDigit) {\n  EXPECT_FALSE(IsAsciiDigit('\\0'));\n  EXPECT_FALSE(IsAsciiDigit(' '));\n  EXPECT_FALSE(IsAsciiDigit('+'));\n  EXPECT_FALSE(IsAsciiDigit('-'));\n  EXPECT_FALSE(IsAsciiDigit('.'));\n  EXPECT_FALSE(IsAsciiDigit('a'));\n}\n\nTEST(IsAsciiDigitTest, IsTrueForDigit) {\n  EXPECT_TRUE(IsAsciiDigit('0'));\n  EXPECT_TRUE(IsAsciiDigit('1'));\n  EXPECT_TRUE(IsAsciiDigit('5'));\n  EXPECT_TRUE(IsAsciiDigit('9'));\n}\n\nTEST(IsAsciiPunctTest, IsFalseForNonPunct) {\n  EXPECT_FALSE(IsAsciiPunct('\\0'));\n  EXPECT_FALSE(IsAsciiPunct(' '));\n  EXPECT_FALSE(IsAsciiPunct('\\n'));\n  EXPECT_FALSE(IsAsciiPunct('a'));\n  EXPECT_FALSE(IsAsciiPunct('0'));\n}\n\nTEST(IsAsciiPunctTest, IsTrueForPunct) {\n  for (const char* p = \"^-!\\\"#$%&'()*+,./:;<=>?@[\\\\]_`{|}~\"; *p; p++) {\n    EXPECT_PRED1(IsAsciiPunct, *p);\n  }\n}\n\nTEST(IsRepeatTest, IsFalseForNonRepeatChar) {\n  EXPECT_FALSE(IsRepeat('\\0'));\n  EXPECT_FALSE(IsRepeat(' '));\n  EXPECT_FALSE(IsRepeat('a'));\n  EXPECT_FALSE(IsRepeat('1'));\n  EXPECT_FALSE(IsRepeat('-'));\n}\n\nTEST(IsRepeatTest, IsTrueForRepeatChar) {\n  EXPECT_TRUE(IsRepeat('?'));\n  EXPECT_TRUE(IsRepeat('*'));\n  EXPECT_TRUE(IsRepeat('+'));\n}\n\nTEST(IsAsciiWhiteSpaceTest, IsFalseForNonWhiteSpace) {\n  EXPECT_FALSE(IsAsciiWhiteSpace('\\0'));\n  EXPECT_FALSE(IsAsciiWhiteSpace('a'));\n  EXPECT_FALSE(IsAsciiWhiteSpace('1'));\n  EXPECT_FALSE(IsAsciiWhiteSpace('+'));\n  EXPECT_FALSE(IsAsciiWhiteSpace('_'));\n}\n\nTEST(IsAsciiWhiteSpaceTest, IsTrueForWhiteSpace) {\n  EXPECT_TRUE(IsAsciiWhiteSpace(' '));\n  EXPECT_TRUE(IsAsciiWhiteSpace('\\n'));\n  EXPECT_TRUE(IsAsciiWhiteSpace('\\r'));\n  EXPECT_TRUE(IsAsciiWhiteSpace('\\t'));\n  EXPECT_TRUE(IsAsciiWhiteSpace('\\v'));\n  EXPECT_TRUE(IsAsciiWhiteSpace('\\f'));\n}\n\nTEST(IsAsciiWordCharTest, IsFalseForNonWordChar) {\n  EXPECT_FALSE(IsAsciiWordChar('\\0'));\n  EXPECT_FALSE(IsAsciiWordChar('+'));\n  EXPECT_FALSE(IsAsciiWordChar('.'));\n  EXPECT_FALSE(IsAsciiWordChar(' '));\n  EXPECT_FALSE(IsAsciiWordChar('\\n'));\n}\n\nTEST(IsAsciiWordCharTest, IsTrueForLetter) {\n  EXPECT_TRUE(IsAsciiWordChar('a'));\n  EXPECT_TRUE(IsAsciiWordChar('b'));\n  EXPECT_TRUE(IsAsciiWordChar('A'));\n  EXPECT_TRUE(IsAsciiWordChar('Z'));\n}\n\nTEST(IsAsciiWordCharTest, IsTrueForDigit) {\n  EXPECT_TRUE(IsAsciiWordChar('0'));\n  EXPECT_TRUE(IsAsciiWordChar('1'));\n  EXPECT_TRUE(IsAsciiWordChar('7'));\n  EXPECT_TRUE(IsAsciiWordChar('9'));\n}\n\nTEST(IsAsciiWordCharTest, IsTrueForUnderscore) {\n  EXPECT_TRUE(IsAsciiWordChar('_'));\n}\n\nTEST(IsValidEscapeTest, IsFalseForNonPrintable) {\n  EXPECT_FALSE(IsValidEscape('\\0'));\n  EXPECT_FALSE(IsValidEscape('\\007'));\n}\n\nTEST(IsValidEscapeTest, IsFalseForDigit) {\n  EXPECT_FALSE(IsValidEscape('0'));\n  EXPECT_FALSE(IsValidEscape('9'));\n}\n\nTEST(IsValidEscapeTest, IsFalseForWhiteSpace) {\n  EXPECT_FALSE(IsValidEscape(' '));\n  EXPECT_FALSE(IsValidEscape('\\n'));\n}\n\nTEST(IsValidEscapeTest, IsFalseForSomeLetter) {\n  EXPECT_FALSE(IsValidEscape('a'));\n  EXPECT_FALSE(IsValidEscape('Z'));\n}\n\nTEST(IsValidEscapeTest, IsTrueForPunct) {\n  EXPECT_TRUE(IsValidEscape('.'));\n  EXPECT_TRUE(IsValidEscape('-'));\n  EXPECT_TRUE(IsValidEscape('^'));\n  EXPECT_TRUE(IsValidEscape('$'));\n  EXPECT_TRUE(IsValidEscape('('));\n  EXPECT_TRUE(IsValidEscape(']'));\n  EXPECT_TRUE(IsValidEscape('{'));\n  EXPECT_TRUE(IsValidEscape('|'));\n}\n\nTEST(IsValidEscapeTest, IsTrueForSomeLetter) {\n  EXPECT_TRUE(IsValidEscape('d'));\n  EXPECT_TRUE(IsValidEscape('D'));\n  EXPECT_TRUE(IsValidEscape('s'));\n  EXPECT_TRUE(IsValidEscape('S'));\n  EXPECT_TRUE(IsValidEscape('w'));\n  EXPECT_TRUE(IsValidEscape('W'));\n}\n\nTEST(AtomMatchesCharTest, EscapedPunct) {\n  EXPECT_FALSE(AtomMatchesChar(true, '\\\\', '\\0'));\n  EXPECT_FALSE(AtomMatchesChar(true, '\\\\', ' '));\n  EXPECT_FALSE(AtomMatchesChar(true, '_', '.'));\n  EXPECT_FALSE(AtomMatchesChar(true, '.', 'a'));\n\n  EXPECT_TRUE(AtomMatchesChar(true, '\\\\', '\\\\'));\n  EXPECT_TRUE(AtomMatchesChar(true, '_', '_'));\n  EXPECT_TRUE(AtomMatchesChar(true, '+', '+'));\n  EXPECT_TRUE(AtomMatchesChar(true, '.', '.'));\n}\n\nTEST(AtomMatchesCharTest, Escaped_d) {\n  EXPECT_FALSE(AtomMatchesChar(true, 'd', '\\0'));\n  EXPECT_FALSE(AtomMatchesChar(true, 'd', 'a'));\n  EXPECT_FALSE(AtomMatchesChar(true, 'd', '.'));\n\n  EXPECT_TRUE(AtomMatchesChar(true, 'd', '0'));\n  EXPECT_TRUE(AtomMatchesChar(true, 'd', '9'));\n}\n\nTEST(AtomMatchesCharTest, Escaped_D) {\n  EXPECT_FALSE(AtomMatchesChar(true, 'D', '0'));\n  EXPECT_FALSE(AtomMatchesChar(true, 'D', '9'));\n\n  EXPECT_TRUE(AtomMatchesChar(true, 'D', '\\0'));\n  EXPECT_TRUE(AtomMatchesChar(true, 'D', 'a'));\n  EXPECT_TRUE(AtomMatchesChar(true, 'D', '-'));\n}\n\nTEST(AtomMatchesCharTest, Escaped_s) {\n  EXPECT_FALSE(AtomMatchesChar(true, 's', '\\0'));\n  EXPECT_FALSE(AtomMatchesChar(true, 's', 'a'));\n  EXPECT_FALSE(AtomMatchesChar(true, 's', '.'));\n  EXPECT_FALSE(AtomMatchesChar(true, 's', '9'));\n\n  EXPECT_TRUE(AtomMatchesChar(true, 's', ' '));\n  EXPECT_TRUE(AtomMatchesChar(true, 's', '\\n'));\n  EXPECT_TRUE(AtomMatchesChar(true, 's', '\\t'));\n}\n\nTEST(AtomMatchesCharTest, Escaped_S) {\n  EXPECT_FALSE(AtomMatchesChar(true, 'S', ' '));\n  EXPECT_FALSE(AtomMatchesChar(true, 'S', '\\r'));\n\n  EXPECT_TRUE(AtomMatchesChar(true, 'S', '\\0'));\n  EXPECT_TRUE(AtomMatchesChar(true, 'S', 'a'));\n  EXPECT_TRUE(AtomMatchesChar(true, 'S', '9'));\n}\n\nTEST(AtomMatchesCharTest, Escaped_w) {\n  EXPECT_FALSE(AtomMatchesChar(true, 'w', '\\0'));\n  EXPECT_FALSE(AtomMatchesChar(true, 'w', '+'));\n  EXPECT_FALSE(AtomMatchesChar(true, 'w', ' '));\n  EXPECT_FALSE(AtomMatchesChar(true, 'w', '\\n'));\n\n  EXPECT_TRUE(AtomMatchesChar(true, 'w', '0'));\n  EXPECT_TRUE(AtomMatchesChar(true, 'w', 'b'));\n  EXPECT_TRUE(AtomMatchesChar(true, 'w', 'C'));\n  EXPECT_TRUE(AtomMatchesChar(true, 'w', '_'));\n}\n\nTEST(AtomMatchesCharTest, Escaped_W) {\n  EXPECT_FALSE(AtomMatchesChar(true, 'W', 'A'));\n  EXPECT_FALSE(AtomMatchesChar(true, 'W', 'b'));\n  EXPECT_FALSE(AtomMatchesChar(true, 'W', '9'));\n  EXPECT_FALSE(AtomMatchesChar(true, 'W', '_'));\n\n  EXPECT_TRUE(AtomMatchesChar(true, 'W', '\\0'));\n  EXPECT_TRUE(AtomMatchesChar(true, 'W', '*'));\n  EXPECT_TRUE(AtomMatchesChar(true, 'W', '\\n'));\n}\n\nTEST(AtomMatchesCharTest, EscapedWhiteSpace) {\n  EXPECT_FALSE(AtomMatchesChar(true, 'f', '\\0'));\n  EXPECT_FALSE(AtomMatchesChar(true, 'f', '\\n'));\n  EXPECT_FALSE(AtomMatchesChar(true, 'n', '\\0'));\n  EXPECT_FALSE(AtomMatchesChar(true, 'n', '\\r'));\n  EXPECT_FALSE(AtomMatchesChar(true, 'r', '\\0'));\n  EXPECT_FALSE(AtomMatchesChar(true, 'r', 'a'));\n  EXPECT_FALSE(AtomMatchesChar(true, 't', '\\0'));\n  EXPECT_FALSE(AtomMatchesChar(true, 't', 't'));\n  EXPECT_FALSE(AtomMatchesChar(true, 'v', '\\0'));\n  EXPECT_FALSE(AtomMatchesChar(true, 'v', '\\f'));\n\n  EXPECT_TRUE(AtomMatchesChar(true, 'f', '\\f'));\n  EXPECT_TRUE(AtomMatchesChar(true, 'n', '\\n'));\n  EXPECT_TRUE(AtomMatchesChar(true, 'r', '\\r'));\n  EXPECT_TRUE(AtomMatchesChar(true, 't', '\\t'));\n  EXPECT_TRUE(AtomMatchesChar(true, 'v', '\\v'));\n}\n\nTEST(AtomMatchesCharTest, UnescapedDot) {\n  EXPECT_FALSE(AtomMatchesChar(false, '.', '\\n'));\n\n  EXPECT_TRUE(AtomMatchesChar(false, '.', '\\0'));\n  EXPECT_TRUE(AtomMatchesChar(false, '.', '.'));\n  EXPECT_TRUE(AtomMatchesChar(false, '.', 'a'));\n  EXPECT_TRUE(AtomMatchesChar(false, '.', ' '));\n}\n\nTEST(AtomMatchesCharTest, UnescapedChar) {\n  EXPECT_FALSE(AtomMatchesChar(false, 'a', '\\0'));\n  EXPECT_FALSE(AtomMatchesChar(false, 'a', 'b'));\n  EXPECT_FALSE(AtomMatchesChar(false, '$', 'a'));\n\n  EXPECT_TRUE(AtomMatchesChar(false, '$', '$'));\n  EXPECT_TRUE(AtomMatchesChar(false, '5', '5'));\n  EXPECT_TRUE(AtomMatchesChar(false, 'Z', 'Z'));\n}\n\nTEST(ValidateRegexTest, GeneratesFailureAndReturnsFalseForInvalid) {\n  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(NULL)),\n                          \"NULL is not a valid simple regular expression\");\n  EXPECT_NONFATAL_FAILURE(\n      ASSERT_FALSE(ValidateRegex(\"a\\\\\")),\n      \"Syntax error at index 1 in simple regular expression \\\"a\\\\\\\": \");\n  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(\"a\\\\\")),\n                          \"'\\\\' cannot appear at the end\");\n  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(\"\\\\n\\\\\")),\n                          \"'\\\\' cannot appear at the end\");\n  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(\"\\\\s\\\\hb\")),\n                          \"invalid escape sequence \\\"\\\\h\\\"\");\n  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(\"^^\")),\n                          \"'^' can only appear at the beginning\");\n  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(\".*^b\")),\n                          \"'^' can only appear at the beginning\");\n  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(\"$$\")),\n                          \"'$' can only appear at the end\");\n  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(\"^$a\")),\n                          \"'$' can only appear at the end\");\n  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(\"a(b\")),\n                          \"'(' is unsupported\");\n  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(\"ab)\")),\n                          \"')' is unsupported\");\n  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(\"[ab\")),\n                          \"'[' is unsupported\");\n  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(\"a{2\")),\n                          \"'{' is unsupported\");\n  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(\"?\")),\n                          \"'?' can only follow a repeatable token\");\n  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(\"^*\")),\n                          \"'*' can only follow a repeatable token\");\n  EXPECT_NONFATAL_FAILURE(ASSERT_FALSE(ValidateRegex(\"5*+\")),\n                          \"'+' can only follow a repeatable token\");\n}\n\nTEST(ValidateRegexTest, ReturnsTrueForValid) {\n  EXPECT_TRUE(ValidateRegex(\"\"));\n  EXPECT_TRUE(ValidateRegex(\"a\"));\n  EXPECT_TRUE(ValidateRegex(\".*\"));\n  EXPECT_TRUE(ValidateRegex(\"^a_+\"));\n  EXPECT_TRUE(ValidateRegex(\"^a\\\\t\\\\&?\"));\n  EXPECT_TRUE(ValidateRegex(\"09*$\"));\n  EXPECT_TRUE(ValidateRegex(\"^Z$\"));\n  EXPECT_TRUE(ValidateRegex(\"a\\\\^Z\\\\$\\\\(\\\\)\\\\|\\\\[\\\\]\\\\{\\\\}\"));\n}\n\nTEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrOne) {\n  EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', \"a\", \"ba\"));\n  // Repeating more than once.\n  EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, 'a', '?', \"b\", \"aab\"));\n\n  // Repeating zero times.\n  EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', \"b\", \"ba\"));\n  // Repeating once.\n  EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, 'a', '?', \"b\", \"ab\"));\n  EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '#', '?', \".\", \"##\"));\n}\n\nTEST(MatchRepetitionAndRegexAtHeadTest, WorksForZeroOrMany) {\n  EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '*', \"a$\", \"baab\"));\n\n  // Repeating zero times.\n  EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', \"b\", \"bc\"));\n  // Repeating once.\n  EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '*', \"b\", \"abc\"));\n  // Repeating more than once.\n  EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '*', \"-\", \"ab_1-g\"));\n}\n\nTEST(MatchRepetitionAndRegexAtHeadTest, WorksForOneOrMany) {\n  EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', \"a$\", \"baab\"));\n  // Repeating zero times.\n  EXPECT_FALSE(MatchRepetitionAndRegexAtHead(false, '.', '+', \"b\", \"bc\"));\n\n  // Repeating once.\n  EXPECT_TRUE(MatchRepetitionAndRegexAtHead(false, '.', '+', \"b\", \"abc\"));\n  // Repeating more than once.\n  EXPECT_TRUE(MatchRepetitionAndRegexAtHead(true, 'w', '+', \"-\", \"ab_1-g\"));\n}\n\nTEST(MatchRegexAtHeadTest, ReturnsTrueForEmptyRegex) {\n  EXPECT_TRUE(MatchRegexAtHead(\"\", \"\"));\n  EXPECT_TRUE(MatchRegexAtHead(\"\", \"ab\"));\n}\n\nTEST(MatchRegexAtHeadTest, WorksWhenDollarIsInRegex) {\n  EXPECT_FALSE(MatchRegexAtHead(\"$\", \"a\"));\n\n  EXPECT_TRUE(MatchRegexAtHead(\"$\", \"\"));\n  EXPECT_TRUE(MatchRegexAtHead(\"a$\", \"a\"));\n}\n\nTEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithEscapeSequence) {\n  EXPECT_FALSE(MatchRegexAtHead(\"\\\\w\", \"+\"));\n  EXPECT_FALSE(MatchRegexAtHead(\"\\\\W\", \"ab\"));\n\n  EXPECT_TRUE(MatchRegexAtHead(\"\\\\sa\", \"\\nab\"));\n  EXPECT_TRUE(MatchRegexAtHead(\"\\\\d\", \"1a\"));\n}\n\nTEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetition) {\n  EXPECT_FALSE(MatchRegexAtHead(\".+a\", \"abc\"));\n  EXPECT_FALSE(MatchRegexAtHead(\"a?b\", \"aab\"));\n\n  EXPECT_TRUE(MatchRegexAtHead(\".*a\", \"bc12-ab\"));\n  EXPECT_TRUE(MatchRegexAtHead(\"a?b\", \"b\"));\n  EXPECT_TRUE(MatchRegexAtHead(\"a?b\", \"ab\"));\n}\n\nTEST(MatchRegexAtHeadTest, WorksWhenRegexStartsWithRepetionOfEscapeSequence) {\n  EXPECT_FALSE(MatchRegexAtHead(\"\\\\.+a\", \"abc\"));\n  EXPECT_FALSE(MatchRegexAtHead(\"\\\\s?b\", \"  b\"));\n\n  EXPECT_TRUE(MatchRegexAtHead(\"\\\\(*a\", \"((((ab\"));\n  EXPECT_TRUE(MatchRegexAtHead(\"\\\\^?b\", \"^b\"));\n  EXPECT_TRUE(MatchRegexAtHead(\"\\\\\\\\?b\", \"b\"));\n  EXPECT_TRUE(MatchRegexAtHead(\"\\\\\\\\?b\", \"\\\\b\"));\n}\n\nTEST(MatchRegexAtHeadTest, MatchesSequentially) {\n  EXPECT_FALSE(MatchRegexAtHead(\"ab.*c\", \"acabc\"));\n\n  EXPECT_TRUE(MatchRegexAtHead(\"ab.*c\", \"ab-fsc\"));\n}\n\nTEST(MatchRegexAnywhereTest, ReturnsFalseWhenStringIsNull) {\n  EXPECT_FALSE(MatchRegexAnywhere(\"\", NULL));\n}\n\nTEST(MatchRegexAnywhereTest, WorksWhenRegexStartsWithCaret) {\n  EXPECT_FALSE(MatchRegexAnywhere(\"^a\", \"ba\"));\n  EXPECT_FALSE(MatchRegexAnywhere(\"^$\", \"a\"));\n\n  EXPECT_TRUE(MatchRegexAnywhere(\"^a\", \"ab\"));\n  EXPECT_TRUE(MatchRegexAnywhere(\"^\", \"ab\"));\n  EXPECT_TRUE(MatchRegexAnywhere(\"^$\", \"\"));\n}\n\nTEST(MatchRegexAnywhereTest, ReturnsFalseWhenNoMatch) {\n  EXPECT_FALSE(MatchRegexAnywhere(\"a\", \"bcde123\"));\n  EXPECT_FALSE(MatchRegexAnywhere(\"a.+a\", \"--aa88888888\"));\n}\n\nTEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingPrefix) {\n  EXPECT_TRUE(MatchRegexAnywhere(\"\\\\w+\", \"ab1_ - 5\"));\n  EXPECT_TRUE(MatchRegexAnywhere(\".*=\", \"=\"));\n  EXPECT_TRUE(MatchRegexAnywhere(\"x.*ab?.*bc\", \"xaaabc\"));\n}\n\nTEST(MatchRegexAnywhereTest, ReturnsTrueWhenMatchingNonPrefix) {\n  EXPECT_TRUE(MatchRegexAnywhere(\"\\\\w+\", \"$$$ ab1_ - 5\"));\n  EXPECT_TRUE(MatchRegexAnywhere(\"\\\\.+=\", \"=  ...=\"));\n}\n\n// Tests RE's implicit constructors.\nTEST(RETest, ImplicitConstructorWorks) {\n  const RE empty(\"\");\n  EXPECT_STREQ(\"\", empty.pattern());\n\n  const RE simple(\"hello\");\n  EXPECT_STREQ(\"hello\", simple.pattern());\n}\n\n// Tests that RE's constructors reject invalid regular expressions.\nTEST(RETest, RejectsInvalidRegex) {\n  EXPECT_NONFATAL_FAILURE({ const RE normal(NULL); },\n                          \"NULL is not a valid simple regular expression\");\n\n  EXPECT_NONFATAL_FAILURE({ const RE normal(\".*(\\\\w+\"); },\n                          \"'(' is unsupported\");\n\n  EXPECT_NONFATAL_FAILURE({ const RE invalid(\"^?\"); },\n                          \"'?' can only follow a repeatable token\");\n}\n\n// Tests RE::FullMatch().\nTEST(RETest, FullMatchWorks) {\n  const RE empty(\"\");\n  EXPECT_TRUE(RE::FullMatch(\"\", empty));\n  EXPECT_FALSE(RE::FullMatch(\"a\", empty));\n\n  const RE re1(\"a\");\n  EXPECT_TRUE(RE::FullMatch(\"a\", re1));\n\n  const RE re(\"a.*z\");\n  EXPECT_TRUE(RE::FullMatch(\"az\", re));\n  EXPECT_TRUE(RE::FullMatch(\"axyz\", re));\n  EXPECT_FALSE(RE::FullMatch(\"baz\", re));\n  EXPECT_FALSE(RE::FullMatch(\"azy\", re));\n}\n\n// Tests RE::PartialMatch().\nTEST(RETest, PartialMatchWorks) {\n  const RE empty(\"\");\n  EXPECT_TRUE(RE::PartialMatch(\"\", empty));\n  EXPECT_TRUE(RE::PartialMatch(\"a\", empty));\n\n  const RE re(\"a.*z\");\n  EXPECT_TRUE(RE::PartialMatch(\"az\", re));\n  EXPECT_TRUE(RE::PartialMatch(\"axyz\", re));\n  EXPECT_TRUE(RE::PartialMatch(\"baz\", re));\n  EXPECT_TRUE(RE::PartialMatch(\"azy\", re));\n  EXPECT_FALSE(RE::PartialMatch(\"zza\", re));\n}\n\n#endif  // GTEST_USES_POSIX_RE\n\n#if !GTEST_OS_WINDOWS_MOBILE\n\nTEST(CaptureTest, CapturesStdout) {\n  CaptureStdout();\n  fprintf(stdout, \"abc\");\n  EXPECT_STREQ(\"abc\", GetCapturedStdout().c_str());\n\n  CaptureStdout();\n  fprintf(stdout, \"def%cghi\", '\\0');\n  EXPECT_EQ(::std::string(\"def\\0ghi\", 7), ::std::string(GetCapturedStdout()));\n}\n\nTEST(CaptureTest, CapturesStderr) {\n  CaptureStderr();\n  fprintf(stderr, \"jkl\");\n  EXPECT_STREQ(\"jkl\", GetCapturedStderr().c_str());\n\n  CaptureStderr();\n  fprintf(stderr, \"jkl%cmno\", '\\0');\n  EXPECT_EQ(::std::string(\"jkl\\0mno\", 7), ::std::string(GetCapturedStderr()));\n}\n\n// Tests that stdout and stderr capture don't interfere with each other.\nTEST(CaptureTest, CapturesStdoutAndStderr) {\n  CaptureStdout();\n  CaptureStderr();\n  fprintf(stdout, \"pqr\");\n  fprintf(stderr, \"stu\");\n  EXPECT_STREQ(\"pqr\", GetCapturedStdout().c_str());\n  EXPECT_STREQ(\"stu\", GetCapturedStderr().c_str());\n}\n\nTEST(CaptureDeathTest, CannotReenterStdoutCapture) {\n  CaptureStdout();\n  EXPECT_DEATH_IF_SUPPORTED(CaptureStdout(),\n                            \"Only one stdout capturer can exist at a time\");\n  GetCapturedStdout();\n\n  // We cannot test stderr capturing using death tests as they use it\n  // themselves.\n}\n\n#endif  // !GTEST_OS_WINDOWS_MOBILE\n\nTEST(ThreadLocalTest, DefaultConstructorInitializesToDefaultValues) {\n  ThreadLocal<int> t1;\n  EXPECT_EQ(0, t1.get());\n\n  ThreadLocal<void*> t2;\n  EXPECT_TRUE(t2.get() == nullptr);\n}\n\nTEST(ThreadLocalTest, SingleParamConstructorInitializesToParam) {\n  ThreadLocal<int> t1(123);\n  EXPECT_EQ(123, t1.get());\n\n  int i = 0;\n  ThreadLocal<int*> t2(&i);\n  EXPECT_EQ(&i, t2.get());\n}\n\nclass NoDefaultContructor {\n public:\n  explicit NoDefaultContructor(const char*) {}\n  NoDefaultContructor(const NoDefaultContructor&) {}\n};\n\nTEST(ThreadLocalTest, ValueDefaultContructorIsNotRequiredForParamVersion) {\n  ThreadLocal<NoDefaultContructor> bar(NoDefaultContructor(\"foo\"));\n  bar.pointer();\n}\n\nTEST(ThreadLocalTest, GetAndPointerReturnSameValue) {\n  ThreadLocal<std::string> thread_local_string;\n\n  EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));\n\n  // Verifies the condition still holds after calling set.\n  thread_local_string.set(\"foo\");\n  EXPECT_EQ(thread_local_string.pointer(), &(thread_local_string.get()));\n}\n\nTEST(ThreadLocalTest, PointerAndConstPointerReturnSameValue) {\n  ThreadLocal<std::string> thread_local_string;\n  const ThreadLocal<std::string>& const_thread_local_string =\n      thread_local_string;\n\n  EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());\n\n  thread_local_string.set(\"foo\");\n  EXPECT_EQ(thread_local_string.pointer(), const_thread_local_string.pointer());\n}\n\n#if GTEST_IS_THREADSAFE\n\nvoid AddTwo(int* param) { *param += 2; }\n\nTEST(ThreadWithParamTest, ConstructorExecutesThreadFunc) {\n  int i = 40;\n  ThreadWithParam<int*> thread(&AddTwo, &i, nullptr);\n  thread.Join();\n  EXPECT_EQ(42, i);\n}\n\nTEST(MutexDeathTest, AssertHeldShouldAssertWhenNotLocked) {\n  // AssertHeld() is flaky only in the presence of multiple threads accessing\n  // the lock. In this case, the test is robust.\n  EXPECT_DEATH_IF_SUPPORTED(\n      {\n        Mutex m;\n        { MutexLock lock(&m); }\n        m.AssertHeld();\n      },\n      \"thread .*hold\");\n}\n\nTEST(MutexTest, AssertHeldShouldNotAssertWhenLocked) {\n  Mutex m;\n  MutexLock lock(&m);\n  m.AssertHeld();\n}\n\nclass AtomicCounterWithMutex {\n public:\n  explicit AtomicCounterWithMutex(Mutex* mutex)\n      : value_(0), mutex_(mutex), random_(42) {}\n\n  void Increment() {\n    MutexLock lock(mutex_);\n    int temp = value_;\n    {\n      // We need to put up a memory barrier to prevent reads and writes to\n      // value_ rearranged with the call to sleep_for when observed\n      // from other threads.\n#if GTEST_HAS_PTHREAD\n      // On POSIX, locking a mutex puts up a memory barrier.  We cannot use\n      // Mutex and MutexLock here or rely on their memory barrier\n      // functionality as we are testing them here.\n      pthread_mutex_t memory_barrier_mutex;\n      GTEST_CHECK_POSIX_SUCCESS_(\n          pthread_mutex_init(&memory_barrier_mutex, nullptr));\n      GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_lock(&memory_barrier_mutex));\n\n      std::this_thread::sleep_for(\n          std::chrono::milliseconds(random_.Generate(30)));\n\n      GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_unlock(&memory_barrier_mutex));\n      GTEST_CHECK_POSIX_SUCCESS_(pthread_mutex_destroy(&memory_barrier_mutex));\n#elif GTEST_OS_WINDOWS\n      // On Windows, performing an interlocked access puts up a memory barrier.\n      volatile LONG dummy = 0;\n      ::InterlockedIncrement(&dummy);\n      std::this_thread::sleep_for(\n          std::chrono::milliseconds(random_.Generate(30)));\n      ::InterlockedIncrement(&dummy);\n#else\n#error \"Memory barrier not implemented on this platform.\"\n#endif  // GTEST_HAS_PTHREAD\n    }\n    value_ = temp + 1;\n  }\n  int value() const { return value_; }\n\n private:\n  volatile int value_;\n  Mutex* const mutex_;  // Protects value_.\n  Random random_;\n};\n\nvoid CountingThreadFunc(pair<AtomicCounterWithMutex*, int> param) {\n  for (int i = 0; i < param.second; ++i) param.first->Increment();\n}\n\n// Tests that the mutex only lets one thread at a time to lock it.\nTEST(MutexTest, OnlyOneThreadCanLockAtATime) {\n  Mutex mutex;\n  AtomicCounterWithMutex locked_counter(&mutex);\n\n  typedef ThreadWithParam<pair<AtomicCounterWithMutex*, int> > ThreadType;\n  const int kCycleCount = 20;\n  const int kThreadCount = 7;\n  std::unique_ptr<ThreadType> counting_threads[kThreadCount];\n  Notification threads_can_start;\n  // Creates and runs kThreadCount threads that increment locked_counter\n  // kCycleCount times each.\n  for (int i = 0; i < kThreadCount; ++i) {\n    counting_threads[i].reset(new ThreadType(\n        &CountingThreadFunc, make_pair(&locked_counter, kCycleCount),\n        &threads_can_start));\n  }\n  threads_can_start.Notify();\n  for (int i = 0; i < kThreadCount; ++i) counting_threads[i]->Join();\n\n  // If the mutex lets more than one thread to increment the counter at a\n  // time, they are likely to encounter a race condition and have some\n  // increments overwritten, resulting in the lower then expected counter\n  // value.\n  EXPECT_EQ(kCycleCount * kThreadCount, locked_counter.value());\n}\n\ntemplate <typename T>\nvoid RunFromThread(void(func)(T), T param) {\n  ThreadWithParam<T> thread(func, param, nullptr);\n  thread.Join();\n}\n\nvoid RetrieveThreadLocalValue(\n    pair<ThreadLocal<std::string>*, std::string*> param) {\n  *param.second = param.first->get();\n}\n\nTEST(ThreadLocalTest, ParameterizedConstructorSetsDefault) {\n  ThreadLocal<std::string> thread_local_string(\"foo\");\n  EXPECT_STREQ(\"foo\", thread_local_string.get().c_str());\n\n  thread_local_string.set(\"bar\");\n  EXPECT_STREQ(\"bar\", thread_local_string.get().c_str());\n\n  std::string result;\n  RunFromThread(&RetrieveThreadLocalValue,\n                make_pair(&thread_local_string, &result));\n  EXPECT_STREQ(\"foo\", result.c_str());\n}\n\n// Keeps track of whether of destructors being called on instances of\n// DestructorTracker.  On Windows, waits for the destructor call reports.\nclass DestructorCall {\n public:\n  DestructorCall() {\n    invoked_ = false;\n#if GTEST_OS_WINDOWS\n    wait_event_.Reset(::CreateEvent(NULL, TRUE, FALSE, NULL));\n    GTEST_CHECK_(wait_event_.Get() != NULL);\n#endif\n  }\n\n  bool CheckDestroyed() const {\n#if GTEST_OS_WINDOWS\n    if (::WaitForSingleObject(wait_event_.Get(), 1000) != WAIT_OBJECT_0)\n      return false;\n#endif\n    return invoked_;\n  }\n\n  void ReportDestroyed() {\n    invoked_ = true;\n#if GTEST_OS_WINDOWS\n    ::SetEvent(wait_event_.Get());\n#endif\n  }\n\n  static std::vector<DestructorCall*>& List() { return *list_; }\n\n  static void ResetList() {\n    for (size_t i = 0; i < list_->size(); ++i) {\n      delete list_->at(i);\n    }\n    list_->clear();\n  }\n\n private:\n  bool invoked_;\n#if GTEST_OS_WINDOWS\n  AutoHandle wait_event_;\n#endif\n  static std::vector<DestructorCall*>* const list_;\n\n  DestructorCall(const DestructorCall&) = delete;\n  DestructorCall& operator=(const DestructorCall&) = delete;\n};\n\nstd::vector<DestructorCall*>* const DestructorCall::list_ =\n    new std::vector<DestructorCall*>;\n\n// DestructorTracker keeps track of whether its instances have been\n// destroyed.\nclass DestructorTracker {\n public:\n  DestructorTracker() : index_(GetNewIndex()) {}\n  DestructorTracker(const DestructorTracker& /* rhs */)\n      : index_(GetNewIndex()) {}\n  ~DestructorTracker() {\n    // We never access DestructorCall::List() concurrently, so we don't need\n    // to protect this access with a mutex.\n    DestructorCall::List()[index_]->ReportDestroyed();\n  }\n\n private:\n  static size_t GetNewIndex() {\n    DestructorCall::List().push_back(new DestructorCall);\n    return DestructorCall::List().size() - 1;\n  }\n  const size_t index_;\n};\n\ntypedef ThreadLocal<DestructorTracker>* ThreadParam;\n\nvoid CallThreadLocalGet(ThreadParam thread_local_param) {\n  thread_local_param->get();\n}\n\n// Tests that when a ThreadLocal object dies in a thread, it destroys\n// the managed object for that thread.\nTEST(ThreadLocalTest, DestroysManagedObjectForOwnThreadWhenDying) {\n  DestructorCall::ResetList();\n\n  {\n    ThreadLocal<DestructorTracker> thread_local_tracker;\n    ASSERT_EQ(0U, DestructorCall::List().size());\n\n    // This creates another DestructorTracker object for the main thread.\n    thread_local_tracker.get();\n    ASSERT_EQ(1U, DestructorCall::List().size());\n    ASSERT_FALSE(DestructorCall::List()[0]->CheckDestroyed());\n  }\n\n  // Now thread_local_tracker has died.\n  ASSERT_EQ(1U, DestructorCall::List().size());\n  EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());\n\n  DestructorCall::ResetList();\n}\n\n// Tests that when a thread exits, the thread-local object for that\n// thread is destroyed.\nTEST(ThreadLocalTest, DestroysManagedObjectAtThreadExit) {\n  DestructorCall::ResetList();\n\n  {\n    ThreadLocal<DestructorTracker> thread_local_tracker;\n    ASSERT_EQ(0U, DestructorCall::List().size());\n\n    // This creates another DestructorTracker object in the new thread.\n    ThreadWithParam<ThreadParam> thread(&CallThreadLocalGet,\n                                        &thread_local_tracker, nullptr);\n    thread.Join();\n\n    // The thread has exited, and we should have a DestroyedTracker\n    // instance created for it. But it may not have been destroyed yet.\n    ASSERT_EQ(1U, DestructorCall::List().size());\n  }\n\n  // The thread has exited and thread_local_tracker has died.\n  ASSERT_EQ(1U, DestructorCall::List().size());\n  EXPECT_TRUE(DestructorCall::List()[0]->CheckDestroyed());\n\n  DestructorCall::ResetList();\n}\n\nTEST(ThreadLocalTest, ThreadLocalMutationsAffectOnlyCurrentThread) {\n  ThreadLocal<std::string> thread_local_string;\n  thread_local_string.set(\"Foo\");\n  EXPECT_STREQ(\"Foo\", thread_local_string.get().c_str());\n\n  std::string result;\n  RunFromThread(&RetrieveThreadLocalValue,\n                make_pair(&thread_local_string, &result));\n  EXPECT_TRUE(result.empty());\n}\n\n#endif  // GTEST_IS_THREADSAFE\n\n#if GTEST_OS_WINDOWS\nTEST(WindowsTypesTest, HANDLEIsVoidStar) {\n  StaticAssertTypeEq<HANDLE, void*>();\n}\n\n#if GTEST_OS_WINDOWS_MINGW && !defined(__MINGW64_VERSION_MAJOR)\nTEST(WindowsTypesTest, _CRITICAL_SECTIONIs_CRITICAL_SECTION) {\n  StaticAssertTypeEq<CRITICAL_SECTION, _CRITICAL_SECTION>();\n}\n#else\nTEST(WindowsTypesTest, CRITICAL_SECTIONIs_RTL_CRITICAL_SECTION) {\n  StaticAssertTypeEq<CRITICAL_SECTION, _RTL_CRITICAL_SECTION>();\n}\n#endif\n\n#endif  // GTEST_OS_WINDOWS\n\n}  // namespace internal\n}  // namespace testing\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-printers-test.cc",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Google Test - The Google C++ Testing and Mocking Framework\n//\n// This file tests the universal value printer.\n\n#include <algorithm>\n#include <cctype>\n#include <cstdint>\n#include <cstring>\n#include <deque>\n#include <forward_list>\n#include <limits>\n#include <list>\n#include <map>\n#include <memory>\n#include <set>\n#include <sstream>\n#include <string>\n#include <unordered_map>\n#include <unordered_set>\n#include <utility>\n#include <vector>\n\n#include \"gtest/gtest-printers.h\"\n#include \"gtest/gtest.h\"\n\n// Some user-defined types for testing the universal value printer.\n\n// An anonymous enum type.\nenum AnonymousEnum { kAE1 = -1, kAE2 = 1 };\n\n// An enum without a user-defined printer.\nenum EnumWithoutPrinter { kEWP1 = -2, kEWP2 = 42 };\n\n// An enum with a << operator.\nenum EnumWithStreaming { kEWS1 = 10 };\n\nstd::ostream& operator<<(std::ostream& os, EnumWithStreaming e) {\n  return os << (e == kEWS1 ? \"kEWS1\" : \"invalid\");\n}\n\n// An enum with a PrintTo() function.\nenum EnumWithPrintTo { kEWPT1 = 1 };\n\nvoid PrintTo(EnumWithPrintTo e, std::ostream* os) {\n  *os << (e == kEWPT1 ? \"kEWPT1\" : \"invalid\");\n}\n\n// A class implicitly convertible to BiggestInt.\nclass BiggestIntConvertible {\n public:\n  operator ::testing::internal::BiggestInt() const { return 42; }\n};\n\n// A parent class with two child classes. The parent and one of the kids have\n// stream operators.\nclass ParentClass {};\nclass ChildClassWithStreamOperator : public ParentClass {};\nclass ChildClassWithoutStreamOperator : public ParentClass {};\nstatic void operator<<(std::ostream& os, const ParentClass&) {\n  os << \"ParentClass\";\n}\nstatic void operator<<(std::ostream& os, const ChildClassWithStreamOperator&) {\n  os << \"ChildClassWithStreamOperator\";\n}\n\n// A user-defined unprintable class template in the global namespace.\ntemplate <typename T>\nclass UnprintableTemplateInGlobal {\n public:\n  UnprintableTemplateInGlobal() : value_() {}\n\n private:\n  T value_;\n};\n\n// A user-defined streamable type in the global namespace.\nclass StreamableInGlobal {\n public:\n  virtual ~StreamableInGlobal() {}\n};\n\ninline void operator<<(::std::ostream& os, const StreamableInGlobal& /* x */) {\n  os << \"StreamableInGlobal\";\n}\n\nvoid operator<<(::std::ostream& os, const StreamableInGlobal* /* x */) {\n  os << \"StreamableInGlobal*\";\n}\n\nnamespace foo {\n\n// A user-defined unprintable type in a user namespace.\nclass UnprintableInFoo {\n public:\n  UnprintableInFoo() : z_(0) { memcpy(xy_, \"\\xEF\\x12\\x0\\x0\\x34\\xAB\\x0\\x0\", 8); }\n  double z() const { return z_; }\n\n private:\n  char xy_[8];\n  double z_;\n};\n\n// A user-defined printable type in a user-chosen namespace.\nstruct PrintableViaPrintTo {\n  PrintableViaPrintTo() : value() {}\n  int value;\n};\n\nvoid PrintTo(const PrintableViaPrintTo& x, ::std::ostream* os) {\n  *os << \"PrintableViaPrintTo: \" << x.value;\n}\n\n// A type with a user-defined << for printing its pointer.\nstruct PointerPrintable {};\n\n::std::ostream& operator<<(::std::ostream& os,\n                           const PointerPrintable* /* x */) {\n  return os << \"PointerPrintable*\";\n}\n\n// A user-defined printable class template in a user-chosen namespace.\ntemplate <typename T>\nclass PrintableViaPrintToTemplate {\n public:\n  explicit PrintableViaPrintToTemplate(const T& a_value) : value_(a_value) {}\n\n  const T& value() const { return value_; }\n\n private:\n  T value_;\n};\n\ntemplate <typename T>\nvoid PrintTo(const PrintableViaPrintToTemplate<T>& x, ::std::ostream* os) {\n  *os << \"PrintableViaPrintToTemplate: \" << x.value();\n}\n\n// A user-defined streamable class template in a user namespace.\ntemplate <typename T>\nclass StreamableTemplateInFoo {\n public:\n  StreamableTemplateInFoo() : value_() {}\n\n  const T& value() const { return value_; }\n\n private:\n  T value_;\n};\n\ntemplate <typename T>\ninline ::std::ostream& operator<<(::std::ostream& os,\n                                  const StreamableTemplateInFoo<T>& x) {\n  return os << \"StreamableTemplateInFoo: \" << x.value();\n}\n\n// A user-defined streamable type in a user namespace whose operator<< is\n// templated on the type of the output stream.\nstruct TemplatedStreamableInFoo {};\n\ntemplate <typename OutputStream>\nOutputStream& operator<<(OutputStream& os,\n                         const TemplatedStreamableInFoo& /*ts*/) {\n  os << \"TemplatedStreamableInFoo\";\n  return os;\n}\n\n// A user-defined streamable but recursively-defined container type in\n// a user namespace, it mimics therefore std::filesystem::path or\n// boost::filesystem::path.\nclass PathLike {\n public:\n  struct iterator {\n    typedef PathLike value_type;\n\n    iterator& operator++();\n    PathLike& operator*();\n  };\n\n  using value_type = char;\n  using const_iterator = iterator;\n\n  PathLike() {}\n\n  iterator begin() const { return iterator(); }\n  iterator end() const { return iterator(); }\n\n  friend ::std::ostream& operator<<(::std::ostream& os, const PathLike&) {\n    return os << \"Streamable-PathLike\";\n  }\n};\n\n}  // namespace foo\n\nnamespace testing {\nnamespace {\ntemplate <typename T>\nclass Wrapper {\n public:\n  explicit Wrapper(T&& value) : value_(std::forward<T>(value)) {}\n\n  const T& value() const { return value_; }\n\n private:\n  T value_;\n};\n\n}  // namespace\n\nnamespace internal {\ntemplate <typename T>\nclass UniversalPrinter<Wrapper<T>> {\n public:\n  static void Print(const Wrapper<T>& w, ::std::ostream* os) {\n    *os << \"Wrapper(\";\n    UniversalPrint(w.value(), os);\n    *os << ')';\n  }\n};\n}  // namespace internal\n\nnamespace gtest_printers_test {\n\nusing ::std::deque;\nusing ::std::list;\nusing ::std::make_pair;\nusing ::std::map;\nusing ::std::multimap;\nusing ::std::multiset;\nusing ::std::pair;\nusing ::std::set;\nusing ::std::vector;\nusing ::testing::PrintToString;\nusing ::testing::internal::FormatForComparisonFailureMessage;\nusing ::testing::internal::ImplicitCast_;\nusing ::testing::internal::NativeArray;\nusing ::testing::internal::RelationToSourceReference;\nusing ::testing::internal::Strings;\nusing ::testing::internal::UniversalPrint;\nusing ::testing::internal::UniversalPrinter;\nusing ::testing::internal::UniversalTersePrint;\nusing ::testing::internal::UniversalTersePrintTupleFieldsToStrings;\n\n// Prints a value to a string using the universal value printer.  This\n// is a helper for testing UniversalPrinter<T>::Print() for various types.\ntemplate <typename T>\nstd::string Print(const T& value) {\n  ::std::stringstream ss;\n  UniversalPrinter<T>::Print(value, &ss);\n  return ss.str();\n}\n\n// Prints a value passed by reference to a string, using the universal\n// value printer.  This is a helper for testing\n// UniversalPrinter<T&>::Print() for various types.\ntemplate <typename T>\nstd::string PrintByRef(const T& value) {\n  ::std::stringstream ss;\n  UniversalPrinter<T&>::Print(value, &ss);\n  return ss.str();\n}\n\n// Tests printing various enum types.\n\nTEST(PrintEnumTest, AnonymousEnum) {\n  EXPECT_EQ(\"-1\", Print(kAE1));\n  EXPECT_EQ(\"1\", Print(kAE2));\n}\n\nTEST(PrintEnumTest, EnumWithoutPrinter) {\n  EXPECT_EQ(\"-2\", Print(kEWP1));\n  EXPECT_EQ(\"42\", Print(kEWP2));\n}\n\nTEST(PrintEnumTest, EnumWithStreaming) {\n  EXPECT_EQ(\"kEWS1\", Print(kEWS1));\n  EXPECT_EQ(\"invalid\", Print(static_cast<EnumWithStreaming>(0)));\n}\n\nTEST(PrintEnumTest, EnumWithPrintTo) {\n  EXPECT_EQ(\"kEWPT1\", Print(kEWPT1));\n  EXPECT_EQ(\"invalid\", Print(static_cast<EnumWithPrintTo>(0)));\n}\n\n// Tests printing a class implicitly convertible to BiggestInt.\n\nTEST(PrintClassTest, BiggestIntConvertible) {\n  EXPECT_EQ(\"42\", Print(BiggestIntConvertible()));\n}\n\n// Tests printing various char types.\n\n// char.\nTEST(PrintCharTest, PlainChar) {\n  EXPECT_EQ(\"'\\\\0'\", Print('\\0'));\n  EXPECT_EQ(\"'\\\\'' (39, 0x27)\", Print('\\''));\n  EXPECT_EQ(\"'\\\"' (34, 0x22)\", Print('\"'));\n  EXPECT_EQ(\"'?' (63, 0x3F)\", Print('?'));\n  EXPECT_EQ(\"'\\\\\\\\' (92, 0x5C)\", Print('\\\\'));\n  EXPECT_EQ(\"'\\\\a' (7)\", Print('\\a'));\n  EXPECT_EQ(\"'\\\\b' (8)\", Print('\\b'));\n  EXPECT_EQ(\"'\\\\f' (12, 0xC)\", Print('\\f'));\n  EXPECT_EQ(\"'\\\\n' (10, 0xA)\", Print('\\n'));\n  EXPECT_EQ(\"'\\\\r' (13, 0xD)\", Print('\\r'));\n  EXPECT_EQ(\"'\\\\t' (9)\", Print('\\t'));\n  EXPECT_EQ(\"'\\\\v' (11, 0xB)\", Print('\\v'));\n  EXPECT_EQ(\"'\\\\x7F' (127)\", Print('\\x7F'));\n  EXPECT_EQ(\"'\\\\xFF' (255)\", Print('\\xFF'));\n  EXPECT_EQ(\"' ' (32, 0x20)\", Print(' '));\n  EXPECT_EQ(\"'a' (97, 0x61)\", Print('a'));\n}\n\n// signed char.\nTEST(PrintCharTest, SignedChar) {\n  EXPECT_EQ(\"'\\\\0'\", Print(static_cast<signed char>('\\0')));\n  EXPECT_EQ(\"'\\\\xCE' (-50)\", Print(static_cast<signed char>(-50)));\n}\n\n// unsigned char.\nTEST(PrintCharTest, UnsignedChar) {\n  EXPECT_EQ(\"'\\\\0'\", Print(static_cast<unsigned char>('\\0')));\n  EXPECT_EQ(\"'b' (98, 0x62)\", Print(static_cast<unsigned char>('b')));\n}\n\nTEST(PrintCharTest, Char16) { EXPECT_EQ(\"U+0041\", Print(u'A')); }\n\nTEST(PrintCharTest, Char32) { EXPECT_EQ(\"U+0041\", Print(U'A')); }\n\n#ifdef __cpp_char8_t\nTEST(PrintCharTest, Char8) { EXPECT_EQ(\"U+0041\", Print(u8'A')); }\n#endif\n\n// Tests printing other simple, built-in types.\n\n// bool.\nTEST(PrintBuiltInTypeTest, Bool) {\n  EXPECT_EQ(\"false\", Print(false));\n  EXPECT_EQ(\"true\", Print(true));\n}\n\n// wchar_t.\nTEST(PrintBuiltInTypeTest, Wchar_t) {\n  EXPECT_EQ(\"L'\\\\0'\", Print(L'\\0'));\n  EXPECT_EQ(\"L'\\\\'' (39, 0x27)\", Print(L'\\''));\n  EXPECT_EQ(\"L'\\\"' (34, 0x22)\", Print(L'\"'));\n  EXPECT_EQ(\"L'?' (63, 0x3F)\", Print(L'?'));\n  EXPECT_EQ(\"L'\\\\\\\\' (92, 0x5C)\", Print(L'\\\\'));\n  EXPECT_EQ(\"L'\\\\a' (7)\", Print(L'\\a'));\n  EXPECT_EQ(\"L'\\\\b' (8)\", Print(L'\\b'));\n  EXPECT_EQ(\"L'\\\\f' (12, 0xC)\", Print(L'\\f'));\n  EXPECT_EQ(\"L'\\\\n' (10, 0xA)\", Print(L'\\n'));\n  EXPECT_EQ(\"L'\\\\r' (13, 0xD)\", Print(L'\\r'));\n  EXPECT_EQ(\"L'\\\\t' (9)\", Print(L'\\t'));\n  EXPECT_EQ(\"L'\\\\v' (11, 0xB)\", Print(L'\\v'));\n  EXPECT_EQ(\"L'\\\\x7F' (127)\", Print(L'\\x7F'));\n  EXPECT_EQ(\"L'\\\\xFF' (255)\", Print(L'\\xFF'));\n  EXPECT_EQ(\"L' ' (32, 0x20)\", Print(L' '));\n  EXPECT_EQ(\"L'a' (97, 0x61)\", Print(L'a'));\n  EXPECT_EQ(\"L'\\\\x576' (1398)\", Print(static_cast<wchar_t>(0x576)));\n  EXPECT_EQ(\"L'\\\\xC74D' (51021)\", Print(static_cast<wchar_t>(0xC74D)));\n}\n\n// Test that int64_t provides more storage than wchar_t.\nTEST(PrintTypeSizeTest, Wchar_t) {\n  EXPECT_LT(sizeof(wchar_t), sizeof(int64_t));\n}\n\n// Various integer types.\nTEST(PrintBuiltInTypeTest, Integer) {\n  EXPECT_EQ(\"'\\\\xFF' (255)\", Print(static_cast<unsigned char>(255)));  // uint8\n  EXPECT_EQ(\"'\\\\x80' (-128)\", Print(static_cast<signed char>(-128)));  // int8\n  EXPECT_EQ(\"65535\", Print(std::numeric_limits<uint16_t>::max()));     // uint16\n  EXPECT_EQ(\"-32768\", Print(std::numeric_limits<int16_t>::min()));     // int16\n  EXPECT_EQ(\"4294967295\",\n            Print(std::numeric_limits<uint32_t>::max()));  // uint32\n  EXPECT_EQ(\"-2147483648\",\n            Print(std::numeric_limits<int32_t>::min()));  // int32\n  EXPECT_EQ(\"18446744073709551615\",\n            Print(std::numeric_limits<uint64_t>::max()));  // uint64\n  EXPECT_EQ(\"-9223372036854775808\",\n            Print(std::numeric_limits<int64_t>::min()));  // int64\n#ifdef __cpp_char8_t\n  EXPECT_EQ(\"U+0000\",\n            Print(std::numeric_limits<char8_t>::min()));  // char8_t\n  EXPECT_EQ(\"U+00FF\",\n            Print(std::numeric_limits<char8_t>::max()));  // char8_t\n#endif\n  EXPECT_EQ(\"U+0000\",\n            Print(std::numeric_limits<char16_t>::min()));  // char16_t\n  EXPECT_EQ(\"U+FFFF\",\n            Print(std::numeric_limits<char16_t>::max()));  // char16_t\n  EXPECT_EQ(\"U+0000\",\n            Print(std::numeric_limits<char32_t>::min()));  // char32_t\n  EXPECT_EQ(\"U+FFFFFFFF\",\n            Print(std::numeric_limits<char32_t>::max()));  // char32_t\n}\n\n// Size types.\nTEST(PrintBuiltInTypeTest, Size_t) {\n  EXPECT_EQ(\"1\", Print(sizeof('a')));  // size_t.\n#if !GTEST_OS_WINDOWS\n  // Windows has no ssize_t type.\n  EXPECT_EQ(\"-2\", Print(static_cast<ssize_t>(-2)));  // ssize_t.\n#endif                                               // !GTEST_OS_WINDOWS\n}\n\n// gcc/clang __{u,}int128_t values.\n#if defined(__SIZEOF_INT128__)\nTEST(PrintBuiltInTypeTest, Int128) {\n  // Small ones\n  EXPECT_EQ(\"0\", Print(__int128_t{0}));\n  EXPECT_EQ(\"0\", Print(__uint128_t{0}));\n  EXPECT_EQ(\"12345\", Print(__int128_t{12345}));\n  EXPECT_EQ(\"12345\", Print(__uint128_t{12345}));\n  EXPECT_EQ(\"-12345\", Print(__int128_t{-12345}));\n\n  // Large ones\n  EXPECT_EQ(\"340282366920938463463374607431768211455\", Print(~__uint128_t{}));\n  __int128_t max_128 = static_cast<__int128_t>(~__uint128_t{} / 2);\n  EXPECT_EQ(\"-170141183460469231731687303715884105728\", Print(~max_128));\n  EXPECT_EQ(\"170141183460469231731687303715884105727\", Print(max_128));\n}\n#endif  // __SIZEOF_INT128__\n\n// Floating-points.\nTEST(PrintBuiltInTypeTest, FloatingPoints) {\n  EXPECT_EQ(\"1.5\", Print(1.5f));   // float\n  EXPECT_EQ(\"-2.5\", Print(-2.5));  // double\n}\n\n#if GTEST_HAS_RTTI\nTEST(PrintBuiltInTypeTest, TypeInfo) {\n  struct MyStruct {};\n  auto res = Print(typeid(MyStruct{}));\n  // We can't guarantee that we can demangle the name, but either name should\n  // contain the substring \"MyStruct\".\n  EXPECT_NE(res.find(\"MyStruct\"), res.npos) << res;\n}\n#endif  // GTEST_HAS_RTTI\n\n// Since ::std::stringstream::operator<<(const void *) formats the pointer\n// output differently with different compilers, we have to create the expected\n// output first and use it as our expectation.\nstatic std::string PrintPointer(const void* p) {\n  ::std::stringstream expected_result_stream;\n  expected_result_stream << p;\n  return expected_result_stream.str();\n}\n\n// Tests printing C strings.\n\n// const char*.\nTEST(PrintCStringTest, Const) {\n  const char* p = \"World\";\n  EXPECT_EQ(PrintPointer(p) + \" pointing to \\\"World\\\"\", Print(p));\n}\n\n// char*.\nTEST(PrintCStringTest, NonConst) {\n  char p[] = \"Hi\";\n  EXPECT_EQ(PrintPointer(p) + \" pointing to \\\"Hi\\\"\",\n            Print(static_cast<char*>(p)));\n}\n\n// NULL C string.\nTEST(PrintCStringTest, Null) {\n  const char* p = nullptr;\n  EXPECT_EQ(\"NULL\", Print(p));\n}\n\n// Tests that C strings are escaped properly.\nTEST(PrintCStringTest, EscapesProperly) {\n  const char* p = \"'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\x7F\\xFF a\";\n  EXPECT_EQ(PrintPointer(p) +\n                \" pointing to \\\"'\\\\\\\"?\\\\\\\\\\\\a\\\\b\\\\f\"\n                \"\\\\n\\\\r\\\\t\\\\v\\\\x7F\\\\xFF a\\\"\",\n            Print(p));\n}\n\n#ifdef __cpp_char8_t\n// const char8_t*.\nTEST(PrintU8StringTest, Const) {\n  const char8_t* p = u8\"界\";\n  EXPECT_EQ(PrintPointer(p) + \" pointing to u8\\\"\\\\xE7\\\\x95\\\\x8C\\\"\", Print(p));\n}\n\n// char8_t*.\nTEST(PrintU8StringTest, NonConst) {\n  char8_t p[] = u8\"世\";\n  EXPECT_EQ(PrintPointer(p) + \" pointing to u8\\\"\\\\xE4\\\\xB8\\\\x96\\\"\",\n            Print(static_cast<char8_t*>(p)));\n}\n\n// NULL u8 string.\nTEST(PrintU8StringTest, Null) {\n  const char8_t* p = nullptr;\n  EXPECT_EQ(\"NULL\", Print(p));\n}\n\n// Tests that u8 strings are escaped properly.\nTEST(PrintU8StringTest, EscapesProperly) {\n  const char8_t* p = u8\"'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\x7F\\xFF hello 世界\";\n  EXPECT_EQ(PrintPointer(p) +\n                \" pointing to u8\\\"'\\\\\\\"?\\\\\\\\\\\\a\\\\b\\\\f\\\\n\\\\r\\\\t\\\\v\\\\x7F\\\\xFF \"\n                \"hello \\\\xE4\\\\xB8\\\\x96\\\\xE7\\\\x95\\\\x8C\\\"\",\n            Print(p));\n}\n#endif\n\n// const char16_t*.\nTEST(PrintU16StringTest, Const) {\n  const char16_t* p = u\"界\";\n  EXPECT_EQ(PrintPointer(p) + \" pointing to u\\\"\\\\x754C\\\"\", Print(p));\n}\n\n// char16_t*.\nTEST(PrintU16StringTest, NonConst) {\n  char16_t p[] = u\"世\";\n  EXPECT_EQ(PrintPointer(p) + \" pointing to u\\\"\\\\x4E16\\\"\",\n            Print(static_cast<char16_t*>(p)));\n}\n\n// NULL u16 string.\nTEST(PrintU16StringTest, Null) {\n  const char16_t* p = nullptr;\n  EXPECT_EQ(\"NULL\", Print(p));\n}\n\n// Tests that u16 strings are escaped properly.\nTEST(PrintU16StringTest, EscapesProperly) {\n  const char16_t* p = u\"'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\x7F\\xFF hello 世界\";\n  EXPECT_EQ(PrintPointer(p) +\n                \" pointing to u\\\"'\\\\\\\"?\\\\\\\\\\\\a\\\\b\\\\f\\\\n\\\\r\\\\t\\\\v\\\\x7F\\\\xFF \"\n                \"hello \\\\x4E16\\\\x754C\\\"\",\n            Print(p));\n}\n\n// const char32_t*.\nTEST(PrintU32StringTest, Const) {\n  const char32_t* p = U\"🗺️\";\n  EXPECT_EQ(PrintPointer(p) + \" pointing to U\\\"\\\\x1F5FA\\\\xFE0F\\\"\", Print(p));\n}\n\n// char32_t*.\nTEST(PrintU32StringTest, NonConst) {\n  char32_t p[] = U\"🌌\";\n  EXPECT_EQ(PrintPointer(p) + \" pointing to U\\\"\\\\x1F30C\\\"\",\n            Print(static_cast<char32_t*>(p)));\n}\n\n// NULL u32 string.\nTEST(PrintU32StringTest, Null) {\n  const char32_t* p = nullptr;\n  EXPECT_EQ(\"NULL\", Print(p));\n}\n\n// Tests that u32 strings are escaped properly.\nTEST(PrintU32StringTest, EscapesProperly) {\n  const char32_t* p = U\"'\\\"?\\\\\\a\\b\\f\\n\\r\\t\\v\\x7F\\xFF hello 🗺️\";\n  EXPECT_EQ(PrintPointer(p) +\n                \" pointing to U\\\"'\\\\\\\"?\\\\\\\\\\\\a\\\\b\\\\f\\\\n\\\\r\\\\t\\\\v\\\\x7F\\\\xFF \"\n                \"hello \\\\x1F5FA\\\\xFE0F\\\"\",\n            Print(p));\n}\n\n// MSVC compiler can be configured to define whar_t as a typedef\n// of unsigned short. Defining an overload for const wchar_t* in that case\n// would cause pointers to unsigned shorts be printed as wide strings,\n// possibly accessing more memory than intended and causing invalid\n// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when\n// wchar_t is implemented as a native type.\n#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)\n\n// const wchar_t*.\nTEST(PrintWideCStringTest, Const) {\n  const wchar_t* p = L\"World\";\n  EXPECT_EQ(PrintPointer(p) + \" pointing to L\\\"World\\\"\", Print(p));\n}\n\n// wchar_t*.\nTEST(PrintWideCStringTest, NonConst) {\n  wchar_t p[] = L\"Hi\";\n  EXPECT_EQ(PrintPointer(p) + \" pointing to L\\\"Hi\\\"\",\n            Print(static_cast<wchar_t*>(p)));\n}\n\n// NULL wide C string.\nTEST(PrintWideCStringTest, Null) {\n  const wchar_t* p = nullptr;\n  EXPECT_EQ(\"NULL\", Print(p));\n}\n\n// Tests that wide C strings are escaped properly.\nTEST(PrintWideCStringTest, EscapesProperly) {\n  const wchar_t s[] = {'\\'',  '\"',   '?',    '\\\\', '\\a', '\\b',\n                       '\\f',  '\\n',  '\\r',   '\\t', '\\v', 0xD3,\n                       0x576, 0x8D3, 0xC74D, ' ',  'a',  '\\0'};\n  EXPECT_EQ(PrintPointer(s) +\n                \" pointing to L\\\"'\\\\\\\"?\\\\\\\\\\\\a\\\\b\\\\f\"\n                \"\\\\n\\\\r\\\\t\\\\v\\\\xD3\\\\x576\\\\x8D3\\\\xC74D a\\\"\",\n            Print(static_cast<const wchar_t*>(s)));\n}\n#endif  // native wchar_t\n\n// Tests printing pointers to other char types.\n\n// signed char*.\nTEST(PrintCharPointerTest, SignedChar) {\n  signed char* p = reinterpret_cast<signed char*>(0x1234);\n  EXPECT_EQ(PrintPointer(p), Print(p));\n  p = nullptr;\n  EXPECT_EQ(\"NULL\", Print(p));\n}\n\n// const signed char*.\nTEST(PrintCharPointerTest, ConstSignedChar) {\n  signed char* p = reinterpret_cast<signed char*>(0x1234);\n  EXPECT_EQ(PrintPointer(p), Print(p));\n  p = nullptr;\n  EXPECT_EQ(\"NULL\", Print(p));\n}\n\n// unsigned char*.\nTEST(PrintCharPointerTest, UnsignedChar) {\n  unsigned char* p = reinterpret_cast<unsigned char*>(0x1234);\n  EXPECT_EQ(PrintPointer(p), Print(p));\n  p = nullptr;\n  EXPECT_EQ(\"NULL\", Print(p));\n}\n\n// const unsigned char*.\nTEST(PrintCharPointerTest, ConstUnsignedChar) {\n  const unsigned char* p = reinterpret_cast<const unsigned char*>(0x1234);\n  EXPECT_EQ(PrintPointer(p), Print(p));\n  p = nullptr;\n  EXPECT_EQ(\"NULL\", Print(p));\n}\n\n// Tests printing pointers to simple, built-in types.\n\n// bool*.\nTEST(PrintPointerToBuiltInTypeTest, Bool) {\n  bool* p = reinterpret_cast<bool*>(0xABCD);\n  EXPECT_EQ(PrintPointer(p), Print(p));\n  p = nullptr;\n  EXPECT_EQ(\"NULL\", Print(p));\n}\n\n// void*.\nTEST(PrintPointerToBuiltInTypeTest, Void) {\n  void* p = reinterpret_cast<void*>(0xABCD);\n  EXPECT_EQ(PrintPointer(p), Print(p));\n  p = nullptr;\n  EXPECT_EQ(\"NULL\", Print(p));\n}\n\n// const void*.\nTEST(PrintPointerToBuiltInTypeTest, ConstVoid) {\n  const void* p = reinterpret_cast<const void*>(0xABCD);\n  EXPECT_EQ(PrintPointer(p), Print(p));\n  p = nullptr;\n  EXPECT_EQ(\"NULL\", Print(p));\n}\n\n// Tests printing pointers to pointers.\nTEST(PrintPointerToPointerTest, IntPointerPointer) {\n  int** p = reinterpret_cast<int**>(0xABCD);\n  EXPECT_EQ(PrintPointer(p), Print(p));\n  p = nullptr;\n  EXPECT_EQ(\"NULL\", Print(p));\n}\n\n// Tests printing (non-member) function pointers.\n\nvoid MyFunction(int /* n */) {}\n\nTEST(PrintPointerTest, NonMemberFunctionPointer) {\n  // We cannot directly cast &MyFunction to const void* because the\n  // standard disallows casting between pointers to functions and\n  // pointers to objects, and some compilers (e.g. GCC 3.4) enforce\n  // this limitation.\n  EXPECT_EQ(PrintPointer(reinterpret_cast<const void*>(\n                reinterpret_cast<internal::BiggestInt>(&MyFunction))),\n            Print(&MyFunction));\n  int (*p)(bool) = NULL;  // NOLINT\n  EXPECT_EQ(\"NULL\", Print(p));\n}\n\n// An assertion predicate determining whether a one string is a prefix for\n// another.\ntemplate <typename StringType>\nAssertionResult HasPrefix(const StringType& str, const StringType& prefix) {\n  if (str.find(prefix, 0) == 0) return AssertionSuccess();\n\n  const bool is_wide_string = sizeof(prefix[0]) > 1;\n  const char* const begin_string_quote = is_wide_string ? \"L\\\"\" : \"\\\"\";\n  return AssertionFailure()\n         << begin_string_quote << prefix << \"\\\" is not a prefix of \"\n         << begin_string_quote << str << \"\\\"\\n\";\n}\n\n// Tests printing member variable pointers.  Although they are called\n// pointers, they don't point to a location in the address space.\n// Their representation is implementation-defined.  Thus they will be\n// printed as raw bytes.\n\nstruct Foo {\n public:\n  virtual ~Foo() {}\n  int MyMethod(char x) { return x + 1; }\n  virtual char MyVirtualMethod(int /* n */) { return 'a'; }\n\n  int value;\n};\n\nTEST(PrintPointerTest, MemberVariablePointer) {\n  EXPECT_TRUE(HasPrefix(Print(&Foo::value),\n                        Print(sizeof(&Foo::value)) + \"-byte object \"));\n  int Foo::*p = NULL;  // NOLINT\n  EXPECT_TRUE(HasPrefix(Print(p), Print(sizeof(p)) + \"-byte object \"));\n}\n\n// Tests printing member function pointers.  Although they are called\n// pointers, they don't point to a location in the address space.\n// Their representation is implementation-defined.  Thus they will be\n// printed as raw bytes.\nTEST(PrintPointerTest, MemberFunctionPointer) {\n  EXPECT_TRUE(HasPrefix(Print(&Foo::MyMethod),\n                        Print(sizeof(&Foo::MyMethod)) + \"-byte object \"));\n  EXPECT_TRUE(\n      HasPrefix(Print(&Foo::MyVirtualMethod),\n                Print(sizeof((&Foo::MyVirtualMethod))) + \"-byte object \"));\n  int (Foo::*p)(char) = NULL;  // NOLINT\n  EXPECT_TRUE(HasPrefix(Print(p), Print(sizeof(p)) + \"-byte object \"));\n}\n\n// Tests printing C arrays.\n\n// The difference between this and Print() is that it ensures that the\n// argument is a reference to an array.\ntemplate <typename T, size_t N>\nstd::string PrintArrayHelper(T (&a)[N]) {\n  return Print(a);\n}\n\n// One-dimensional array.\nTEST(PrintArrayTest, OneDimensionalArray) {\n  int a[5] = {1, 2, 3, 4, 5};\n  EXPECT_EQ(\"{ 1, 2, 3, 4, 5 }\", PrintArrayHelper(a));\n}\n\n// Two-dimensional array.\nTEST(PrintArrayTest, TwoDimensionalArray) {\n  int a[2][5] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 0}};\n  EXPECT_EQ(\"{ { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0 } }\", PrintArrayHelper(a));\n}\n\n// Array of const elements.\nTEST(PrintArrayTest, ConstArray) {\n  const bool a[1] = {false};\n  EXPECT_EQ(\"{ false }\", PrintArrayHelper(a));\n}\n\n// char array without terminating NUL.\nTEST(PrintArrayTest, CharArrayWithNoTerminatingNul) {\n  // Array a contains '\\0' in the middle and doesn't end with '\\0'.\n  char a[] = {'H', '\\0', 'i'};\n  EXPECT_EQ(\"\\\"H\\\\0i\\\" (no terminating NUL)\", PrintArrayHelper(a));\n}\n\n// char array with terminating NUL.\nTEST(PrintArrayTest, CharArrayWithTerminatingNul) {\n  const char a[] = \"\\0Hi\";\n  EXPECT_EQ(\"\\\"\\\\0Hi\\\"\", PrintArrayHelper(a));\n}\n\n#ifdef __cpp_char8_t\n// char_t array without terminating NUL.\nTEST(PrintArrayTest, Char8ArrayWithNoTerminatingNul) {\n  // Array a contains '\\0' in the middle and doesn't end with '\\0'.\n  const char8_t a[] = {u8'H', u8'\\0', u8'i'};\n  EXPECT_EQ(\"u8\\\"H\\\\0i\\\" (no terminating NUL)\", PrintArrayHelper(a));\n}\n\n// char8_t array with terminating NUL.\nTEST(PrintArrayTest, Char8ArrayWithTerminatingNul) {\n  const char8_t a[] = u8\"\\0世界\";\n  EXPECT_EQ(\"u8\\\"\\\\0\\\\xE4\\\\xB8\\\\x96\\\\xE7\\\\x95\\\\x8C\\\"\", PrintArrayHelper(a));\n}\n#endif\n\n// const char16_t array without terminating NUL.\nTEST(PrintArrayTest, Char16ArrayWithNoTerminatingNul) {\n  // Array a contains '\\0' in the middle and doesn't end with '\\0'.\n  const char16_t a[] = {u'こ', u'\\0', u'ん', u'に', u'ち', u'は'};\n  EXPECT_EQ(\"u\\\"\\\\x3053\\\\0\\\\x3093\\\\x306B\\\\x3061\\\\x306F\\\" (no terminating NUL)\",\n            PrintArrayHelper(a));\n}\n\n// char16_t array with terminating NUL.\nTEST(PrintArrayTest, Char16ArrayWithTerminatingNul) {\n  const char16_t a[] = u\"\\0こんにちは\";\n  EXPECT_EQ(\"u\\\"\\\\0\\\\x3053\\\\x3093\\\\x306B\\\\x3061\\\\x306F\\\"\", PrintArrayHelper(a));\n}\n\n// char32_t array without terminating NUL.\nTEST(PrintArrayTest, Char32ArrayWithNoTerminatingNul) {\n  // Array a contains '\\0' in the middle and doesn't end with '\\0'.\n  const char32_t a[] = {U'👋', U'\\0', U'🌌'};\n  EXPECT_EQ(\"U\\\"\\\\x1F44B\\\\0\\\\x1F30C\\\" (no terminating NUL)\",\n            PrintArrayHelper(a));\n}\n\n// char32_t array with terminating NUL.\nTEST(PrintArrayTest, Char32ArrayWithTerminatingNul) {\n  const char32_t a[] = U\"\\0👋🌌\";\n  EXPECT_EQ(\"U\\\"\\\\0\\\\x1F44B\\\\x1F30C\\\"\", PrintArrayHelper(a));\n}\n\n// wchar_t array without terminating NUL.\nTEST(PrintArrayTest, WCharArrayWithNoTerminatingNul) {\n  // Array a contains '\\0' in the middle and doesn't end with '\\0'.\n  const wchar_t a[] = {L'H', L'\\0', L'i'};\n  EXPECT_EQ(\"L\\\"H\\\\0i\\\" (no terminating NUL)\", PrintArrayHelper(a));\n}\n\n// wchar_t array with terminating NUL.\nTEST(PrintArrayTest, WCharArrayWithTerminatingNul) {\n  const wchar_t a[] = L\"\\0Hi\";\n  EXPECT_EQ(\"L\\\"\\\\0Hi\\\"\", PrintArrayHelper(a));\n}\n\n// Array of objects.\nTEST(PrintArrayTest, ObjectArray) {\n  std::string a[3] = {\"Hi\", \"Hello\", \"Ni hao\"};\n  EXPECT_EQ(\"{ \\\"Hi\\\", \\\"Hello\\\", \\\"Ni hao\\\" }\", PrintArrayHelper(a));\n}\n\n// Array with many elements.\nTEST(PrintArrayTest, BigArray) {\n  int a[100] = {1, 2, 3};\n  EXPECT_EQ(\"{ 1, 2, 3, 0, 0, 0, 0, 0, ..., 0, 0, 0, 0, 0, 0, 0, 0 }\",\n            PrintArrayHelper(a));\n}\n\n// Tests printing ::string and ::std::string.\n\n// ::std::string.\nTEST(PrintStringTest, StringInStdNamespace) {\n  const char s[] = \"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\x7F\\xFF a\";\n  const ::std::string str(s, sizeof(s));\n  EXPECT_EQ(\"\\\"'\\\\\\\"?\\\\\\\\\\\\a\\\\b\\\\f\\\\n\\\\0\\\\r\\\\t\\\\v\\\\x7F\\\\xFF a\\\\0\\\"\",\n            Print(str));\n}\n\nTEST(PrintStringTest, StringAmbiguousHex) {\n  // \"\\x6BANANA\" is ambiguous, it can be interpreted as starting with either of:\n  // '\\x6', '\\x6B', or '\\x6BA'.\n\n  // a hex escaping sequence following by a decimal digit\n  EXPECT_EQ(\"\\\"0\\\\x12\\\" \\\"3\\\"\", Print(::std::string(\"0\\x12\"\n                                                    \"3\")));\n  // a hex escaping sequence following by a hex digit (lower-case)\n  EXPECT_EQ(\"\\\"mm\\\\x6\\\" \\\"bananas\\\"\", Print(::std::string(\"mm\\x6\"\n                                                          \"bananas\")));\n  // a hex escaping sequence following by a hex digit (upper-case)\n  EXPECT_EQ(\"\\\"NOM\\\\x6\\\" \\\"BANANA\\\"\", Print(::std::string(\"NOM\\x6\"\n                                                          \"BANANA\")));\n  // a hex escaping sequence following by a non-xdigit\n  EXPECT_EQ(\"\\\"!\\\\x5-!\\\"\", Print(::std::string(\"!\\x5-!\")));\n}\n\n// Tests printing ::std::wstring.\n#if GTEST_HAS_STD_WSTRING\n// ::std::wstring.\nTEST(PrintWideStringTest, StringInStdNamespace) {\n  const wchar_t s[] = L\"'\\\"?\\\\\\a\\b\\f\\n\\0\\r\\t\\v\\xD3\\x576\\x8D3\\xC74D a\";\n  const ::std::wstring str(s, sizeof(s) / sizeof(wchar_t));\n  EXPECT_EQ(\n      \"L\\\"'\\\\\\\"?\\\\\\\\\\\\a\\\\b\\\\f\\\\n\\\\0\\\\r\\\\t\\\\v\"\n      \"\\\\xD3\\\\x576\\\\x8D3\\\\xC74D a\\\\0\\\"\",\n      Print(str));\n}\n\nTEST(PrintWideStringTest, StringAmbiguousHex) {\n  // same for wide strings.\n  EXPECT_EQ(\"L\\\"0\\\\x12\\\" L\\\"3\\\"\", Print(::std::wstring(L\"0\\x12\"\n                                                       L\"3\")));\n  EXPECT_EQ(\"L\\\"mm\\\\x6\\\" L\\\"bananas\\\"\", Print(::std::wstring(L\"mm\\x6\"\n                                                             L\"bananas\")));\n  EXPECT_EQ(\"L\\\"NOM\\\\x6\\\" L\\\"BANANA\\\"\", Print(::std::wstring(L\"NOM\\x6\"\n                                                             L\"BANANA\")));\n  EXPECT_EQ(\"L\\\"!\\\\x5-!\\\"\", Print(::std::wstring(L\"!\\x5-!\")));\n}\n#endif  // GTEST_HAS_STD_WSTRING\n\n#ifdef __cpp_char8_t\nTEST(PrintStringTest, U8String) {\n  std::u8string str = u8\"Hello, 世界\";\n  EXPECT_EQ(str, str);  // Verify EXPECT_EQ compiles with this type.\n  EXPECT_EQ(\"u8\\\"Hello, \\\\xE4\\\\xB8\\\\x96\\\\xE7\\\\x95\\\\x8C\\\"\", Print(str));\n}\n#endif\n\nTEST(PrintStringTest, U16String) {\n  std::u16string str = u\"Hello, 世界\";\n  EXPECT_EQ(str, str);  // Verify EXPECT_EQ compiles with this type.\n  EXPECT_EQ(\"u\\\"Hello, \\\\x4E16\\\\x754C\\\"\", Print(str));\n}\n\nTEST(PrintStringTest, U32String) {\n  std::u32string str = U\"Hello, 🗺️\";\n  EXPECT_EQ(str, str);  // Verify EXPECT_EQ compiles with this type\n  EXPECT_EQ(\"U\\\"Hello, \\\\x1F5FA\\\\xFE0F\\\"\", Print(str));\n}\n\n// Tests printing types that support generic streaming (i.e. streaming\n// to std::basic_ostream<Char, CharTraits> for any valid Char and\n// CharTraits types).\n\n// Tests printing a non-template type that supports generic streaming.\n\nclass AllowsGenericStreaming {};\n\ntemplate <typename Char, typename CharTraits>\nstd::basic_ostream<Char, CharTraits>& operator<<(\n    std::basic_ostream<Char, CharTraits>& os,\n    const AllowsGenericStreaming& /* a */) {\n  return os << \"AllowsGenericStreaming\";\n}\n\nTEST(PrintTypeWithGenericStreamingTest, NonTemplateType) {\n  AllowsGenericStreaming a;\n  EXPECT_EQ(\"AllowsGenericStreaming\", Print(a));\n}\n\n// Tests printing a template type that supports generic streaming.\n\ntemplate <typename T>\nclass AllowsGenericStreamingTemplate {};\n\ntemplate <typename Char, typename CharTraits, typename T>\nstd::basic_ostream<Char, CharTraits>& operator<<(\n    std::basic_ostream<Char, CharTraits>& os,\n    const AllowsGenericStreamingTemplate<T>& /* a */) {\n  return os << \"AllowsGenericStreamingTemplate\";\n}\n\nTEST(PrintTypeWithGenericStreamingTest, TemplateType) {\n  AllowsGenericStreamingTemplate<int> a;\n  EXPECT_EQ(\"AllowsGenericStreamingTemplate\", Print(a));\n}\n\n// Tests printing a type that supports generic streaming and can be\n// implicitly converted to another printable type.\n\ntemplate <typename T>\nclass AllowsGenericStreamingAndImplicitConversionTemplate {\n public:\n  operator bool() const { return false; }\n};\n\ntemplate <typename Char, typename CharTraits, typename T>\nstd::basic_ostream<Char, CharTraits>& operator<<(\n    std::basic_ostream<Char, CharTraits>& os,\n    const AllowsGenericStreamingAndImplicitConversionTemplate<T>& /* a */) {\n  return os << \"AllowsGenericStreamingAndImplicitConversionTemplate\";\n}\n\nTEST(PrintTypeWithGenericStreamingTest, TypeImplicitlyConvertible) {\n  AllowsGenericStreamingAndImplicitConversionTemplate<int> a;\n  EXPECT_EQ(\"AllowsGenericStreamingAndImplicitConversionTemplate\", Print(a));\n}\n\n#if GTEST_INTERNAL_HAS_STRING_VIEW\n\n// Tests printing internal::StringView.\n\nTEST(PrintStringViewTest, SimpleStringView) {\n  const internal::StringView sp = \"Hello\";\n  EXPECT_EQ(\"\\\"Hello\\\"\", Print(sp));\n}\n\nTEST(PrintStringViewTest, UnprintableCharacters) {\n  const char str[] = \"NUL (\\0) and \\r\\t\";\n  const internal::StringView sp(str, sizeof(str) - 1);\n  EXPECT_EQ(\"\\\"NUL (\\\\0) and \\\\r\\\\t\\\"\", Print(sp));\n}\n\n#endif  // GTEST_INTERNAL_HAS_STRING_VIEW\n\n// Tests printing STL containers.\n\nTEST(PrintStlContainerTest, EmptyDeque) {\n  deque<char> empty;\n  EXPECT_EQ(\"{}\", Print(empty));\n}\n\nTEST(PrintStlContainerTest, NonEmptyDeque) {\n  deque<int> non_empty;\n  non_empty.push_back(1);\n  non_empty.push_back(3);\n  EXPECT_EQ(\"{ 1, 3 }\", Print(non_empty));\n}\n\nTEST(PrintStlContainerTest, OneElementHashMap) {\n  ::std::unordered_map<int, char> map1;\n  map1[1] = 'a';\n  EXPECT_EQ(\"{ (1, 'a' (97, 0x61)) }\", Print(map1));\n}\n\nTEST(PrintStlContainerTest, HashMultiMap) {\n  ::std::unordered_multimap<int, bool> map1;\n  map1.insert(make_pair(5, true));\n  map1.insert(make_pair(5, false));\n\n  // Elements of hash_multimap can be printed in any order.\n  const std::string result = Print(map1);\n  EXPECT_TRUE(result == \"{ (5, true), (5, false) }\" ||\n              result == \"{ (5, false), (5, true) }\")\n      << \" where Print(map1) returns \\\"\" << result << \"\\\".\";\n}\n\nTEST(PrintStlContainerTest, HashSet) {\n  ::std::unordered_set<int> set1;\n  set1.insert(1);\n  EXPECT_EQ(\"{ 1 }\", Print(set1));\n}\n\nTEST(PrintStlContainerTest, HashMultiSet) {\n  const int kSize = 5;\n  int a[kSize] = {1, 1, 2, 5, 1};\n  ::std::unordered_multiset<int> set1(a, a + kSize);\n\n  // Elements of hash_multiset can be printed in any order.\n  const std::string result = Print(set1);\n  const std::string expected_pattern = \"{ d, d, d, d, d }\";  // d means a digit.\n\n  // Verifies the result matches the expected pattern; also extracts\n  // the numbers in the result.\n  ASSERT_EQ(expected_pattern.length(), result.length());\n  std::vector<int> numbers;\n  for (size_t i = 0; i != result.length(); i++) {\n    if (expected_pattern[i] == 'd') {\n      ASSERT_NE(isdigit(static_cast<unsigned char>(result[i])), 0);\n      numbers.push_back(result[i] - '0');\n    } else {\n      EXPECT_EQ(expected_pattern[i], result[i])\n          << \" where result is \" << result;\n    }\n  }\n\n  // Makes sure the result contains the right numbers.\n  std::sort(numbers.begin(), numbers.end());\n  std::sort(a, a + kSize);\n  EXPECT_TRUE(std::equal(a, a + kSize, numbers.begin()));\n}\n\nTEST(PrintStlContainerTest, List) {\n  const std::string a[] = {\"hello\", \"world\"};\n  const list<std::string> strings(a, a + 2);\n  EXPECT_EQ(\"{ \\\"hello\\\", \\\"world\\\" }\", Print(strings));\n}\n\nTEST(PrintStlContainerTest, Map) {\n  map<int, bool> map1;\n  map1[1] = true;\n  map1[5] = false;\n  map1[3] = true;\n  EXPECT_EQ(\"{ (1, true), (3, true), (5, false) }\", Print(map1));\n}\n\nTEST(PrintStlContainerTest, MultiMap) {\n  multimap<bool, int> map1;\n  // The make_pair template function would deduce the type as\n  // pair<bool, int> here, and since the key part in a multimap has to\n  // be constant, without a templated ctor in the pair class (as in\n  // libCstd on Solaris), make_pair call would fail to compile as no\n  // implicit conversion is found.  Thus explicit typename is used\n  // here instead.\n  map1.insert(pair<const bool, int>(true, 0));\n  map1.insert(pair<const bool, int>(true, 1));\n  map1.insert(pair<const bool, int>(false, 2));\n  EXPECT_EQ(\"{ (false, 2), (true, 0), (true, 1) }\", Print(map1));\n}\n\nTEST(PrintStlContainerTest, Set) {\n  const unsigned int a[] = {3, 0, 5};\n  set<unsigned int> set1(a, a + 3);\n  EXPECT_EQ(\"{ 0, 3, 5 }\", Print(set1));\n}\n\nTEST(PrintStlContainerTest, MultiSet) {\n  const int a[] = {1, 1, 2, 5, 1};\n  multiset<int> set1(a, a + 5);\n  EXPECT_EQ(\"{ 1, 1, 1, 2, 5 }\", Print(set1));\n}\n\nTEST(PrintStlContainerTest, SinglyLinkedList) {\n  int a[] = {9, 2, 8};\n  const std::forward_list<int> ints(a, a + 3);\n  EXPECT_EQ(\"{ 9, 2, 8 }\", Print(ints));\n}\n\nTEST(PrintStlContainerTest, Pair) {\n  pair<const bool, int> p(true, 5);\n  EXPECT_EQ(\"(true, 5)\", Print(p));\n}\n\nTEST(PrintStlContainerTest, Vector) {\n  vector<int> v;\n  v.push_back(1);\n  v.push_back(2);\n  EXPECT_EQ(\"{ 1, 2 }\", Print(v));\n}\n\nTEST(PrintStlContainerTest, LongSequence) {\n  const int a[100] = {1, 2, 3};\n  const vector<int> v(a, a + 100);\n  EXPECT_EQ(\n      \"{ 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, \"\n      \"0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ... }\",\n      Print(v));\n}\n\nTEST(PrintStlContainerTest, NestedContainer) {\n  const int a1[] = {1, 2};\n  const int a2[] = {3, 4, 5};\n  const list<int> l1(a1, a1 + 2);\n  const list<int> l2(a2, a2 + 3);\n\n  vector<list<int>> v;\n  v.push_back(l1);\n  v.push_back(l2);\n  EXPECT_EQ(\"{ { 1, 2 }, { 3, 4, 5 } }\", Print(v));\n}\n\nTEST(PrintStlContainerTest, OneDimensionalNativeArray) {\n  const int a[3] = {1, 2, 3};\n  NativeArray<int> b(a, 3, RelationToSourceReference());\n  EXPECT_EQ(\"{ 1, 2, 3 }\", Print(b));\n}\n\nTEST(PrintStlContainerTest, TwoDimensionalNativeArray) {\n  const int a[2][3] = {{1, 2, 3}, {4, 5, 6}};\n  NativeArray<int[3]> b(a, 2, RelationToSourceReference());\n  EXPECT_EQ(\"{ { 1, 2, 3 }, { 4, 5, 6 } }\", Print(b));\n}\n\n// Tests that a class named iterator isn't treated as a container.\n\nstruct iterator {\n  char x;\n};\n\nTEST(PrintStlContainerTest, Iterator) {\n  iterator it = {};\n  EXPECT_EQ(\"1-byte object <00>\", Print(it));\n}\n\n// Tests that a class named const_iterator isn't treated as a container.\n\nstruct const_iterator {\n  char x;\n};\n\nTEST(PrintStlContainerTest, ConstIterator) {\n  const_iterator it = {};\n  EXPECT_EQ(\"1-byte object <00>\", Print(it));\n}\n\n// Tests printing ::std::tuples.\n\n// Tuples of various arities.\nTEST(PrintStdTupleTest, VariousSizes) {\n  ::std::tuple<> t0;\n  EXPECT_EQ(\"()\", Print(t0));\n\n  ::std::tuple<int> t1(5);\n  EXPECT_EQ(\"(5)\", Print(t1));\n\n  ::std::tuple<char, bool> t2('a', true);\n  EXPECT_EQ(\"('a' (97, 0x61), true)\", Print(t2));\n\n  ::std::tuple<bool, int, int> t3(false, 2, 3);\n  EXPECT_EQ(\"(false, 2, 3)\", Print(t3));\n\n  ::std::tuple<bool, int, int, int> t4(false, 2, 3, 4);\n  EXPECT_EQ(\"(false, 2, 3, 4)\", Print(t4));\n\n  const char* const str = \"8\";\n  ::std::tuple<bool, char, short, int32_t, int64_t, float, double,  // NOLINT\n               const char*, void*, std::string>\n      t10(false, 'a', static_cast<short>(3), 4, 5, 1.5F, -2.5, str,  // NOLINT\n          nullptr, \"10\");\n  EXPECT_EQ(\"(false, 'a' (97, 0x61), 3, 4, 5, 1.5, -2.5, \" + PrintPointer(str) +\n                \" pointing to \\\"8\\\", NULL, \\\"10\\\")\",\n            Print(t10));\n}\n\n// Nested tuples.\nTEST(PrintStdTupleTest, NestedTuple) {\n  ::std::tuple<::std::tuple<int, bool>, char> nested(::std::make_tuple(5, true),\n                                                     'a');\n  EXPECT_EQ(\"((5, true), 'a' (97, 0x61))\", Print(nested));\n}\n\nTEST(PrintNullptrT, Basic) { EXPECT_EQ(\"(nullptr)\", Print(nullptr)); }\n\nTEST(PrintReferenceWrapper, Printable) {\n  int x = 5;\n  EXPECT_EQ(\"@\" + PrintPointer(&x) + \" 5\", Print(std::ref(x)));\n  EXPECT_EQ(\"@\" + PrintPointer(&x) + \" 5\", Print(std::cref(x)));\n}\n\nTEST(PrintReferenceWrapper, Unprintable) {\n  ::foo::UnprintableInFoo up;\n  EXPECT_EQ(\n      \"@\" + PrintPointer(&up) +\n          \" 16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>\",\n      Print(std::ref(up)));\n  EXPECT_EQ(\n      \"@\" + PrintPointer(&up) +\n          \" 16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>\",\n      Print(std::cref(up)));\n}\n\n// Tests printing user-defined unprintable types.\n\n// Unprintable types in the global namespace.\nTEST(PrintUnprintableTypeTest, InGlobalNamespace) {\n  EXPECT_EQ(\"1-byte object <00>\", Print(UnprintableTemplateInGlobal<char>()));\n}\n\n// Unprintable types in a user namespace.\nTEST(PrintUnprintableTypeTest, InUserNamespace) {\n  EXPECT_EQ(\"16-byte object <EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>\",\n            Print(::foo::UnprintableInFoo()));\n}\n\n// Unprintable types are that too big to be printed completely.\n\nstruct Big {\n  Big() { memset(array, 0, sizeof(array)); }\n  char array[257];\n};\n\nTEST(PrintUnpritableTypeTest, BigObject) {\n  EXPECT_EQ(\n      \"257-byte object <00-00 00-00 00-00 00-00 00-00 00-00 \"\n      \"00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 \"\n      \"00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 \"\n      \"00-00 00-00 00-00 00-00 00-00 00-00 ... 00-00 00-00 00-00 \"\n      \"00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 \"\n      \"00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 \"\n      \"00-00 00-00 00-00 00-00 00-00 00-00 00-00 00-00 00>\",\n      Print(Big()));\n}\n\n// Tests printing user-defined streamable types.\n\n// Streamable types in the global namespace.\nTEST(PrintStreamableTypeTest, InGlobalNamespace) {\n  StreamableInGlobal x;\n  EXPECT_EQ(\"StreamableInGlobal\", Print(x));\n  EXPECT_EQ(\"StreamableInGlobal*\", Print(&x));\n}\n\n// Printable template types in a user namespace.\nTEST(PrintStreamableTypeTest, TemplateTypeInUserNamespace) {\n  EXPECT_EQ(\"StreamableTemplateInFoo: 0\",\n            Print(::foo::StreamableTemplateInFoo<int>()));\n}\n\nTEST(PrintStreamableTypeTest, TypeInUserNamespaceWithTemplatedStreamOperator) {\n  EXPECT_EQ(\"TemplatedStreamableInFoo\",\n            Print(::foo::TemplatedStreamableInFoo()));\n}\n\nTEST(PrintStreamableTypeTest, SubclassUsesSuperclassStreamOperator) {\n  ParentClass parent;\n  ChildClassWithStreamOperator child_stream;\n  ChildClassWithoutStreamOperator child_no_stream;\n  EXPECT_EQ(\"ParentClass\", Print(parent));\n  EXPECT_EQ(\"ChildClassWithStreamOperator\", Print(child_stream));\n  EXPECT_EQ(\"ParentClass\", Print(child_no_stream));\n}\n\n// Tests printing a user-defined recursive container type that has a <<\n// operator.\nTEST(PrintStreamableTypeTest, PathLikeInUserNamespace) {\n  ::foo::PathLike x;\n  EXPECT_EQ(\"Streamable-PathLike\", Print(x));\n  const ::foo::PathLike cx;\n  EXPECT_EQ(\"Streamable-PathLike\", Print(cx));\n}\n\n// Tests printing user-defined types that have a PrintTo() function.\nTEST(PrintPrintableTypeTest, InUserNamespace) {\n  EXPECT_EQ(\"PrintableViaPrintTo: 0\", Print(::foo::PrintableViaPrintTo()));\n}\n\n// Tests printing a pointer to a user-defined type that has a <<\n// operator for its pointer.\nTEST(PrintPrintableTypeTest, PointerInUserNamespace) {\n  ::foo::PointerPrintable x;\n  EXPECT_EQ(\"PointerPrintable*\", Print(&x));\n}\n\n// Tests printing user-defined class template that have a PrintTo() function.\nTEST(PrintPrintableTypeTest, TemplateInUserNamespace) {\n  EXPECT_EQ(\"PrintableViaPrintToTemplate: 5\",\n            Print(::foo::PrintableViaPrintToTemplate<int>(5)));\n}\n\n// Tests that the universal printer prints both the address and the\n// value of a reference.\nTEST(PrintReferenceTest, PrintsAddressAndValue) {\n  int n = 5;\n  EXPECT_EQ(\"@\" + PrintPointer(&n) + \" 5\", PrintByRef(n));\n\n  int a[2][3] = {{0, 1, 2}, {3, 4, 5}};\n  EXPECT_EQ(\"@\" + PrintPointer(a) + \" { { 0, 1, 2 }, { 3, 4, 5 } }\",\n            PrintByRef(a));\n\n  const ::foo::UnprintableInFoo x;\n  EXPECT_EQ(\"@\" + PrintPointer(&x) +\n                \" 16-byte object \"\n                \"<EF-12 00-00 34-AB 00-00 00-00 00-00 00-00 00-00>\",\n            PrintByRef(x));\n}\n\n// Tests that the universal printer prints a function pointer passed by\n// reference.\nTEST(PrintReferenceTest, HandlesFunctionPointer) {\n  void (*fp)(int n) = &MyFunction;\n  const std::string fp_pointer_string =\n      PrintPointer(reinterpret_cast<const void*>(&fp));\n  // We cannot directly cast &MyFunction to const void* because the\n  // standard disallows casting between pointers to functions and\n  // pointers to objects, and some compilers (e.g. GCC 3.4) enforce\n  // this limitation.\n  const std::string fp_string = PrintPointer(reinterpret_cast<const void*>(\n      reinterpret_cast<internal::BiggestInt>(fp)));\n  EXPECT_EQ(\"@\" + fp_pointer_string + \" \" + fp_string, PrintByRef(fp));\n}\n\n// Tests that the universal printer prints a member function pointer\n// passed by reference.\nTEST(PrintReferenceTest, HandlesMemberFunctionPointer) {\n  int (Foo::*p)(char ch) = &Foo::MyMethod;\n  EXPECT_TRUE(HasPrefix(PrintByRef(p),\n                        \"@\" + PrintPointer(reinterpret_cast<const void*>(&p)) +\n                            \" \" + Print(sizeof(p)) + \"-byte object \"));\n\n  char (Foo::*p2)(int n) = &Foo::MyVirtualMethod;\n  EXPECT_TRUE(HasPrefix(PrintByRef(p2),\n                        \"@\" + PrintPointer(reinterpret_cast<const void*>(&p2)) +\n                            \" \" + Print(sizeof(p2)) + \"-byte object \"));\n}\n\n// Tests that the universal printer prints a member variable pointer\n// passed by reference.\nTEST(PrintReferenceTest, HandlesMemberVariablePointer) {\n  int Foo::*p = &Foo::value;  // NOLINT\n  EXPECT_TRUE(HasPrefix(PrintByRef(p), \"@\" + PrintPointer(&p) + \" \" +\n                                           Print(sizeof(p)) + \"-byte object \"));\n}\n\n// Tests that FormatForComparisonFailureMessage(), which is used to print\n// an operand in a comparison assertion (e.g. ASSERT_EQ) when the assertion\n// fails, formats the operand in the desired way.\n\n// scalar\nTEST(FormatForComparisonFailureMessageTest, WorksForScalar) {\n  EXPECT_STREQ(\"123\", FormatForComparisonFailureMessage(123, 124).c_str());\n}\n\n// non-char pointer\nTEST(FormatForComparisonFailureMessageTest, WorksForNonCharPointer) {\n  int n = 0;\n  EXPECT_EQ(PrintPointer(&n),\n            FormatForComparisonFailureMessage(&n, &n).c_str());\n}\n\n// non-char array\nTEST(FormatForComparisonFailureMessageTest, FormatsNonCharArrayAsPointer) {\n  // In expression 'array == x', 'array' is compared by pointer.\n  // Therefore we want to print an array operand as a pointer.\n  int n[] = {1, 2, 3};\n  EXPECT_EQ(PrintPointer(n), FormatForComparisonFailureMessage(n, n).c_str());\n}\n\n// Tests formatting a char pointer when it's compared with another pointer.\n// In this case we want to print it as a raw pointer, as the comparison is by\n// pointer.\n\n// char pointer vs pointer\nTEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsPointer) {\n  // In expression 'p == x', where 'p' and 'x' are (const or not) char\n  // pointers, the operands are compared by pointer.  Therefore we\n  // want to print 'p' as a pointer instead of a C string (we don't\n  // even know if it's supposed to point to a valid C string).\n\n  // const char*\n  const char* s = \"hello\";\n  EXPECT_EQ(PrintPointer(s), FormatForComparisonFailureMessage(s, s).c_str());\n\n  // char*\n  char ch = 'a';\n  EXPECT_EQ(PrintPointer(&ch),\n            FormatForComparisonFailureMessage(&ch, &ch).c_str());\n}\n\n// wchar_t pointer vs pointer\nTEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsPointer) {\n  // In expression 'p == x', where 'p' and 'x' are (const or not) char\n  // pointers, the operands are compared by pointer.  Therefore we\n  // want to print 'p' as a pointer instead of a wide C string (we don't\n  // even know if it's supposed to point to a valid wide C string).\n\n  // const wchar_t*\n  const wchar_t* s = L\"hello\";\n  EXPECT_EQ(PrintPointer(s), FormatForComparisonFailureMessage(s, s).c_str());\n\n  // wchar_t*\n  wchar_t ch = L'a';\n  EXPECT_EQ(PrintPointer(&ch),\n            FormatForComparisonFailureMessage(&ch, &ch).c_str());\n}\n\n// Tests formatting a char pointer when it's compared to a string object.\n// In this case we want to print the char pointer as a C string.\n\n// char pointer vs std::string\nTEST(FormatForComparisonFailureMessageTest, WorksForCharPointerVsStdString) {\n  const char* s = \"hello \\\"world\";\n  EXPECT_STREQ(\"\\\"hello \\\\\\\"world\\\"\",  // The string content should be escaped.\n               FormatForComparisonFailureMessage(s, ::std::string()).c_str());\n\n  // char*\n  char str[] = \"hi\\1\";\n  char* p = str;\n  EXPECT_STREQ(\"\\\"hi\\\\x1\\\"\",  // The string content should be escaped.\n               FormatForComparisonFailureMessage(p, ::std::string()).c_str());\n}\n\n#if GTEST_HAS_STD_WSTRING\n// wchar_t pointer vs std::wstring\nTEST(FormatForComparisonFailureMessageTest, WorksForWCharPointerVsStdWString) {\n  const wchar_t* s = L\"hi \\\"world\";\n  EXPECT_STREQ(\"L\\\"hi \\\\\\\"world\\\"\",  // The string content should be escaped.\n               FormatForComparisonFailureMessage(s, ::std::wstring()).c_str());\n\n  // wchar_t*\n  wchar_t str[] = L\"hi\\1\";\n  wchar_t* p = str;\n  EXPECT_STREQ(\"L\\\"hi\\\\x1\\\"\",  // The string content should be escaped.\n               FormatForComparisonFailureMessage(p, ::std::wstring()).c_str());\n}\n#endif\n\n// Tests formatting a char array when it's compared with a pointer or array.\n// In this case we want to print the array as a row pointer, as the comparison\n// is by pointer.\n\n// char array vs pointer\nTEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsPointer) {\n  char str[] = \"hi \\\"world\\\"\";\n  char* p = nullptr;\n  EXPECT_EQ(PrintPointer(str),\n            FormatForComparisonFailureMessage(str, p).c_str());\n}\n\n// char array vs char array\nTEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsCharArray) {\n  const char str[] = \"hi \\\"world\\\"\";\n  EXPECT_EQ(PrintPointer(str),\n            FormatForComparisonFailureMessage(str, str).c_str());\n}\n\n// wchar_t array vs pointer\nTEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsPointer) {\n  wchar_t str[] = L\"hi \\\"world\\\"\";\n  wchar_t* p = nullptr;\n  EXPECT_EQ(PrintPointer(str),\n            FormatForComparisonFailureMessage(str, p).c_str());\n}\n\n// wchar_t array vs wchar_t array\nTEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsWCharArray) {\n  const wchar_t str[] = L\"hi \\\"world\\\"\";\n  EXPECT_EQ(PrintPointer(str),\n            FormatForComparisonFailureMessage(str, str).c_str());\n}\n\n// Tests formatting a char array when it's compared with a string object.\n// In this case we want to print the array as a C string.\n\n// char array vs std::string\nTEST(FormatForComparisonFailureMessageTest, WorksForCharArrayVsStdString) {\n  const char str[] = \"hi \\\"world\\\"\";\n  EXPECT_STREQ(\"\\\"hi \\\\\\\"world\\\\\\\"\\\"\",  // The content should be escaped.\n               FormatForComparisonFailureMessage(str, ::std::string()).c_str());\n}\n\n#if GTEST_HAS_STD_WSTRING\n// wchar_t array vs std::wstring\nTEST(FormatForComparisonFailureMessageTest, WorksForWCharArrayVsStdWString) {\n  const wchar_t str[] = L\"hi \\\"w\\0rld\\\"\";\n  EXPECT_STREQ(\n      \"L\\\"hi \\\\\\\"w\\\"\",  // The content should be escaped.\n                        // Embedded NUL terminates the string.\n      FormatForComparisonFailureMessage(str, ::std::wstring()).c_str());\n}\n#endif\n\n// Useful for testing PrintToString().  We cannot use EXPECT_EQ()\n// there as its implementation uses PrintToString().  The caller must\n// ensure that 'value' has no side effect.\n#define EXPECT_PRINT_TO_STRING_(value, expected_string)  \\\n  EXPECT_TRUE(PrintToString(value) == (expected_string)) \\\n      << \" where \" #value \" prints as \" << (PrintToString(value))\n\nTEST(PrintToStringTest, WorksForScalar) { EXPECT_PRINT_TO_STRING_(123, \"123\"); }\n\nTEST(PrintToStringTest, WorksForPointerToConstChar) {\n  const char* p = \"hello\";\n  EXPECT_PRINT_TO_STRING_(p, \"\\\"hello\\\"\");\n}\n\nTEST(PrintToStringTest, WorksForPointerToNonConstChar) {\n  char s[] = \"hello\";\n  char* p = s;\n  EXPECT_PRINT_TO_STRING_(p, \"\\\"hello\\\"\");\n}\n\nTEST(PrintToStringTest, EscapesForPointerToConstChar) {\n  const char* p = \"hello\\n\";\n  EXPECT_PRINT_TO_STRING_(p, \"\\\"hello\\\\n\\\"\");\n}\n\nTEST(PrintToStringTest, EscapesForPointerToNonConstChar) {\n  char s[] = \"hello\\1\";\n  char* p = s;\n  EXPECT_PRINT_TO_STRING_(p, \"\\\"hello\\\\x1\\\"\");\n}\n\nTEST(PrintToStringTest, WorksForArray) {\n  int n[3] = {1, 2, 3};\n  EXPECT_PRINT_TO_STRING_(n, \"{ 1, 2, 3 }\");\n}\n\nTEST(PrintToStringTest, WorksForCharArray) {\n  char s[] = \"hello\";\n  EXPECT_PRINT_TO_STRING_(s, \"\\\"hello\\\"\");\n}\n\nTEST(PrintToStringTest, WorksForCharArrayWithEmbeddedNul) {\n  const char str_with_nul[] = \"hello\\0 world\";\n  EXPECT_PRINT_TO_STRING_(str_with_nul, \"\\\"hello\\\\0 world\\\"\");\n\n  char mutable_str_with_nul[] = \"hello\\0 world\";\n  EXPECT_PRINT_TO_STRING_(mutable_str_with_nul, \"\\\"hello\\\\0 world\\\"\");\n}\n\nTEST(PrintToStringTest, ContainsNonLatin) {\n  // Test with valid UTF-8. Prints both in hex and as text.\n  std::string non_ascii_str = ::std::string(\"오전 4:30\");\n  EXPECT_PRINT_TO_STRING_(non_ascii_str,\n                          \"\\\"\\\\xEC\\\\x98\\\\xA4\\\\xEC\\\\xA0\\\\x84 4:30\\\"\\n\"\n                          \"    As Text: \\\"오전 4:30\\\"\");\n  non_ascii_str = ::std::string(\"From ä — ẑ\");\n  EXPECT_PRINT_TO_STRING_(non_ascii_str,\n                          \"\\\"From \\\\xC3\\\\xA4 \\\\xE2\\\\x80\\\\x94 \\\\xE1\\\\xBA\\\\x91\\\"\"\n                          \"\\n    As Text: \\\"From ä — ẑ\\\"\");\n}\n\nTEST(IsValidUTF8Test, IllFormedUTF8) {\n  // The following test strings are ill-formed UTF-8 and are printed\n  // as hex only (or ASCII, in case of ASCII bytes) because IsValidUTF8() is\n  // expected to fail, thus output does not contain \"As Text:\".\n\n  static const char* const kTestdata[][2] = {\n      // 2-byte lead byte followed by a single-byte character.\n      {\"\\xC3\\x74\", \"\\\"\\\\xC3t\\\"\"},\n      // Valid 2-byte character followed by an orphan trail byte.\n      {\"\\xC3\\x84\\xA4\", \"\\\"\\\\xC3\\\\x84\\\\xA4\\\"\"},\n      // Lead byte without trail byte.\n      {\"abc\\xC3\", \"\\\"abc\\\\xC3\\\"\"},\n      // 3-byte lead byte, single-byte character, orphan trail byte.\n      {\"x\\xE2\\x70\\x94\", \"\\\"x\\\\xE2p\\\\x94\\\"\"},\n      // Truncated 3-byte character.\n      {\"\\xE2\\x80\", \"\\\"\\\\xE2\\\\x80\\\"\"},\n      // Truncated 3-byte character followed by valid 2-byte char.\n      {\"\\xE2\\x80\\xC3\\x84\", \"\\\"\\\\xE2\\\\x80\\\\xC3\\\\x84\\\"\"},\n      // Truncated 3-byte character followed by a single-byte character.\n      {\"\\xE2\\x80\\x7A\", \"\\\"\\\\xE2\\\\x80z\\\"\"},\n      // 3-byte lead byte followed by valid 3-byte character.\n      {\"\\xE2\\xE2\\x80\\x94\", \"\\\"\\\\xE2\\\\xE2\\\\x80\\\\x94\\\"\"},\n      // 4-byte lead byte followed by valid 3-byte character.\n      {\"\\xF0\\xE2\\x80\\x94\", \"\\\"\\\\xF0\\\\xE2\\\\x80\\\\x94\\\"\"},\n      // Truncated 4-byte character.\n      {\"\\xF0\\xE2\\x80\", \"\\\"\\\\xF0\\\\xE2\\\\x80\\\"\"},\n      // Invalid UTF-8 byte sequences embedded in other chars.\n      {\"abc\\xE2\\x80\\x94\\xC3\\x74xyc\", \"\\\"abc\\\\xE2\\\\x80\\\\x94\\\\xC3txyc\\\"\"},\n      {\"abc\\xC3\\x84\\xE2\\x80\\xC3\\x84xyz\",\n       \"\\\"abc\\\\xC3\\\\x84\\\\xE2\\\\x80\\\\xC3\\\\x84xyz\\\"\"},\n      // Non-shortest UTF-8 byte sequences are also ill-formed.\n      // The classics: xC0, xC1 lead byte.\n      {\"\\xC0\\x80\", \"\\\"\\\\xC0\\\\x80\\\"\"},\n      {\"\\xC1\\x81\", \"\\\"\\\\xC1\\\\x81\\\"\"},\n      // Non-shortest sequences.\n      {\"\\xE0\\x80\\x80\", \"\\\"\\\\xE0\\\\x80\\\\x80\\\"\"},\n      {\"\\xf0\\x80\\x80\\x80\", \"\\\"\\\\xF0\\\\x80\\\\x80\\\\x80\\\"\"},\n      // Last valid code point before surrogate range, should be printed as\n      // text,\n      // too.\n      {\"\\xED\\x9F\\xBF\", \"\\\"\\\\xED\\\\x9F\\\\xBF\\\"\\n    As Text: \\\"퟿\\\"\"},\n      // Start of surrogate lead. Surrogates are not printed as text.\n      {\"\\xED\\xA0\\x80\", \"\\\"\\\\xED\\\\xA0\\\\x80\\\"\"},\n      // Last non-private surrogate lead.\n      {\"\\xED\\xAD\\xBF\", \"\\\"\\\\xED\\\\xAD\\\\xBF\\\"\"},\n      // First private-use surrogate lead.\n      {\"\\xED\\xAE\\x80\", \"\\\"\\\\xED\\\\xAE\\\\x80\\\"\"},\n      // Last private-use surrogate lead.\n      {\"\\xED\\xAF\\xBF\", \"\\\"\\\\xED\\\\xAF\\\\xBF\\\"\"},\n      // Mid-point of surrogate trail.\n      {\"\\xED\\xB3\\xBF\", \"\\\"\\\\xED\\\\xB3\\\\xBF\\\"\"},\n      // First valid code point after surrogate range, should be printed as\n      // text,\n      // too.\n      {\"\\xEE\\x80\\x80\", \"\\\"\\\\xEE\\\\x80\\\\x80\\\"\\n    As Text: \\\"\\\"\"}};\n\n  for (int i = 0; i < int(sizeof(kTestdata) / sizeof(kTestdata[0])); ++i) {\n    EXPECT_PRINT_TO_STRING_(kTestdata[i][0], kTestdata[i][1]);\n  }\n}\n\n#undef EXPECT_PRINT_TO_STRING_\n\nTEST(UniversalTersePrintTest, WorksForNonReference) {\n  ::std::stringstream ss;\n  UniversalTersePrint(123, &ss);\n  EXPECT_EQ(\"123\", ss.str());\n}\n\nTEST(UniversalTersePrintTest, WorksForReference) {\n  const int& n = 123;\n  ::std::stringstream ss;\n  UniversalTersePrint(n, &ss);\n  EXPECT_EQ(\"123\", ss.str());\n}\n\nTEST(UniversalTersePrintTest, WorksForCString) {\n  const char* s1 = \"abc\";\n  ::std::stringstream ss1;\n  UniversalTersePrint(s1, &ss1);\n  EXPECT_EQ(\"\\\"abc\\\"\", ss1.str());\n\n  char* s2 = const_cast<char*>(s1);\n  ::std::stringstream ss2;\n  UniversalTersePrint(s2, &ss2);\n  EXPECT_EQ(\"\\\"abc\\\"\", ss2.str());\n\n  const char* s3 = nullptr;\n  ::std::stringstream ss3;\n  UniversalTersePrint(s3, &ss3);\n  EXPECT_EQ(\"NULL\", ss3.str());\n}\n\nTEST(UniversalPrintTest, WorksForNonReference) {\n  ::std::stringstream ss;\n  UniversalPrint(123, &ss);\n  EXPECT_EQ(\"123\", ss.str());\n}\n\nTEST(UniversalPrintTest, WorksForReference) {\n  const int& n = 123;\n  ::std::stringstream ss;\n  UniversalPrint(n, &ss);\n  EXPECT_EQ(\"123\", ss.str());\n}\n\nTEST(UniversalPrintTest, WorksForPairWithConst) {\n  std::pair<const Wrapper<std::string>, int> p(Wrapper<std::string>(\"abc\"), 1);\n  ::std::stringstream ss;\n  UniversalPrint(p, &ss);\n  EXPECT_EQ(\"(Wrapper(\\\"abc\\\"), 1)\", ss.str());\n}\n\nTEST(UniversalPrintTest, WorksForCString) {\n  const char* s1 = \"abc\";\n  ::std::stringstream ss1;\n  UniversalPrint(s1, &ss1);\n  EXPECT_EQ(PrintPointer(s1) + \" pointing to \\\"abc\\\"\", std::string(ss1.str()));\n\n  char* s2 = const_cast<char*>(s1);\n  ::std::stringstream ss2;\n  UniversalPrint(s2, &ss2);\n  EXPECT_EQ(PrintPointer(s2) + \" pointing to \\\"abc\\\"\", std::string(ss2.str()));\n\n  const char* s3 = nullptr;\n  ::std::stringstream ss3;\n  UniversalPrint(s3, &ss3);\n  EXPECT_EQ(\"NULL\", ss3.str());\n}\n\nTEST(UniversalPrintTest, WorksForCharArray) {\n  const char str[] = \"\\\"Line\\0 1\\\"\\nLine 2\";\n  ::std::stringstream ss1;\n  UniversalPrint(str, &ss1);\n  EXPECT_EQ(\"\\\"\\\\\\\"Line\\\\0 1\\\\\\\"\\\\nLine 2\\\"\", ss1.str());\n\n  const char mutable_str[] = \"\\\"Line\\0 1\\\"\\nLine 2\";\n  ::std::stringstream ss2;\n  UniversalPrint(mutable_str, &ss2);\n  EXPECT_EQ(\"\\\"\\\\\\\"Line\\\\0 1\\\\\\\"\\\\nLine 2\\\"\", ss2.str());\n}\n\nTEST(UniversalPrintTest, IncompleteType) {\n  struct Incomplete;\n  char some_object = 0;\n  EXPECT_EQ(\"(incomplete type)\",\n            PrintToString(reinterpret_cast<Incomplete&>(some_object)));\n}\n\nTEST(UniversalPrintTest, SmartPointers) {\n  EXPECT_EQ(\"(nullptr)\", PrintToString(std::unique_ptr<int>()));\n  std::unique_ptr<int> p(new int(17));\n  EXPECT_EQ(\"(ptr = \" + PrintPointer(p.get()) + \", value = 17)\",\n            PrintToString(p));\n  std::unique_ptr<int[]> p2(new int[2]);\n  EXPECT_EQ(\"(\" + PrintPointer(p2.get()) + \")\", PrintToString(p2));\n\n  EXPECT_EQ(\"(nullptr)\", PrintToString(std::shared_ptr<int>()));\n  std::shared_ptr<int> p3(new int(1979));\n  EXPECT_EQ(\"(ptr = \" + PrintPointer(p3.get()) + \", value = 1979)\",\n            PrintToString(p3));\n#if __cpp_lib_shared_ptr_arrays >= 201611L\n  std::shared_ptr<int[]> p4(new int[2]);\n  EXPECT_EQ(\"(\" + PrintPointer(p4.get()) + \")\", PrintToString(p4));\n#endif\n\n  // modifiers\n  EXPECT_EQ(\"(nullptr)\", PrintToString(std::unique_ptr<int>()));\n  EXPECT_EQ(\"(nullptr)\", PrintToString(std::unique_ptr<const int>()));\n  EXPECT_EQ(\"(nullptr)\", PrintToString(std::unique_ptr<volatile int>()));\n  EXPECT_EQ(\"(nullptr)\", PrintToString(std::unique_ptr<volatile const int>()));\n  EXPECT_EQ(\"(nullptr)\", PrintToString(std::unique_ptr<int[]>()));\n  EXPECT_EQ(\"(nullptr)\", PrintToString(std::unique_ptr<const int[]>()));\n  EXPECT_EQ(\"(nullptr)\", PrintToString(std::unique_ptr<volatile int[]>()));\n  EXPECT_EQ(\"(nullptr)\",\n            PrintToString(std::unique_ptr<volatile const int[]>()));\n  EXPECT_EQ(\"(nullptr)\", PrintToString(std::shared_ptr<int>()));\n  EXPECT_EQ(\"(nullptr)\", PrintToString(std::shared_ptr<const int>()));\n  EXPECT_EQ(\"(nullptr)\", PrintToString(std::shared_ptr<volatile int>()));\n  EXPECT_EQ(\"(nullptr)\", PrintToString(std::shared_ptr<volatile const int>()));\n#if __cpp_lib_shared_ptr_arrays >= 201611L\n  EXPECT_EQ(\"(nullptr)\", PrintToString(std::shared_ptr<int[]>()));\n  EXPECT_EQ(\"(nullptr)\", PrintToString(std::shared_ptr<const int[]>()));\n  EXPECT_EQ(\"(nullptr)\", PrintToString(std::shared_ptr<volatile int[]>()));\n  EXPECT_EQ(\"(nullptr)\",\n            PrintToString(std::shared_ptr<volatile const int[]>()));\n#endif\n\n  // void\n  EXPECT_EQ(\"(nullptr)\", PrintToString(std::unique_ptr<void, void (*)(void*)>(\n                             nullptr, nullptr)));\n  EXPECT_EQ(\"(\" + PrintPointer(p.get()) + \")\",\n            PrintToString(\n                std::unique_ptr<void, void (*)(void*)>(p.get(), [](void*) {})));\n  EXPECT_EQ(\"(nullptr)\", PrintToString(std::shared_ptr<void>()));\n  EXPECT_EQ(\"(\" + PrintPointer(p.get()) + \")\",\n            PrintToString(std::shared_ptr<void>(p.get(), [](void*) {})));\n}\n\nTEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsEmptyTuple) {\n  Strings result = UniversalTersePrintTupleFieldsToStrings(::std::make_tuple());\n  EXPECT_EQ(0u, result.size());\n}\n\nTEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsOneTuple) {\n  Strings result =\n      UniversalTersePrintTupleFieldsToStrings(::std::make_tuple(1));\n  ASSERT_EQ(1u, result.size());\n  EXPECT_EQ(\"1\", result[0]);\n}\n\nTEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTwoTuple) {\n  Strings result =\n      UniversalTersePrintTupleFieldsToStrings(::std::make_tuple(1, 'a'));\n  ASSERT_EQ(2u, result.size());\n  EXPECT_EQ(\"1\", result[0]);\n  EXPECT_EQ(\"'a' (97, 0x61)\", result[1]);\n}\n\nTEST(UniversalTersePrintTupleFieldsToStringsTestWithStd, PrintsTersely) {\n  const int n = 1;\n  Strings result = UniversalTersePrintTupleFieldsToStrings(\n      ::std::tuple<const int&, const char*>(n, \"a\"));\n  ASSERT_EQ(2u, result.size());\n  EXPECT_EQ(\"1\", result[0]);\n  EXPECT_EQ(\"\\\"a\\\"\", result[1]);\n}\n\n#if GTEST_INTERNAL_HAS_ANY\nclass PrintAnyTest : public ::testing::Test {\n protected:\n  template <typename T>\n  static std::string ExpectedTypeName() {\n#if GTEST_HAS_RTTI\n    return internal::GetTypeName<T>();\n#else\n    return \"<unknown_type>\";\n#endif  // GTEST_HAS_RTTI\n  }\n};\n\nTEST_F(PrintAnyTest, Empty) {\n  internal::Any any;\n  EXPECT_EQ(\"no value\", PrintToString(any));\n}\n\nTEST_F(PrintAnyTest, NonEmpty) {\n  internal::Any any;\n  constexpr int val1 = 10;\n  const std::string val2 = \"content\";\n\n  any = val1;\n  EXPECT_EQ(\"value of type \" + ExpectedTypeName<int>(), PrintToString(any));\n\n  any = val2;\n  EXPECT_EQ(\"value of type \" + ExpectedTypeName<std::string>(),\n            PrintToString(any));\n}\n#endif  // GTEST_INTERNAL_HAS_ANY\n\n#if GTEST_INTERNAL_HAS_OPTIONAL\nTEST(PrintOptionalTest, Basic) {\n  EXPECT_EQ(\"(nullopt)\", PrintToString(internal::Nullopt()));\n  internal::Optional<int> value;\n  EXPECT_EQ(\"(nullopt)\", PrintToString(value));\n  value = {7};\n  EXPECT_EQ(\"(7)\", PrintToString(value));\n  EXPECT_EQ(\"(1.1)\", PrintToString(internal::Optional<double>{1.1}));\n  EXPECT_EQ(\"(\\\"A\\\")\", PrintToString(internal::Optional<std::string>{\"A\"}));\n}\n#endif  // GTEST_INTERNAL_HAS_OPTIONAL\n\n#if GTEST_INTERNAL_HAS_VARIANT\nstruct NonPrintable {\n  unsigned char contents = 17;\n};\n\nTEST(PrintOneofTest, Basic) {\n  using Type = internal::Variant<int, StreamableInGlobal, NonPrintable>;\n  EXPECT_EQ(\"('int(index = 0)' with value 7)\", PrintToString(Type(7)));\n  EXPECT_EQ(\"('StreamableInGlobal(index = 1)' with value StreamableInGlobal)\",\n            PrintToString(Type(StreamableInGlobal{})));\n  EXPECT_EQ(\n      \"('testing::gtest_printers_test::NonPrintable(index = 2)' with value \"\n      \"1-byte object <11>)\",\n      PrintToString(Type(NonPrintable{})));\n}\n#endif  // GTEST_INTERNAL_HAS_VARIANT\nnamespace {\nclass string_ref;\n\n/**\n * This is a synthetic pointer to a fixed size string.\n */\nclass string_ptr {\n public:\n  string_ptr(const char* data, size_t size) : data_(data), size_(size) {}\n\n  string_ptr& operator++() noexcept {\n    data_ += size_;\n    return *this;\n  }\n\n  string_ref operator*() const noexcept;\n\n private:\n  const char* data_;\n  size_t size_;\n};\n\n/**\n * This is a synthetic reference of a fixed size string.\n */\nclass string_ref {\n public:\n  string_ref(const char* data, size_t size) : data_(data), size_(size) {}\n\n  string_ptr operator&() const noexcept { return {data_, size_}; }  // NOLINT\n\n  bool operator==(const char* s) const noexcept {\n    if (size_ > 0 && data_[size_ - 1] != 0) {\n      return std::string(data_, size_) == std::string(s);\n    } else {\n      return std::string(data_) == std::string(s);\n    }\n  }\n\n private:\n  const char* data_;\n  size_t size_;\n};\n\nstring_ref string_ptr::operator*() const noexcept { return {data_, size_}; }\n\nTEST(string_ref, compare) {\n  const char* s = \"alex\\0davidjohn\\0\";\n  string_ptr ptr(s, 5);\n  EXPECT_EQ(*ptr, \"alex\");\n  EXPECT_TRUE(*ptr == \"alex\");\n  ++ptr;\n  EXPECT_EQ(*ptr, \"david\");\n  EXPECT_TRUE(*ptr == \"david\");\n  ++ptr;\n  EXPECT_EQ(*ptr, \"john\");\n}\n\n}  // namespace\n\n}  // namespace gtest_printers_test\n}  // namespace testing\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-setuptestsuite-test.py",
    "content": "#!/usr/bin/env python\n#\n# Copyright 2019, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Verifies that SetUpTestSuite and TearDownTestSuite errors are noticed.\"\"\"\n\nfrom googletest.test import gtest_test_utils\n\nCOMMAND = gtest_test_utils.GetTestExecutablePath(\n    'googletest-setuptestsuite-test_')\n\n\nclass GTestSetUpTestSuiteTest(gtest_test_utils.TestCase):\n\n  def testSetupErrorAndTearDownError(self):\n    p = gtest_test_utils.Subprocess(COMMAND)\n    self.assertNotEqual(p.exit_code, 0, msg=p.output)\n\n    self.assertIn(\n        '[  FAILED  ] SetupFailTest: SetUpTestSuite or TearDownTestSuite\\n'\n        '[  FAILED  ] TearDownFailTest: SetUpTestSuite or TearDownTestSuite\\n'\n        '\\n'\n        ' 2 FAILED TEST SUITES\\n',\n        p.output)\n\nif __name__ == '__main__':\n  gtest_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-setuptestsuite-test_.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"gtest/gtest.h\"\n\nclass SetupFailTest : public ::testing::Test {\n protected:\n  static void SetUpTestSuite() { ASSERT_EQ(\"\", \"SET_UP_FAIL\"); }\n};\n\nTEST_F(SetupFailTest, NoopPassingTest) {}\n\nclass TearDownFailTest : public ::testing::Test {\n protected:\n  static void TearDownTestSuite() { ASSERT_EQ(\"\", \"TEAR_DOWN_FAIL\"); }\n};\n\nTEST_F(TearDownFailTest, NoopPassingTest) {}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-shuffle-test.py",
    "content": "#!/usr/bin/env python\n#\n# Copyright 2009 Google Inc. All Rights Reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Verifies that test shuffling works.\"\"\"\n\nimport os\nfrom googletest.test import gtest_test_utils\n\n# Command to run the googletest-shuffle-test_ program.\nCOMMAND = gtest_test_utils.GetTestExecutablePath('googletest-shuffle-test_')\n\n# The environment variables for test sharding.\nTOTAL_SHARDS_ENV_VAR = 'GTEST_TOTAL_SHARDS'\nSHARD_INDEX_ENV_VAR = 'GTEST_SHARD_INDEX'\n\nTEST_FILTER = 'A*.A:A*.B:C*'\n\nALL_TESTS = []\nACTIVE_TESTS = []\nFILTERED_TESTS = []\nSHARDED_TESTS = []\n\nSHUFFLED_ALL_TESTS = []\nSHUFFLED_ACTIVE_TESTS = []\nSHUFFLED_FILTERED_TESTS = []\nSHUFFLED_SHARDED_TESTS = []\n\n\ndef AlsoRunDisabledTestsFlag():\n  return '--gtest_also_run_disabled_tests'\n\n\ndef FilterFlag(test_filter):\n  return '--gtest_filter=%s' % (test_filter,)\n\n\ndef RepeatFlag(n):\n  return '--gtest_repeat=%s' % (n,)\n\n\ndef ShuffleFlag():\n  return '--gtest_shuffle'\n\n\ndef RandomSeedFlag(n):\n  return '--gtest_random_seed=%s' % (n,)\n\n\ndef RunAndReturnOutput(extra_env, args):\n  \"\"\"Runs the test program and returns its output.\"\"\"\n\n  environ_copy = os.environ.copy()\n  environ_copy.update(extra_env)\n\n  return gtest_test_utils.Subprocess([COMMAND] + args, env=environ_copy).output\n\n\ndef GetTestsForAllIterations(extra_env, args):\n  \"\"\"Runs the test program and returns a list of test lists.\n\n  Args:\n    extra_env: a map from environment variables to their values\n    args: command line flags to pass to googletest-shuffle-test_\n\n  Returns:\n    A list where the i-th element is the list of tests run in the i-th\n    test iteration.\n  \"\"\"\n\n  test_iterations = []\n  for line in RunAndReturnOutput(extra_env, args).split('\\n'):\n    if line.startswith('----'):\n      tests = []\n      test_iterations.append(tests)\n    elif line.strip():\n      tests.append(line.strip())  # 'TestCaseName.TestName'\n\n  return test_iterations\n\n\ndef GetTestCases(tests):\n  \"\"\"Returns a list of test cases in the given full test names.\n\n  Args:\n    tests: a list of full test names\n\n  Returns:\n    A list of test cases from 'tests', in their original order.\n    Consecutive duplicates are removed.\n  \"\"\"\n\n  test_cases = []\n  for test in tests:\n    test_case = test.split('.')[0]\n    if not test_case in test_cases:\n      test_cases.append(test_case)\n\n  return test_cases\n\n\ndef CalculateTestLists():\n  \"\"\"Calculates the list of tests run under different flags.\"\"\"\n\n  if not ALL_TESTS:\n    ALL_TESTS.extend(\n        GetTestsForAllIterations({}, [AlsoRunDisabledTestsFlag()])[0])\n\n  if not ACTIVE_TESTS:\n    ACTIVE_TESTS.extend(GetTestsForAllIterations({}, [])[0])\n\n  if not FILTERED_TESTS:\n    FILTERED_TESTS.extend(\n        GetTestsForAllIterations({}, [FilterFlag(TEST_FILTER)])[0])\n\n  if not SHARDED_TESTS:\n    SHARDED_TESTS.extend(\n        GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',\n                                  SHARD_INDEX_ENV_VAR: '1'},\n                                 [])[0])\n\n  if not SHUFFLED_ALL_TESTS:\n    SHUFFLED_ALL_TESTS.extend(GetTestsForAllIterations(\n        {}, [AlsoRunDisabledTestsFlag(), ShuffleFlag(), RandomSeedFlag(1)])[0])\n\n  if not SHUFFLED_ACTIVE_TESTS:\n    SHUFFLED_ACTIVE_TESTS.extend(GetTestsForAllIterations(\n        {}, [ShuffleFlag(), RandomSeedFlag(1)])[0])\n\n  if not SHUFFLED_FILTERED_TESTS:\n    SHUFFLED_FILTERED_TESTS.extend(GetTestsForAllIterations(\n        {}, [ShuffleFlag(), RandomSeedFlag(1), FilterFlag(TEST_FILTER)])[0])\n\n  if not SHUFFLED_SHARDED_TESTS:\n    SHUFFLED_SHARDED_TESTS.extend(\n        GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',\n                                  SHARD_INDEX_ENV_VAR: '1'},\n                                 [ShuffleFlag(), RandomSeedFlag(1)])[0])\n\n\nclass GTestShuffleUnitTest(gtest_test_utils.TestCase):\n  \"\"\"Tests test shuffling.\"\"\"\n\n  def setUp(self):\n    CalculateTestLists()\n\n  def testShufflePreservesNumberOfTests(self):\n    self.assertEqual(len(ALL_TESTS), len(SHUFFLED_ALL_TESTS))\n    self.assertEqual(len(ACTIVE_TESTS), len(SHUFFLED_ACTIVE_TESTS))\n    self.assertEqual(len(FILTERED_TESTS), len(SHUFFLED_FILTERED_TESTS))\n    self.assertEqual(len(SHARDED_TESTS), len(SHUFFLED_SHARDED_TESTS))\n\n  def testShuffleChangesTestOrder(self):\n    self.assert_(SHUFFLED_ALL_TESTS != ALL_TESTS, SHUFFLED_ALL_TESTS)\n    self.assert_(SHUFFLED_ACTIVE_TESTS != ACTIVE_TESTS, SHUFFLED_ACTIVE_TESTS)\n    self.assert_(SHUFFLED_FILTERED_TESTS != FILTERED_TESTS,\n                 SHUFFLED_FILTERED_TESTS)\n    self.assert_(SHUFFLED_SHARDED_TESTS != SHARDED_TESTS,\n                 SHUFFLED_SHARDED_TESTS)\n\n  def testShuffleChangesTestCaseOrder(self):\n    self.assert_(GetTestCases(SHUFFLED_ALL_TESTS) != GetTestCases(ALL_TESTS),\n                 GetTestCases(SHUFFLED_ALL_TESTS))\n    self.assert_(\n        GetTestCases(SHUFFLED_ACTIVE_TESTS) != GetTestCases(ACTIVE_TESTS),\n        GetTestCases(SHUFFLED_ACTIVE_TESTS))\n    self.assert_(\n        GetTestCases(SHUFFLED_FILTERED_TESTS) != GetTestCases(FILTERED_TESTS),\n        GetTestCases(SHUFFLED_FILTERED_TESTS))\n    self.assert_(\n        GetTestCases(SHUFFLED_SHARDED_TESTS) != GetTestCases(SHARDED_TESTS),\n        GetTestCases(SHUFFLED_SHARDED_TESTS))\n\n  def testShuffleDoesNotRepeatTest(self):\n    for test in SHUFFLED_ALL_TESTS:\n      self.assertEqual(1, SHUFFLED_ALL_TESTS.count(test),\n                       '%s appears more than once' % (test,))\n    for test in SHUFFLED_ACTIVE_TESTS:\n      self.assertEqual(1, SHUFFLED_ACTIVE_TESTS.count(test),\n                       '%s appears more than once' % (test,))\n    for test in SHUFFLED_FILTERED_TESTS:\n      self.assertEqual(1, SHUFFLED_FILTERED_TESTS.count(test),\n                       '%s appears more than once' % (test,))\n    for test in SHUFFLED_SHARDED_TESTS:\n      self.assertEqual(1, SHUFFLED_SHARDED_TESTS.count(test),\n                       '%s appears more than once' % (test,))\n\n  def testShuffleDoesNotCreateNewTest(self):\n    for test in SHUFFLED_ALL_TESTS:\n      self.assert_(test in ALL_TESTS, '%s is an invalid test' % (test,))\n    for test in SHUFFLED_ACTIVE_TESTS:\n      self.assert_(test in ACTIVE_TESTS, '%s is an invalid test' % (test,))\n    for test in SHUFFLED_FILTERED_TESTS:\n      self.assert_(test in FILTERED_TESTS, '%s is an invalid test' % (test,))\n    for test in SHUFFLED_SHARDED_TESTS:\n      self.assert_(test in SHARDED_TESTS, '%s is an invalid test' % (test,))\n\n  def testShuffleIncludesAllTests(self):\n    for test in ALL_TESTS:\n      self.assert_(test in SHUFFLED_ALL_TESTS, '%s is missing' % (test,))\n    for test in ACTIVE_TESTS:\n      self.assert_(test in SHUFFLED_ACTIVE_TESTS, '%s is missing' % (test,))\n    for test in FILTERED_TESTS:\n      self.assert_(test in SHUFFLED_FILTERED_TESTS, '%s is missing' % (test,))\n    for test in SHARDED_TESTS:\n      self.assert_(test in SHUFFLED_SHARDED_TESTS, '%s is missing' % (test,))\n\n  def testShuffleLeavesDeathTestsAtFront(self):\n    non_death_test_found = False\n    for test in SHUFFLED_ACTIVE_TESTS:\n      if 'DeathTest.' in test:\n        self.assert_(not non_death_test_found,\n                     '%s appears after a non-death test' % (test,))\n      else:\n        non_death_test_found = True\n\n  def _VerifyTestCasesDoNotInterleave(self, tests):\n    test_cases = []\n    for test in tests:\n      [test_case, _] = test.split('.')\n      if test_cases and test_cases[-1] != test_case:\n        test_cases.append(test_case)\n        self.assertEqual(1, test_cases.count(test_case),\n                         'Test case %s is not grouped together in %s' %\n                         (test_case, tests))\n\n  def testShuffleDoesNotInterleaveTestCases(self):\n    self._VerifyTestCasesDoNotInterleave(SHUFFLED_ALL_TESTS)\n    self._VerifyTestCasesDoNotInterleave(SHUFFLED_ACTIVE_TESTS)\n    self._VerifyTestCasesDoNotInterleave(SHUFFLED_FILTERED_TESTS)\n    self._VerifyTestCasesDoNotInterleave(SHUFFLED_SHARDED_TESTS)\n\n  def testShuffleRestoresOrderAfterEachIteration(self):\n    # Get the test lists in all 3 iterations, using random seed 1, 2,\n    # and 3 respectively.  Google Test picks a different seed in each\n    # iteration, and this test depends on the current implementation\n    # picking successive numbers.  This dependency is not ideal, but\n    # makes the test much easier to write.\n    [tests_in_iteration1, tests_in_iteration2, tests_in_iteration3] = (\n        GetTestsForAllIterations(\n            {}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)]))\n\n    # Make sure running the tests with random seed 1 gets the same\n    # order as in iteration 1 above.\n    [tests_with_seed1] = GetTestsForAllIterations(\n        {}, [ShuffleFlag(), RandomSeedFlag(1)])\n    self.assertEqual(tests_in_iteration1, tests_with_seed1)\n\n    # Make sure running the tests with random seed 2 gets the same\n    # order as in iteration 2 above.  Success means that Google Test\n    # correctly restores the test order before re-shuffling at the\n    # beginning of iteration 2.\n    [tests_with_seed2] = GetTestsForAllIterations(\n        {}, [ShuffleFlag(), RandomSeedFlag(2)])\n    self.assertEqual(tests_in_iteration2, tests_with_seed2)\n\n    # Make sure running the tests with random seed 3 gets the same\n    # order as in iteration 3 above.  Success means that Google Test\n    # correctly restores the test order before re-shuffling at the\n    # beginning of iteration 3.\n    [tests_with_seed3] = GetTestsForAllIterations(\n        {}, [ShuffleFlag(), RandomSeedFlag(3)])\n    self.assertEqual(tests_in_iteration3, tests_with_seed3)\n\n  def testShuffleGeneratesNewOrderInEachIteration(self):\n    [tests_in_iteration1, tests_in_iteration2, tests_in_iteration3] = (\n        GetTestsForAllIterations(\n            {}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)]))\n\n    self.assert_(tests_in_iteration1 != tests_in_iteration2,\n                 tests_in_iteration1)\n    self.assert_(tests_in_iteration1 != tests_in_iteration3,\n                 tests_in_iteration1)\n    self.assert_(tests_in_iteration2 != tests_in_iteration3,\n                 tests_in_iteration2)\n\n  def testShuffleShardedTestsPreservesPartition(self):\n    # If we run M tests on N shards, the same M tests should be run in\n    # total, regardless of the random seeds used by the shards.\n    [tests1] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',\n                                         SHARD_INDEX_ENV_VAR: '0'},\n                                        [ShuffleFlag(), RandomSeedFlag(1)])\n    [tests2] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',\n                                         SHARD_INDEX_ENV_VAR: '1'},\n                                        [ShuffleFlag(), RandomSeedFlag(20)])\n    [tests3] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3',\n                                         SHARD_INDEX_ENV_VAR: '2'},\n                                        [ShuffleFlag(), RandomSeedFlag(25)])\n    sorted_sharded_tests = tests1 + tests2 + tests3\n    sorted_sharded_tests.sort()\n    sorted_active_tests = []\n    sorted_active_tests.extend(ACTIVE_TESTS)\n    sorted_active_tests.sort()\n    self.assertEqual(sorted_active_tests, sorted_sharded_tests)\n\nif __name__ == '__main__':\n  gtest_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-shuffle-test_.cc",
    "content": "// Copyright 2009, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Verifies that test shuffling works.\n\n#include \"gtest/gtest.h\"\n\nnamespace {\n\nusing ::testing::EmptyTestEventListener;\nusing ::testing::InitGoogleTest;\nusing ::testing::Message;\nusing ::testing::Test;\nusing ::testing::TestEventListeners;\nusing ::testing::TestInfo;\nusing ::testing::UnitTest;\n\n// The test methods are empty, as the sole purpose of this program is\n// to print the test names before/after shuffling.\n\nclass A : public Test {};\nTEST_F(A, A) {}\nTEST_F(A, B) {}\n\nTEST(ADeathTest, A) {}\nTEST(ADeathTest, B) {}\nTEST(ADeathTest, C) {}\n\nTEST(B, A) {}\nTEST(B, B) {}\nTEST(B, C) {}\nTEST(B, DISABLED_D) {}\nTEST(B, DISABLED_E) {}\n\nTEST(BDeathTest, A) {}\nTEST(BDeathTest, B) {}\n\nTEST(C, A) {}\nTEST(C, B) {}\nTEST(C, C) {}\nTEST(C, DISABLED_D) {}\n\nTEST(CDeathTest, A) {}\n\nTEST(DISABLED_D, A) {}\nTEST(DISABLED_D, DISABLED_B) {}\n\n// This printer prints the full test names only, starting each test\n// iteration with a \"----\" marker.\nclass TestNamePrinter : public EmptyTestEventListener {\n public:\n  void OnTestIterationStart(const UnitTest& /* unit_test */,\n                            int /* iteration */) override {\n    printf(\"----\\n\");\n  }\n\n  void OnTestStart(const TestInfo& test_info) override {\n    printf(\"%s.%s\\n\", test_info.test_suite_name(), test_info.name());\n  }\n};\n\n}  // namespace\n\nint main(int argc, char** argv) {\n  InitGoogleTest(&argc, argv);\n\n  // Replaces the default printer with TestNamePrinter, which prints\n  // the test name only.\n  TestEventListeners& listeners = UnitTest::GetInstance()->listeners();\n  delete listeners.Release(listeners.default_result_printer());\n  listeners.Append(new TestNamePrinter);\n\n  return RUN_ALL_TESTS();\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-test-part-test.cc",
    "content": "// Copyright 2008 Google Inc.\n// All Rights Reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"gtest/gtest-test-part.h\"\n#include \"gtest/gtest.h\"\n\nusing testing::Message;\nusing testing::Test;\nusing testing::TestPartResult;\nusing testing::TestPartResultArray;\n\nnamespace {\n\n// Tests the TestPartResult class.\n\n// The test fixture for testing TestPartResult.\nclass TestPartResultTest : public Test {\n protected:\n  TestPartResultTest()\n      : r1_(TestPartResult::kSuccess, \"foo/bar.cc\", 10, \"Success!\"),\n        r2_(TestPartResult::kNonFatalFailure, \"foo/bar.cc\", -1, \"Failure!\"),\n        r3_(TestPartResult::kFatalFailure, nullptr, -1, \"Failure!\"),\n        r4_(TestPartResult::kSkip, \"foo/bar.cc\", 2, \"Skipped!\") {}\n\n  TestPartResult r1_, r2_, r3_, r4_;\n};\n\nTEST_F(TestPartResultTest, ConstructorWorks) {\n  Message message;\n  message << \"something is terribly wrong\";\n  message << static_cast<const char*>(testing::internal::kStackTraceMarker);\n  message << \"some unimportant stack trace\";\n\n  const TestPartResult result(TestPartResult::kNonFatalFailure, \"some_file.cc\",\n                              42, message.GetString().c_str());\n\n  EXPECT_EQ(TestPartResult::kNonFatalFailure, result.type());\n  EXPECT_STREQ(\"some_file.cc\", result.file_name());\n  EXPECT_EQ(42, result.line_number());\n  EXPECT_STREQ(message.GetString().c_str(), result.message());\n  EXPECT_STREQ(\"something is terribly wrong\", result.summary());\n}\n\nTEST_F(TestPartResultTest, ResultAccessorsWork) {\n  const TestPartResult success(TestPartResult::kSuccess, \"file.cc\", 42,\n                               \"message\");\n  EXPECT_TRUE(success.passed());\n  EXPECT_FALSE(success.failed());\n  EXPECT_FALSE(success.nonfatally_failed());\n  EXPECT_FALSE(success.fatally_failed());\n  EXPECT_FALSE(success.skipped());\n\n  const TestPartResult nonfatal_failure(TestPartResult::kNonFatalFailure,\n                                        \"file.cc\", 42, \"message\");\n  EXPECT_FALSE(nonfatal_failure.passed());\n  EXPECT_TRUE(nonfatal_failure.failed());\n  EXPECT_TRUE(nonfatal_failure.nonfatally_failed());\n  EXPECT_FALSE(nonfatal_failure.fatally_failed());\n  EXPECT_FALSE(nonfatal_failure.skipped());\n\n  const TestPartResult fatal_failure(TestPartResult::kFatalFailure, \"file.cc\",\n                                     42, \"message\");\n  EXPECT_FALSE(fatal_failure.passed());\n  EXPECT_TRUE(fatal_failure.failed());\n  EXPECT_FALSE(fatal_failure.nonfatally_failed());\n  EXPECT_TRUE(fatal_failure.fatally_failed());\n  EXPECT_FALSE(fatal_failure.skipped());\n\n  const TestPartResult skip(TestPartResult::kSkip, \"file.cc\", 42, \"message\");\n  EXPECT_FALSE(skip.passed());\n  EXPECT_FALSE(skip.failed());\n  EXPECT_FALSE(skip.nonfatally_failed());\n  EXPECT_FALSE(skip.fatally_failed());\n  EXPECT_TRUE(skip.skipped());\n}\n\n// Tests TestPartResult::type().\nTEST_F(TestPartResultTest, type) {\n  EXPECT_EQ(TestPartResult::kSuccess, r1_.type());\n  EXPECT_EQ(TestPartResult::kNonFatalFailure, r2_.type());\n  EXPECT_EQ(TestPartResult::kFatalFailure, r3_.type());\n  EXPECT_EQ(TestPartResult::kSkip, r4_.type());\n}\n\n// Tests TestPartResult::file_name().\nTEST_F(TestPartResultTest, file_name) {\n  EXPECT_STREQ(\"foo/bar.cc\", r1_.file_name());\n  EXPECT_STREQ(nullptr, r3_.file_name());\n  EXPECT_STREQ(\"foo/bar.cc\", r4_.file_name());\n}\n\n// Tests TestPartResult::line_number().\nTEST_F(TestPartResultTest, line_number) {\n  EXPECT_EQ(10, r1_.line_number());\n  EXPECT_EQ(-1, r2_.line_number());\n  EXPECT_EQ(2, r4_.line_number());\n}\n\n// Tests TestPartResult::message().\nTEST_F(TestPartResultTest, message) {\n  EXPECT_STREQ(\"Success!\", r1_.message());\n  EXPECT_STREQ(\"Skipped!\", r4_.message());\n}\n\n// Tests TestPartResult::passed().\nTEST_F(TestPartResultTest, Passed) {\n  EXPECT_TRUE(r1_.passed());\n  EXPECT_FALSE(r2_.passed());\n  EXPECT_FALSE(r3_.passed());\n  EXPECT_FALSE(r4_.passed());\n}\n\n// Tests TestPartResult::failed().\nTEST_F(TestPartResultTest, Failed) {\n  EXPECT_FALSE(r1_.failed());\n  EXPECT_TRUE(r2_.failed());\n  EXPECT_TRUE(r3_.failed());\n  EXPECT_FALSE(r4_.failed());\n}\n\n// Tests TestPartResult::failed().\nTEST_F(TestPartResultTest, Skipped) {\n  EXPECT_FALSE(r1_.skipped());\n  EXPECT_FALSE(r2_.skipped());\n  EXPECT_FALSE(r3_.skipped());\n  EXPECT_TRUE(r4_.skipped());\n}\n\n// Tests TestPartResult::fatally_failed().\nTEST_F(TestPartResultTest, FatallyFailed) {\n  EXPECT_FALSE(r1_.fatally_failed());\n  EXPECT_FALSE(r2_.fatally_failed());\n  EXPECT_TRUE(r3_.fatally_failed());\n  EXPECT_FALSE(r4_.fatally_failed());\n}\n\n// Tests TestPartResult::nonfatally_failed().\nTEST_F(TestPartResultTest, NonfatallyFailed) {\n  EXPECT_FALSE(r1_.nonfatally_failed());\n  EXPECT_TRUE(r2_.nonfatally_failed());\n  EXPECT_FALSE(r3_.nonfatally_failed());\n  EXPECT_FALSE(r4_.nonfatally_failed());\n}\n\n// Tests the TestPartResultArray class.\n\nclass TestPartResultArrayTest : public Test {\n protected:\n  TestPartResultArrayTest()\n      : r1_(TestPartResult::kNonFatalFailure, \"foo/bar.cc\", -1, \"Failure 1\"),\n        r2_(TestPartResult::kFatalFailure, \"foo/bar.cc\", -1, \"Failure 2\") {}\n\n  const TestPartResult r1_, r2_;\n};\n\n// Tests that TestPartResultArray initially has size 0.\nTEST_F(TestPartResultArrayTest, InitialSizeIsZero) {\n  TestPartResultArray results;\n  EXPECT_EQ(0, results.size());\n}\n\n// Tests that TestPartResultArray contains the given TestPartResult\n// after one Append() operation.\nTEST_F(TestPartResultArrayTest, ContainsGivenResultAfterAppend) {\n  TestPartResultArray results;\n  results.Append(r1_);\n  EXPECT_EQ(1, results.size());\n  EXPECT_STREQ(\"Failure 1\", results.GetTestPartResult(0).message());\n}\n\n// Tests that TestPartResultArray contains the given TestPartResults\n// after two Append() operations.\nTEST_F(TestPartResultArrayTest, ContainsGivenResultsAfterTwoAppends) {\n  TestPartResultArray results;\n  results.Append(r1_);\n  results.Append(r2_);\n  EXPECT_EQ(2, results.size());\n  EXPECT_STREQ(\"Failure 1\", results.GetTestPartResult(0).message());\n  EXPECT_STREQ(\"Failure 2\", results.GetTestPartResult(1).message());\n}\n\ntypedef TestPartResultArrayTest TestPartResultArrayDeathTest;\n\n// Tests that the program dies when GetTestPartResult() is called with\n// an invalid index.\nTEST_F(TestPartResultArrayDeathTest, DiesWhenIndexIsOutOfBound) {\n  TestPartResultArray results;\n  results.Append(r1_);\n\n  EXPECT_DEATH_IF_SUPPORTED(results.GetTestPartResult(-1), \"\");\n  EXPECT_DEATH_IF_SUPPORTED(results.GetTestPartResult(1), \"\");\n}\n\n}  // namespace\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-throw-on-failure-test.py",
    "content": "#!/usr/bin/env python\n#\n# Copyright 2009, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Tests Google Test's throw-on-failure mode with exceptions disabled.\n\nThis script invokes googletest-throw-on-failure-test_ (a program written with\nGoogle Test) with different environments and command line flags.\n\"\"\"\n\nimport os\nfrom googletest.test import gtest_test_utils\n\n\n# Constants.\n\n# The command line flag for enabling/disabling the throw-on-failure mode.\nTHROW_ON_FAILURE = 'gtest_throw_on_failure'\n\n# Path to the googletest-throw-on-failure-test_ program, compiled with\n# exceptions disabled.\nEXE_PATH = gtest_test_utils.GetTestExecutablePath(\n    'googletest-throw-on-failure-test_')\n\n\n# Utilities.\n\n\ndef SetEnvVar(env_var, value):\n  \"\"\"Sets an environment variable to a given value; unsets it when the\n  given value is None.\n  \"\"\"\n\n  env_var = env_var.upper()\n  if value is not None:\n    os.environ[env_var] = value\n  elif env_var in os.environ:\n    del os.environ[env_var]\n\n\ndef Run(command):\n  \"\"\"Runs a command; returns True/False if its exit code is/isn't 0.\"\"\"\n\n  print('Running \"%s\". . .' % ' '.join(command))\n  p = gtest_test_utils.Subprocess(command)\n  return p.exited and p.exit_code == 0\n\n\n# The tests.\nclass ThrowOnFailureTest(gtest_test_utils.TestCase):\n  \"\"\"Tests the throw-on-failure mode.\"\"\"\n\n  def RunAndVerify(self, env_var_value, flag_value, should_fail):\n    \"\"\"Runs googletest-throw-on-failure-test_ and verifies that it does\n    (or does not) exit with a non-zero code.\n\n    Args:\n      env_var_value:    value of the GTEST_BREAK_ON_FAILURE environment\n                        variable; None if the variable should be unset.\n      flag_value:       value of the --gtest_break_on_failure flag;\n                        None if the flag should not be present.\n      should_fail:      True if and only if the program is expected to fail.\n    \"\"\"\n\n    SetEnvVar(THROW_ON_FAILURE, env_var_value)\n\n    if env_var_value is None:\n      env_var_value_msg = ' is not set'\n    else:\n      env_var_value_msg = '=' + env_var_value\n\n    if flag_value is None:\n      flag = ''\n    elif flag_value == '0':\n      flag = '--%s=0' % THROW_ON_FAILURE\n    else:\n      flag = '--%s' % THROW_ON_FAILURE\n\n    command = [EXE_PATH]\n    if flag:\n      command.append(flag)\n\n    if should_fail:\n      should_or_not = 'should'\n    else:\n      should_or_not = 'should not'\n\n    failed = not Run(command)\n\n    SetEnvVar(THROW_ON_FAILURE, None)\n\n    msg = ('when %s%s, an assertion failure in \"%s\" %s cause a non-zero '\n           'exit code.' %\n           (THROW_ON_FAILURE, env_var_value_msg, ' '.join(command),\n            should_or_not))\n    self.assert_(failed == should_fail, msg)\n\n  def testDefaultBehavior(self):\n    \"\"\"Tests the behavior of the default mode.\"\"\"\n\n    self.RunAndVerify(env_var_value=None, flag_value=None, should_fail=False)\n\n  def testThrowOnFailureEnvVar(self):\n    \"\"\"Tests using the GTEST_THROW_ON_FAILURE environment variable.\"\"\"\n\n    self.RunAndVerify(env_var_value='0',\n                      flag_value=None,\n                      should_fail=False)\n    self.RunAndVerify(env_var_value='1',\n                      flag_value=None,\n                      should_fail=True)\n\n  def testThrowOnFailureFlag(self):\n    \"\"\"Tests using the --gtest_throw_on_failure flag.\"\"\"\n\n    self.RunAndVerify(env_var_value=None,\n                      flag_value='0',\n                      should_fail=False)\n    self.RunAndVerify(env_var_value=None,\n                      flag_value='1',\n                      should_fail=True)\n\n  def testThrowOnFailureFlagOverridesEnvVar(self):\n    \"\"\"Tests that --gtest_throw_on_failure overrides GTEST_THROW_ON_FAILURE.\"\"\"\n\n    self.RunAndVerify(env_var_value='0',\n                      flag_value='0',\n                      should_fail=False)\n    self.RunAndVerify(env_var_value='0',\n                      flag_value='1',\n                      should_fail=True)\n    self.RunAndVerify(env_var_value='1',\n                      flag_value='0',\n                      should_fail=False)\n    self.RunAndVerify(env_var_value='1',\n                      flag_value='1',\n                      should_fail=True)\n\n\nif __name__ == '__main__':\n  gtest_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-throw-on-failure-test_.cc",
    "content": "// Copyright 2009, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Tests Google Test's throw-on-failure mode with exceptions disabled.\n//\n// This program must be compiled with exceptions disabled.  It will be\n// invoked by googletest-throw-on-failure-test.py, and is expected to exit\n// with non-zero in the throw-on-failure mode or 0 otherwise.\n\n#include <stdio.h>   // for fflush, fprintf, NULL, etc.\n#include <stdlib.h>  // for exit\n\n#include <exception>  // for set_terminate\n\n#include \"gtest/gtest.h\"\n\n// This terminate handler aborts the program using exit() rather than abort().\n// This avoids showing pop-ups on Windows systems and core dumps on Unix-like\n// ones.\nvoid TerminateHandler() {\n  fprintf(stderr, \"%s\\n\", \"Unhandled C++ exception terminating the program.\");\n  fflush(nullptr);\n  exit(1);\n}\n\nint main(int argc, char** argv) {\n#if GTEST_HAS_EXCEPTIONS\n  std::set_terminate(&TerminateHandler);\n#endif\n  testing::InitGoogleTest(&argc, argv);\n\n  // We want to ensure that people can use Google Test assertions in\n  // other testing frameworks, as long as they initialize Google Test\n  // properly and set the throw-on-failure mode.  Therefore, we don't\n  // use Google Test's constructs for defining and running tests\n  // (e.g. TEST and RUN_ALL_TESTS) here.\n\n  // In the throw-on-failure mode with exceptions disabled, this\n  // assertion will cause the program to exit with a non-zero code.\n  EXPECT_EQ(2, 3);\n\n  // When not in the throw-on-failure mode, the control will reach\n  // here.\n  return 0;\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-uninitialized-test.py",
    "content": "#!/usr/bin/env python\n#\n# Copyright 2008, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Verifies that Google Test warns the user when not initialized properly.\"\"\"\n\nfrom googletest.test import gtest_test_utils\n\nCOMMAND = gtest_test_utils.GetTestExecutablePath('googletest-uninitialized-test_')\n\n\ndef Assert(condition):\n  if not condition:\n    raise AssertionError\n\n\ndef AssertEq(expected, actual):\n  if expected != actual:\n    print('Expected: %s' % (expected,))\n    print('  Actual: %s' % (actual,))\n    raise AssertionError\n\n\ndef TestExitCodeAndOutput(command):\n  \"\"\"Runs the given command and verifies its exit code and output.\"\"\"\n\n  # Verifies that 'command' exits with code 1.\n  p = gtest_test_utils.Subprocess(command)\n  if p.exited and p.exit_code == 0:\n    Assert('IMPORTANT NOTICE' in p.output);\n  Assert('InitGoogleTest' in p.output)\n\n\nclass GTestUninitializedTest(gtest_test_utils.TestCase):\n  def testExitCodeAndOutput(self):\n    TestExitCodeAndOutput(COMMAND)\n\n\nif __name__ == '__main__':\n  gtest_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/googletest-uninitialized-test_.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"gtest/gtest.h\"\n\nTEST(DummyTest, Dummy) {\n  // This test doesn't verify anything.  We just need it to create a\n  // realistic stage for testing the behavior of Google Test when\n  // RUN_ALL_TESTS() is called without\n  // testing::InitGoogleTest() being called first.\n}\n\nint main() { return RUN_ALL_TESTS(); }\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest-typed-test2_test.cc",
    "content": "// Copyright 2008 Google Inc.\n// All Rights Reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include <vector>\n\n#include \"gtest/gtest.h\"\n#include \"test/gtest-typed-test_test.h\"\n\n// Tests that the same type-parameterized test case can be\n// instantiated in different translation units linked together.\n// (ContainerTest is also instantiated in gtest-typed-test_test.cc.)\nINSTANTIATE_TYPED_TEST_SUITE_P(Vector, ContainerTest,\n                               testing::Types<std::vector<int> >);\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest-typed-test_test.cc",
    "content": "// Copyright 2008 Google Inc.\n// All Rights Reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"test/gtest-typed-test_test.h\"\n\n#include <set>\n#include <type_traits>\n#include <vector>\n\n#include \"gtest/gtest.h\"\n\n#if _MSC_VER\nGTEST_DISABLE_MSC_WARNINGS_PUSH_(4127 /* conditional expression is constant */)\n#endif  //  _MSC_VER\n\nusing testing::Test;\n\n// Used for testing that SetUpTestSuite()/TearDownTestSuite(), fixture\n// ctor/dtor, and SetUp()/TearDown() work correctly in typed tests and\n// type-parameterized test.\ntemplate <typename T>\nclass CommonTest : public Test {\n  // For some technical reason, SetUpTestSuite() and TearDownTestSuite()\n  // must be public.\n public:\n  static void SetUpTestSuite() { shared_ = new T(5); }\n\n  static void TearDownTestSuite() {\n    delete shared_;\n    shared_ = nullptr;\n  }\n\n  // This 'protected:' is optional.  There's no harm in making all\n  // members of this fixture class template public.\n protected:\n  // We used to use std::list here, but switched to std::vector since\n  // MSVC's <list> doesn't compile cleanly with /W4.\n  typedef std::vector<T> Vector;\n  typedef std::set<int> IntSet;\n\n  CommonTest() : value_(1) {}\n\n  ~CommonTest() override { EXPECT_EQ(3, value_); }\n\n  void SetUp() override {\n    EXPECT_EQ(1, value_);\n    value_++;\n  }\n\n  void TearDown() override {\n    EXPECT_EQ(2, value_);\n    value_++;\n  }\n\n  T value_;\n  static T* shared_;\n};\n\ntemplate <typename T>\nT* CommonTest<T>::shared_ = nullptr;\n\nusing testing::Types;\n\n// Tests that SetUpTestSuite()/TearDownTestSuite(), fixture ctor/dtor,\n// and SetUp()/TearDown() work correctly in typed tests\n\ntypedef Types<char, int> TwoTypes;\nTYPED_TEST_SUITE(CommonTest, TwoTypes);\n\nTYPED_TEST(CommonTest, ValuesAreCorrect) {\n  // Static members of the fixture class template can be visited via\n  // the TestFixture:: prefix.\n  EXPECT_EQ(5, *TestFixture::shared_);\n\n  // Typedefs in the fixture class template can be visited via the\n  // \"typename TestFixture::\" prefix.\n  typename TestFixture::Vector empty;\n  EXPECT_EQ(0U, empty.size());\n\n  typename TestFixture::IntSet empty2;\n  EXPECT_EQ(0U, empty2.size());\n\n  // Non-static members of the fixture class must be visited via\n  // 'this', as required by C++ for class templates.\n  EXPECT_EQ(2, this->value_);\n}\n\n// The second test makes sure shared_ is not deleted after the first\n// test.\nTYPED_TEST(CommonTest, ValuesAreStillCorrect) {\n  // Static members of the fixture class template can also be visited\n  // via 'this'.\n  ASSERT_TRUE(this->shared_ != nullptr);\n  EXPECT_EQ(5, *this->shared_);\n\n  // TypeParam can be used to refer to the type parameter.\n  EXPECT_EQ(static_cast<TypeParam>(2), this->value_);\n}\n\n// Tests that multiple TYPED_TEST_SUITE's can be defined in the same\n// translation unit.\n\ntemplate <typename T>\nclass TypedTest1 : public Test {};\n\n// Verifies that the second argument of TYPED_TEST_SUITE can be a\n// single type.\nTYPED_TEST_SUITE(TypedTest1, int);\nTYPED_TEST(TypedTest1, A) {}\n\ntemplate <typename T>\nclass TypedTest2 : public Test {};\n\n// Verifies that the second argument of TYPED_TEST_SUITE can be a\n// Types<...> type list.\nTYPED_TEST_SUITE(TypedTest2, Types<int>);\n\n// This also verifies that tests from different typed test cases can\n// share the same name.\nTYPED_TEST(TypedTest2, A) {}\n\n// Tests that a typed test case can be defined in a namespace.\n\nnamespace library1 {\n\ntemplate <typename T>\nclass NumericTest : public Test {};\n\ntypedef Types<int, long> NumericTypes;\nTYPED_TEST_SUITE(NumericTest, NumericTypes);\n\nTYPED_TEST(NumericTest, DefaultIsZero) { EXPECT_EQ(0, TypeParam()); }\n\n}  // namespace library1\n\n// Tests that custom names work.\ntemplate <typename T>\nclass TypedTestWithNames : public Test {};\n\nclass TypedTestNames {\n public:\n  template <typename T>\n  static std::string GetName(int i) {\n    if (std::is_same<T, char>::value) {\n      return std::string(\"char\") + ::testing::PrintToString(i);\n    }\n    if (std::is_same<T, int>::value) {\n      return std::string(\"int\") + ::testing::PrintToString(i);\n    }\n  }\n};\n\nTYPED_TEST_SUITE(TypedTestWithNames, TwoTypes, TypedTestNames);\n\nTYPED_TEST(TypedTestWithNames, TestSuiteName) {\n  if (std::is_same<TypeParam, char>::value) {\n    EXPECT_STREQ(::testing::UnitTest::GetInstance()\n                     ->current_test_info()\n                     ->test_suite_name(),\n                 \"TypedTestWithNames/char0\");\n  }\n  if (std::is_same<TypeParam, int>::value) {\n    EXPECT_STREQ(::testing::UnitTest::GetInstance()\n                     ->current_test_info()\n                     ->test_suite_name(),\n                 \"TypedTestWithNames/int1\");\n  }\n}\n\nusing testing::Types;\nusing testing::internal::TypedTestSuitePState;\n\n// Tests TypedTestSuitePState.\n\nclass TypedTestSuitePStateTest : public Test {\n protected:\n  void SetUp() override {\n    state_.AddTestName(\"foo.cc\", 0, \"FooTest\", \"A\");\n    state_.AddTestName(\"foo.cc\", 0, \"FooTest\", \"B\");\n    state_.AddTestName(\"foo.cc\", 0, \"FooTest\", \"C\");\n  }\n\n  TypedTestSuitePState state_;\n};\n\nTEST_F(TypedTestSuitePStateTest, SucceedsForMatchingList) {\n  const char* tests = \"A, B, C\";\n  EXPECT_EQ(tests,\n            state_.VerifyRegisteredTestNames(\"Suite\", \"foo.cc\", 1, tests));\n}\n\n// Makes sure that the order of the tests and spaces around the names\n// don't matter.\nTEST_F(TypedTestSuitePStateTest, IgnoresOrderAndSpaces) {\n  const char* tests = \"A,C,   B\";\n  EXPECT_EQ(tests,\n            state_.VerifyRegisteredTestNames(\"Suite\", \"foo.cc\", 1, tests));\n}\n\nusing TypedTestSuitePStateDeathTest = TypedTestSuitePStateTest;\n\nTEST_F(TypedTestSuitePStateDeathTest, DetectsDuplicates) {\n  EXPECT_DEATH_IF_SUPPORTED(\n      state_.VerifyRegisteredTestNames(\"Suite\", \"foo.cc\", 1, \"A, B, A, C\"),\n      \"foo\\\\.cc.1.?: Test A is listed more than once\\\\.\");\n}\n\nTEST_F(TypedTestSuitePStateDeathTest, DetectsExtraTest) {\n  EXPECT_DEATH_IF_SUPPORTED(\n      state_.VerifyRegisteredTestNames(\"Suite\", \"foo.cc\", 1, \"A, B, C, D\"),\n      \"foo\\\\.cc.1.?: No test named D can be found in this test suite\\\\.\");\n}\n\nTEST_F(TypedTestSuitePStateDeathTest, DetectsMissedTest) {\n  EXPECT_DEATH_IF_SUPPORTED(\n      state_.VerifyRegisteredTestNames(\"Suite\", \"foo.cc\", 1, \"A, C\"),\n      \"foo\\\\.cc.1.?: You forgot to list test B\\\\.\");\n}\n\n// Tests that defining a test for a parameterized test case generates\n// a run-time error if the test case has been registered.\nTEST_F(TypedTestSuitePStateDeathTest, DetectsTestAfterRegistration) {\n  state_.VerifyRegisteredTestNames(\"Suite\", \"foo.cc\", 1, \"A, B, C\");\n  EXPECT_DEATH_IF_SUPPORTED(\n      state_.AddTestName(\"foo.cc\", 2, \"FooTest\", \"D\"),\n      \"foo\\\\.cc.2.?: Test D must be defined before REGISTER_TYPED_TEST_SUITE_P\"\n      \"\\\\(FooTest, \\\\.\\\\.\\\\.\\\\)\\\\.\");\n}\n\n// Tests that SetUpTestSuite()/TearDownTestSuite(), fixture ctor/dtor,\n// and SetUp()/TearDown() work correctly in type-parameterized tests.\n\ntemplate <typename T>\nclass DerivedTest : public CommonTest<T> {};\n\nTYPED_TEST_SUITE_P(DerivedTest);\n\nTYPED_TEST_P(DerivedTest, ValuesAreCorrect) {\n  // Static members of the fixture class template can be visited via\n  // the TestFixture:: prefix.\n  EXPECT_EQ(5, *TestFixture::shared_);\n\n  // Non-static members of the fixture class must be visited via\n  // 'this', as required by C++ for class templates.\n  EXPECT_EQ(2, this->value_);\n}\n\n// The second test makes sure shared_ is not deleted after the first\n// test.\nTYPED_TEST_P(DerivedTest, ValuesAreStillCorrect) {\n  // Static members of the fixture class template can also be visited\n  // via 'this'.\n  ASSERT_TRUE(this->shared_ != nullptr);\n  EXPECT_EQ(5, *this->shared_);\n  EXPECT_EQ(2, this->value_);\n}\n\nREGISTER_TYPED_TEST_SUITE_P(DerivedTest, ValuesAreCorrect,\n                            ValuesAreStillCorrect);\n\ntypedef Types<short, long> MyTwoTypes;\nINSTANTIATE_TYPED_TEST_SUITE_P(My, DerivedTest, MyTwoTypes);\n\n// Tests that custom names work with type parametrized tests. We reuse the\n// TwoTypes from above here.\ntemplate <typename T>\nclass TypeParametrizedTestWithNames : public Test {};\n\nTYPED_TEST_SUITE_P(TypeParametrizedTestWithNames);\n\nTYPED_TEST_P(TypeParametrizedTestWithNames, TestSuiteName) {\n  if (std::is_same<TypeParam, char>::value) {\n    EXPECT_STREQ(::testing::UnitTest::GetInstance()\n                     ->current_test_info()\n                     ->test_suite_name(),\n                 \"CustomName/TypeParametrizedTestWithNames/parChar0\");\n  }\n  if (std::is_same<TypeParam, int>::value) {\n    EXPECT_STREQ(::testing::UnitTest::GetInstance()\n                     ->current_test_info()\n                     ->test_suite_name(),\n                 \"CustomName/TypeParametrizedTestWithNames/parInt1\");\n  }\n}\n\nREGISTER_TYPED_TEST_SUITE_P(TypeParametrizedTestWithNames, TestSuiteName);\n\nclass TypeParametrizedTestNames {\n public:\n  template <typename T>\n  static std::string GetName(int i) {\n    if (std::is_same<T, char>::value) {\n      return std::string(\"parChar\") + ::testing::PrintToString(i);\n    }\n    if (std::is_same<T, int>::value) {\n      return std::string(\"parInt\") + ::testing::PrintToString(i);\n    }\n  }\n};\n\nINSTANTIATE_TYPED_TEST_SUITE_P(CustomName, TypeParametrizedTestWithNames,\n                               TwoTypes, TypeParametrizedTestNames);\n\n// Tests that multiple TYPED_TEST_SUITE_P's can be defined in the same\n// translation unit.\n\ntemplate <typename T>\nclass TypedTestP1 : public Test {};\n\nTYPED_TEST_SUITE_P(TypedTestP1);\n\n// For testing that the code between TYPED_TEST_SUITE_P() and\n// TYPED_TEST_P() is not enclosed in a namespace.\nusing IntAfterTypedTestSuiteP = int;\n\nTYPED_TEST_P(TypedTestP1, A) {}\nTYPED_TEST_P(TypedTestP1, B) {}\n\n// For testing that the code between TYPED_TEST_P() and\n// REGISTER_TYPED_TEST_SUITE_P() is not enclosed in a namespace.\nusing IntBeforeRegisterTypedTestSuiteP = int;\n\nREGISTER_TYPED_TEST_SUITE_P(TypedTestP1, A, B);\n\ntemplate <typename T>\nclass TypedTestP2 : public Test {};\n\nTYPED_TEST_SUITE_P(TypedTestP2);\n\n// This also verifies that tests from different type-parameterized\n// test cases can share the same name.\nTYPED_TEST_P(TypedTestP2, A) {}\n\nREGISTER_TYPED_TEST_SUITE_P(TypedTestP2, A);\n\n// Verifies that the code between TYPED_TEST_SUITE_P() and\n// REGISTER_TYPED_TEST_SUITE_P() is not enclosed in a namespace.\nIntAfterTypedTestSuiteP after = 0;\nIntBeforeRegisterTypedTestSuiteP before = 0;\n\n// Verifies that the last argument of INSTANTIATE_TYPED_TEST_SUITE_P()\n// can be either a single type or a Types<...> type list.\nINSTANTIATE_TYPED_TEST_SUITE_P(Int, TypedTestP1, int);\nINSTANTIATE_TYPED_TEST_SUITE_P(Int, TypedTestP2, Types<int>);\n\n// Tests that the same type-parameterized test case can be\n// instantiated more than once in the same translation unit.\nINSTANTIATE_TYPED_TEST_SUITE_P(Double, TypedTestP2, Types<double>);\n\n// Tests that the same type-parameterized test case can be\n// instantiated in different translation units linked together.\n// (ContainerTest is also instantiated in gtest-typed-test_test.cc.)\ntypedef Types<std::vector<double>, std::set<char> > MyContainers;\nINSTANTIATE_TYPED_TEST_SUITE_P(My, ContainerTest, MyContainers);\n\n// Tests that a type-parameterized test case can be defined and\n// instantiated in a namespace.\n\nnamespace library2 {\n\ntemplate <typename T>\nclass NumericTest : public Test {};\n\nTYPED_TEST_SUITE_P(NumericTest);\n\nTYPED_TEST_P(NumericTest, DefaultIsZero) { EXPECT_EQ(0, TypeParam()); }\n\nTYPED_TEST_P(NumericTest, ZeroIsLessThanOne) {\n  EXPECT_LT(TypeParam(0), TypeParam(1));\n}\n\nREGISTER_TYPED_TEST_SUITE_P(NumericTest, DefaultIsZero, ZeroIsLessThanOne);\ntypedef Types<int, double> NumericTypes;\nINSTANTIATE_TYPED_TEST_SUITE_P(My, NumericTest, NumericTypes);\n\nstatic const char* GetTestName() {\n  return testing::UnitTest::GetInstance()->current_test_info()->name();\n}\n// Test the stripping of space from test names\ntemplate <typename T>\nclass TrimmedTest : public Test {};\nTYPED_TEST_SUITE_P(TrimmedTest);\nTYPED_TEST_P(TrimmedTest, Test1) { EXPECT_STREQ(\"Test1\", GetTestName()); }\nTYPED_TEST_P(TrimmedTest, Test2) { EXPECT_STREQ(\"Test2\", GetTestName()); }\nTYPED_TEST_P(TrimmedTest, Test3) { EXPECT_STREQ(\"Test3\", GetTestName()); }\nTYPED_TEST_P(TrimmedTest, Test4) { EXPECT_STREQ(\"Test4\", GetTestName()); }\nTYPED_TEST_P(TrimmedTest, Test5) { EXPECT_STREQ(\"Test5\", GetTestName()); }\nREGISTER_TYPED_TEST_SUITE_P(TrimmedTest, Test1, Test2, Test3, Test4,\n                            Test5);  // NOLINT\ntemplate <typename T1, typename T2>\nstruct MyPair {};\n// Be sure to try a type with a comma in its name just in case it matters.\ntypedef Types<int, double, MyPair<int, int> > TrimTypes;\nINSTANTIATE_TYPED_TEST_SUITE_P(My, TrimmedTest, TrimTypes);\n\n}  // namespace library2\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest-typed-test_test.h",
    "content": "// Copyright 2008 Google Inc.\n// All Rights Reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#ifndef GOOGLETEST_TEST_GTEST_TYPED_TEST_TEST_H_\n#define GOOGLETEST_TEST_GTEST_TYPED_TEST_TEST_H_\n\n#include \"gtest/gtest.h\"\n\nusing testing::Test;\n\n// For testing that the same type-parameterized test case can be\n// instantiated in different translation units linked together.\n// ContainerTest will be instantiated in both gtest-typed-test_test.cc\n// and gtest-typed-test2_test.cc.\n\ntemplate <typename T>\nclass ContainerTest : public Test {};\n\nTYPED_TEST_SUITE_P(ContainerTest);\n\nTYPED_TEST_P(ContainerTest, CanBeDefaultConstructed) { TypeParam container; }\n\nTYPED_TEST_P(ContainerTest, InitialSizeIsZero) {\n  TypeParam container;\n  EXPECT_EQ(0U, container.size());\n}\n\nREGISTER_TYPED_TEST_SUITE_P(ContainerTest, CanBeDefaultConstructed,\n                            InitialSizeIsZero);\n\n#endif  // GOOGLETEST_TEST_GTEST_TYPED_TEST_TEST_H_\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest-unittest-api_test.cc",
    "content": "// Copyright 2009 Google Inc.  All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// The Google C++ Testing and Mocking Framework (Google Test)\n//\n// This file contains tests verifying correctness of data provided via\n// UnitTest's public methods.\n\n#include <string.h>  // For strcmp.\n\n#include <algorithm>\n\n#include \"gtest/gtest.h\"\n\nusing ::testing::InitGoogleTest;\n\nnamespace testing {\nnamespace internal {\n\ntemplate <typename T>\nstruct LessByName {\n  bool operator()(const T* a, const T* b) {\n    return strcmp(a->name(), b->name()) < 0;\n  }\n};\n\nclass UnitTestHelper {\n public:\n  // Returns the array of pointers to all test suites sorted by the test suite\n  // name.  The caller is responsible for deleting the array.\n  static TestSuite const** GetSortedTestSuites() {\n    UnitTest& unit_test = *UnitTest::GetInstance();\n    auto const** const test_suites = new const TestSuite*[static_cast<size_t>(\n        unit_test.total_test_suite_count())];\n\n    for (int i = 0; i < unit_test.total_test_suite_count(); ++i)\n      test_suites[i] = unit_test.GetTestSuite(i);\n\n    std::sort(test_suites, test_suites + unit_test.total_test_suite_count(),\n              LessByName<TestSuite>());\n    return test_suites;\n  }\n\n  // Returns the test suite by its name.  The caller doesn't own the returned\n  // pointer.\n  static const TestSuite* FindTestSuite(const char* name) {\n    UnitTest& unit_test = *UnitTest::GetInstance();\n    for (int i = 0; i < unit_test.total_test_suite_count(); ++i) {\n      const TestSuite* test_suite = unit_test.GetTestSuite(i);\n      if (0 == strcmp(test_suite->name(), name)) return test_suite;\n    }\n    return nullptr;\n  }\n\n  // Returns the array of pointers to all tests in a particular test suite\n  // sorted by the test name.  The caller is responsible for deleting the\n  // array.\n  static TestInfo const** GetSortedTests(const TestSuite* test_suite) {\n    TestInfo const** const tests = new const TestInfo*[static_cast<size_t>(\n        test_suite->total_test_count())];\n\n    for (int i = 0; i < test_suite->total_test_count(); ++i)\n      tests[i] = test_suite->GetTestInfo(i);\n\n    std::sort(tests, tests + test_suite->total_test_count(),\n              LessByName<TestInfo>());\n    return tests;\n  }\n};\n\ntemplate <typename T>\nclass TestSuiteWithCommentTest : public Test {};\nTYPED_TEST_SUITE(TestSuiteWithCommentTest, Types<int>);\nTYPED_TEST(TestSuiteWithCommentTest, Dummy) {}\n\nconst int kTypedTestSuites = 1;\nconst int kTypedTests = 1;\n\n// We can only test the accessors that do not change value while tests run.\n// Since tests can be run in any order, the values the accessors that track\n// test execution (such as failed_test_count) can not be predicted.\nTEST(ApiTest, UnitTestImmutableAccessorsWork) {\n  UnitTest* unit_test = UnitTest::GetInstance();\n\n  ASSERT_EQ(2 + kTypedTestSuites, unit_test->total_test_suite_count());\n  EXPECT_EQ(1 + kTypedTestSuites, unit_test->test_suite_to_run_count());\n  EXPECT_EQ(2, unit_test->disabled_test_count());\n  EXPECT_EQ(5 + kTypedTests, unit_test->total_test_count());\n  EXPECT_EQ(3 + kTypedTests, unit_test->test_to_run_count());\n\n  const TestSuite** const test_suites = UnitTestHelper::GetSortedTestSuites();\n\n  EXPECT_STREQ(\"ApiTest\", test_suites[0]->name());\n  EXPECT_STREQ(\"DISABLED_Test\", test_suites[1]->name());\n  EXPECT_STREQ(\"TestSuiteWithCommentTest/0\", test_suites[2]->name());\n\n  delete[] test_suites;\n\n  // The following lines initiate actions to verify certain methods in\n  // FinalSuccessChecker::TearDown.\n\n  // Records a test property to verify TestResult::GetTestProperty().\n  RecordProperty(\"key\", \"value\");\n}\n\nAssertionResult IsNull(const char* str) {\n  if (str != nullptr) {\n    return testing::AssertionFailure() << \"argument is \" << str;\n  }\n  return AssertionSuccess();\n}\n\nTEST(ApiTest, TestSuiteImmutableAccessorsWork) {\n  const TestSuite* test_suite = UnitTestHelper::FindTestSuite(\"ApiTest\");\n  ASSERT_TRUE(test_suite != nullptr);\n\n  EXPECT_STREQ(\"ApiTest\", test_suite->name());\n  EXPECT_TRUE(IsNull(test_suite->type_param()));\n  EXPECT_TRUE(test_suite->should_run());\n  EXPECT_EQ(1, test_suite->disabled_test_count());\n  EXPECT_EQ(3, test_suite->test_to_run_count());\n  ASSERT_EQ(4, test_suite->total_test_count());\n\n  const TestInfo** tests = UnitTestHelper::GetSortedTests(test_suite);\n\n  EXPECT_STREQ(\"DISABLED_Dummy1\", tests[0]->name());\n  EXPECT_STREQ(\"ApiTest\", tests[0]->test_suite_name());\n  EXPECT_TRUE(IsNull(tests[0]->value_param()));\n  EXPECT_TRUE(IsNull(tests[0]->type_param()));\n  EXPECT_FALSE(tests[0]->should_run());\n\n  EXPECT_STREQ(\"TestSuiteDisabledAccessorsWork\", tests[1]->name());\n  EXPECT_STREQ(\"ApiTest\", tests[1]->test_suite_name());\n  EXPECT_TRUE(IsNull(tests[1]->value_param()));\n  EXPECT_TRUE(IsNull(tests[1]->type_param()));\n  EXPECT_TRUE(tests[1]->should_run());\n\n  EXPECT_STREQ(\"TestSuiteImmutableAccessorsWork\", tests[2]->name());\n  EXPECT_STREQ(\"ApiTest\", tests[2]->test_suite_name());\n  EXPECT_TRUE(IsNull(tests[2]->value_param()));\n  EXPECT_TRUE(IsNull(tests[2]->type_param()));\n  EXPECT_TRUE(tests[2]->should_run());\n\n  EXPECT_STREQ(\"UnitTestImmutableAccessorsWork\", tests[3]->name());\n  EXPECT_STREQ(\"ApiTest\", tests[3]->test_suite_name());\n  EXPECT_TRUE(IsNull(tests[3]->value_param()));\n  EXPECT_TRUE(IsNull(tests[3]->type_param()));\n  EXPECT_TRUE(tests[3]->should_run());\n\n  delete[] tests;\n  tests = nullptr;\n\n  test_suite = UnitTestHelper::FindTestSuite(\"TestSuiteWithCommentTest/0\");\n  ASSERT_TRUE(test_suite != nullptr);\n\n  EXPECT_STREQ(\"TestSuiteWithCommentTest/0\", test_suite->name());\n  EXPECT_STREQ(GetTypeName<Types<int>>().c_str(), test_suite->type_param());\n  EXPECT_TRUE(test_suite->should_run());\n  EXPECT_EQ(0, test_suite->disabled_test_count());\n  EXPECT_EQ(1, test_suite->test_to_run_count());\n  ASSERT_EQ(1, test_suite->total_test_count());\n\n  tests = UnitTestHelper::GetSortedTests(test_suite);\n\n  EXPECT_STREQ(\"Dummy\", tests[0]->name());\n  EXPECT_STREQ(\"TestSuiteWithCommentTest/0\", tests[0]->test_suite_name());\n  EXPECT_TRUE(IsNull(tests[0]->value_param()));\n  EXPECT_STREQ(GetTypeName<Types<int>>().c_str(), tests[0]->type_param());\n  EXPECT_TRUE(tests[0]->should_run());\n\n  delete[] tests;\n}\n\nTEST(ApiTest, TestSuiteDisabledAccessorsWork) {\n  const TestSuite* test_suite = UnitTestHelper::FindTestSuite(\"DISABLED_Test\");\n  ASSERT_TRUE(test_suite != nullptr);\n\n  EXPECT_STREQ(\"DISABLED_Test\", test_suite->name());\n  EXPECT_TRUE(IsNull(test_suite->type_param()));\n  EXPECT_FALSE(test_suite->should_run());\n  EXPECT_EQ(1, test_suite->disabled_test_count());\n  EXPECT_EQ(0, test_suite->test_to_run_count());\n  ASSERT_EQ(1, test_suite->total_test_count());\n\n  const TestInfo* const test_info = test_suite->GetTestInfo(0);\n  EXPECT_STREQ(\"Dummy2\", test_info->name());\n  EXPECT_STREQ(\"DISABLED_Test\", test_info->test_suite_name());\n  EXPECT_TRUE(IsNull(test_info->value_param()));\n  EXPECT_TRUE(IsNull(test_info->type_param()));\n  EXPECT_FALSE(test_info->should_run());\n}\n\n// These two tests are here to provide support for testing\n// test_suite_to_run_count, disabled_test_count, and test_to_run_count.\nTEST(ApiTest, DISABLED_Dummy1) {}\nTEST(DISABLED_Test, Dummy2) {}\n\nclass FinalSuccessChecker : public Environment {\n protected:\n  void TearDown() override {\n    UnitTest* unit_test = UnitTest::GetInstance();\n\n    EXPECT_EQ(1 + kTypedTestSuites, unit_test->successful_test_suite_count());\n    EXPECT_EQ(3 + kTypedTests, unit_test->successful_test_count());\n    EXPECT_EQ(0, unit_test->failed_test_suite_count());\n    EXPECT_EQ(0, unit_test->failed_test_count());\n    EXPECT_TRUE(unit_test->Passed());\n    EXPECT_FALSE(unit_test->Failed());\n    ASSERT_EQ(2 + kTypedTestSuites, unit_test->total_test_suite_count());\n\n    const TestSuite** const test_suites = UnitTestHelper::GetSortedTestSuites();\n\n    EXPECT_STREQ(\"ApiTest\", test_suites[0]->name());\n    EXPECT_TRUE(IsNull(test_suites[0]->type_param()));\n    EXPECT_TRUE(test_suites[0]->should_run());\n    EXPECT_EQ(1, test_suites[0]->disabled_test_count());\n    ASSERT_EQ(4, test_suites[0]->total_test_count());\n    EXPECT_EQ(3, test_suites[0]->successful_test_count());\n    EXPECT_EQ(0, test_suites[0]->failed_test_count());\n    EXPECT_TRUE(test_suites[0]->Passed());\n    EXPECT_FALSE(test_suites[0]->Failed());\n\n    EXPECT_STREQ(\"DISABLED_Test\", test_suites[1]->name());\n    EXPECT_TRUE(IsNull(test_suites[1]->type_param()));\n    EXPECT_FALSE(test_suites[1]->should_run());\n    EXPECT_EQ(1, test_suites[1]->disabled_test_count());\n    ASSERT_EQ(1, test_suites[1]->total_test_count());\n    EXPECT_EQ(0, test_suites[1]->successful_test_count());\n    EXPECT_EQ(0, test_suites[1]->failed_test_count());\n\n    EXPECT_STREQ(\"TestSuiteWithCommentTest/0\", test_suites[2]->name());\n    EXPECT_STREQ(GetTypeName<Types<int>>().c_str(),\n                 test_suites[2]->type_param());\n    EXPECT_TRUE(test_suites[2]->should_run());\n    EXPECT_EQ(0, test_suites[2]->disabled_test_count());\n    ASSERT_EQ(1, test_suites[2]->total_test_count());\n    EXPECT_EQ(1, test_suites[2]->successful_test_count());\n    EXPECT_EQ(0, test_suites[2]->failed_test_count());\n    EXPECT_TRUE(test_suites[2]->Passed());\n    EXPECT_FALSE(test_suites[2]->Failed());\n\n    const TestSuite* test_suite = UnitTestHelper::FindTestSuite(\"ApiTest\");\n    const TestInfo** tests = UnitTestHelper::GetSortedTests(test_suite);\n    EXPECT_STREQ(\"DISABLED_Dummy1\", tests[0]->name());\n    EXPECT_STREQ(\"ApiTest\", tests[0]->test_suite_name());\n    EXPECT_FALSE(tests[0]->should_run());\n\n    EXPECT_STREQ(\"TestSuiteDisabledAccessorsWork\", tests[1]->name());\n    EXPECT_STREQ(\"ApiTest\", tests[1]->test_suite_name());\n    EXPECT_TRUE(IsNull(tests[1]->value_param()));\n    EXPECT_TRUE(IsNull(tests[1]->type_param()));\n    EXPECT_TRUE(tests[1]->should_run());\n    EXPECT_TRUE(tests[1]->result()->Passed());\n    EXPECT_EQ(0, tests[1]->result()->test_property_count());\n\n    EXPECT_STREQ(\"TestSuiteImmutableAccessorsWork\", tests[2]->name());\n    EXPECT_STREQ(\"ApiTest\", tests[2]->test_suite_name());\n    EXPECT_TRUE(IsNull(tests[2]->value_param()));\n    EXPECT_TRUE(IsNull(tests[2]->type_param()));\n    EXPECT_TRUE(tests[2]->should_run());\n    EXPECT_TRUE(tests[2]->result()->Passed());\n    EXPECT_EQ(0, tests[2]->result()->test_property_count());\n\n    EXPECT_STREQ(\"UnitTestImmutableAccessorsWork\", tests[3]->name());\n    EXPECT_STREQ(\"ApiTest\", tests[3]->test_suite_name());\n    EXPECT_TRUE(IsNull(tests[3]->value_param()));\n    EXPECT_TRUE(IsNull(tests[3]->type_param()));\n    EXPECT_TRUE(tests[3]->should_run());\n    EXPECT_TRUE(tests[3]->result()->Passed());\n    EXPECT_EQ(1, tests[3]->result()->test_property_count());\n    const TestProperty& property = tests[3]->result()->GetTestProperty(0);\n    EXPECT_STREQ(\"key\", property.key());\n    EXPECT_STREQ(\"value\", property.value());\n\n    delete[] tests;\n\n    test_suite = UnitTestHelper::FindTestSuite(\"TestSuiteWithCommentTest/0\");\n    tests = UnitTestHelper::GetSortedTests(test_suite);\n\n    EXPECT_STREQ(\"Dummy\", tests[0]->name());\n    EXPECT_STREQ(\"TestSuiteWithCommentTest/0\", tests[0]->test_suite_name());\n    EXPECT_TRUE(IsNull(tests[0]->value_param()));\n    EXPECT_STREQ(GetTypeName<Types<int>>().c_str(), tests[0]->type_param());\n    EXPECT_TRUE(tests[0]->should_run());\n    EXPECT_TRUE(tests[0]->result()->Passed());\n    EXPECT_EQ(0, tests[0]->result()->test_property_count());\n\n    delete[] tests;\n    delete[] test_suites;\n  }\n};\n\n}  // namespace internal\n}  // namespace testing\n\nint main(int argc, char** argv) {\n  InitGoogleTest(&argc, argv);\n\n  AddGlobalTestEnvironment(new testing::internal::FinalSuccessChecker());\n\n  return RUN_ALL_TESTS();\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_all_test.cc",
    "content": "// Copyright 2009, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// Tests for Google C++ Testing and Mocking Framework (Google Test)\n//\n// Sometimes it's desirable to build most of Google Test's own tests\n// by compiling a single file.  This file serves this purpose.\n#include \"test/googletest-filepath-test.cc\"\n#include \"test/googletest-message-test.cc\"\n#include \"test/googletest-options-test.cc\"\n#include \"test/googletest-port-test.cc\"\n#include \"test/googletest-test-part-test.cc\"\n#include \"test/gtest-typed-test2_test.cc\"\n#include \"test/gtest-typed-test_test.cc\"\n#include \"test/gtest_pred_impl_unittest.cc\"\n#include \"test/gtest_prod_test.cc\"\n#include \"test/gtest_skip_test.cc\"\n#include \"test/gtest_unittest.cc\"\n#include \"test/production.cc\"\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_assert_by_exception_test.cc",
    "content": "// Copyright 2009, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Tests Google Test's assert-by-exception mode with exceptions enabled.\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <stdexcept>\n\n#include \"gtest/gtest.h\"\n\nclass ThrowListener : public testing::EmptyTestEventListener {\n  void OnTestPartResult(const testing::TestPartResult& result) override {\n    if (result.type() == testing::TestPartResult::kFatalFailure) {\n      throw testing::AssertionException(result);\n    }\n  }\n};\n\n// Prints the given failure message and exits the program with\n// non-zero.  We use this instead of a Google Test assertion to\n// indicate a failure, as the latter is been tested and cannot be\n// relied on.\nvoid Fail(const char* msg) {\n  printf(\"FAILURE: %s\\n\", msg);\n  fflush(stdout);\n  exit(1);\n}\n\nstatic void AssertFalse() { ASSERT_EQ(2, 3) << \"Expected failure\"; }\n\n// Tests that an assertion failure throws a subclass of\n// std::runtime_error.\nTEST(Test, Test) {\n  // A successful assertion shouldn't throw.\n  try {\n    EXPECT_EQ(3, 3);\n  } catch (...) {\n    Fail(\"A successful assertion wrongfully threw.\");\n  }\n\n  // A successful assertion shouldn't throw.\n  try {\n    EXPECT_EQ(3, 4);\n  } catch (...) {\n    Fail(\"A failed non-fatal assertion wrongfully threw.\");\n  }\n\n  // A failed assertion should throw.\n  try {\n    AssertFalse();\n  } catch (const testing::AssertionException& e) {\n    if (strstr(e.what(), \"Expected failure\") != nullptr) throw;\n\n    printf(\"%s\",\n           \"A failed assertion did throw an exception of the right type, \"\n           \"but the message is incorrect.  Instead of containing \\\"Expected \"\n           \"failure\\\", it is:\\n\");\n    Fail(e.what());\n  } catch (...) {\n    Fail(\"A failed assertion threw the wrong type of exception.\");\n  }\n  Fail(\"A failed assertion should've thrown but didn't.\");\n}\n\nint kTestForContinuingTest = 0;\n\nTEST(Test, Test2) { kTestForContinuingTest = 1; }\n\nint main(int argc, char** argv) {\n  testing::InitGoogleTest(&argc, argv);\n  testing::UnitTest::GetInstance()->listeners().Append(new ThrowListener);\n\n  int result = RUN_ALL_TESTS();\n  if (result == 0) {\n    printf(\"RUN_ALL_TESTS returned %d\\n\", result);\n    Fail(\"Expected failure instead.\");\n  }\n\n  if (kTestForContinuingTest == 0) {\n    Fail(\"Should have continued with other tests, but did not.\");\n  }\n  return 0;\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_environment_test.cc",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// Tests using global test environments.\n\n#include <stdio.h>\n#include <stdlib.h>\n\n#include \"gtest/gtest.h\"\n#include \"src/gtest-internal-inl.h\"\n\nnamespace {\n\nenum FailureType { NO_FAILURE, NON_FATAL_FAILURE, FATAL_FAILURE };\n\n// For testing using global test environments.\nclass MyEnvironment : public testing::Environment {\n public:\n  MyEnvironment() { Reset(); }\n\n  // Depending on the value of failure_in_set_up_, SetUp() will\n  // generate a non-fatal failure, generate a fatal failure, or\n  // succeed.\n  void SetUp() override {\n    set_up_was_run_ = true;\n\n    switch (failure_in_set_up_) {\n      case NON_FATAL_FAILURE:\n        ADD_FAILURE() << \"Expected non-fatal failure in global set-up.\";\n        break;\n      case FATAL_FAILURE:\n        FAIL() << \"Expected fatal failure in global set-up.\";\n        break;\n      default:\n        break;\n    }\n  }\n\n  // Generates a non-fatal failure.\n  void TearDown() override {\n    tear_down_was_run_ = true;\n    ADD_FAILURE() << \"Expected non-fatal failure in global tear-down.\";\n  }\n\n  // Resets the state of the environment s.t. it can be reused.\n  void Reset() {\n    failure_in_set_up_ = NO_FAILURE;\n    set_up_was_run_ = false;\n    tear_down_was_run_ = false;\n  }\n\n  // We call this function to set the type of failure SetUp() should\n  // generate.\n  void set_failure_in_set_up(FailureType type) { failure_in_set_up_ = type; }\n\n  // Was SetUp() run?\n  bool set_up_was_run() const { return set_up_was_run_; }\n\n  // Was TearDown() run?\n  bool tear_down_was_run() const { return tear_down_was_run_; }\n\n private:\n  FailureType failure_in_set_up_;\n  bool set_up_was_run_;\n  bool tear_down_was_run_;\n};\n\n// Was the TEST run?\nbool test_was_run;\n\n// The sole purpose of this TEST is to enable us to check whether it\n// was run.\nTEST(FooTest, Bar) { test_was_run = true; }\n\n// Prints the message and aborts the program if condition is false.\nvoid Check(bool condition, const char* msg) {\n  if (!condition) {\n    printf(\"FAILED: %s\\n\", msg);\n    testing::internal::posix::Abort();\n  }\n}\n\n// Runs the tests.  Return true if and only if successful.\n//\n// The 'failure' parameter specifies the type of failure that should\n// be generated by the global set-up.\nint RunAllTests(MyEnvironment* env, FailureType failure) {\n  env->Reset();\n  env->set_failure_in_set_up(failure);\n  test_was_run = false;\n  testing::internal::GetUnitTestImpl()->ClearAdHocTestResult();\n  return RUN_ALL_TESTS();\n}\n\n}  // namespace\n\nint main(int argc, char** argv) {\n  testing::InitGoogleTest(&argc, argv);\n\n  // Registers a global test environment, and verifies that the\n  // registration function returns its argument.\n  MyEnvironment* const env = new MyEnvironment;\n  Check(testing::AddGlobalTestEnvironment(env) == env,\n        \"AddGlobalTestEnvironment() should return its argument.\");\n\n  // Verifies that RUN_ALL_TESTS() runs the tests when the global\n  // set-up is successful.\n  Check(RunAllTests(env, NO_FAILURE) != 0,\n        \"RUN_ALL_TESTS() should return non-zero, as the global tear-down \"\n        \"should generate a failure.\");\n  Check(test_was_run,\n        \"The tests should run, as the global set-up should generate no \"\n        \"failure\");\n  Check(env->tear_down_was_run(),\n        \"The global tear-down should run, as the global set-up was run.\");\n\n  // Verifies that RUN_ALL_TESTS() runs the tests when the global\n  // set-up generates no fatal failure.\n  Check(RunAllTests(env, NON_FATAL_FAILURE) != 0,\n        \"RUN_ALL_TESTS() should return non-zero, as both the global set-up \"\n        \"and the global tear-down should generate a non-fatal failure.\");\n  Check(test_was_run,\n        \"The tests should run, as the global set-up should generate no \"\n        \"fatal failure.\");\n  Check(env->tear_down_was_run(),\n        \"The global tear-down should run, as the global set-up was run.\");\n\n  // Verifies that RUN_ALL_TESTS() runs no test when the global set-up\n  // generates a fatal failure.\n  Check(RunAllTests(env, FATAL_FAILURE) != 0,\n        \"RUN_ALL_TESTS() should return non-zero, as the global set-up \"\n        \"should generate a fatal failure.\");\n  Check(!test_was_run,\n        \"The tests should not run, as the global set-up should generate \"\n        \"a fatal failure.\");\n  Check(env->tear_down_was_run(),\n        \"The global tear-down should run, as the global set-up was run.\");\n\n  // Verifies that RUN_ALL_TESTS() doesn't do global set-up or\n  // tear-down when there is no test to run.\n  GTEST_FLAG_SET(filter, \"-*\");\n  Check(RunAllTests(env, NO_FAILURE) == 0,\n        \"RUN_ALL_TESTS() should return zero, as there is no test to run.\");\n  Check(!env->set_up_was_run(),\n        \"The global set-up should not run, as there is no test to run.\");\n  Check(!env->tear_down_was_run(),\n        \"The global tear-down should not run, \"\n        \"as the global set-up was not run.\");\n\n  printf(\"PASS\\n\");\n  return 0;\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_help_test.py",
    "content": "#!/usr/bin/env python\n#\n# Copyright 2009, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Tests the --help flag of Google C++ Testing and Mocking Framework.\n\nSYNOPSIS\n       gtest_help_test.py --build_dir=BUILD/DIR\n         # where BUILD/DIR contains the built gtest_help_test_ file.\n       gtest_help_test.py\n\"\"\"\n\nimport os\nimport re\nimport sys\nfrom googletest.test import gtest_test_utils\n\n\nIS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux'\nIS_GNUHURD = os.name == 'posix' and os.uname()[0] == 'GNU'\nIS_GNUKFREEBSD = os.name == 'posix' and os.uname()[0] == 'GNU/kFreeBSD'\nIS_OPENBSD = os.name == 'posix' and os.uname()[0] == 'OpenBSD'\nIS_WINDOWS = os.name == 'nt'\n\nPROGRAM_PATH = gtest_test_utils.GetTestExecutablePath('gtest_help_test_')\nFLAG_PREFIX = '--gtest_'\nDEATH_TEST_STYLE_FLAG = FLAG_PREFIX + 'death_test_style'\nSTREAM_RESULT_TO_FLAG = FLAG_PREFIX + 'stream_result_to'\nUNKNOWN_GTEST_PREFIXED_FLAG = FLAG_PREFIX + 'unknown_flag_for_testing'\nLIST_TESTS_FLAG = FLAG_PREFIX + 'list_tests'\nINTERNAL_FLAG_FOR_TESTING = FLAG_PREFIX + 'internal_flag_for_testing'\n\nSUPPORTS_DEATH_TESTS = \"DeathTest\" in gtest_test_utils.Subprocess(\n    [PROGRAM_PATH, LIST_TESTS_FLAG]).output\n\nHAS_ABSL_FLAGS = '--has_absl_flags' in sys.argv\n\n# The help message must match this regex.\nHELP_REGEX = re.compile(\n    FLAG_PREFIX + r'list_tests.*' +\n    FLAG_PREFIX + r'filter=.*' +\n    FLAG_PREFIX + r'also_run_disabled_tests.*' +\n    FLAG_PREFIX + r'repeat=.*' +\n    FLAG_PREFIX + r'shuffle.*' +\n    FLAG_PREFIX + r'random_seed=.*' +\n    FLAG_PREFIX + r'color=.*' +\n    FLAG_PREFIX + r'brief.*' +\n    FLAG_PREFIX + r'print_time.*' +\n    FLAG_PREFIX + r'output=.*' +\n    FLAG_PREFIX + r'break_on_failure.*' +\n    FLAG_PREFIX + r'throw_on_failure.*' +\n    FLAG_PREFIX + r'catch_exceptions=0.*',\n    re.DOTALL)\n\n\ndef RunWithFlag(flag):\n  \"\"\"Runs gtest_help_test_ with the given flag.\n\n  Returns:\n    the exit code and the text output as a tuple.\n  Args:\n    flag: the command-line flag to pass to gtest_help_test_, or None.\n  \"\"\"\n\n  if flag is None:\n    command = [PROGRAM_PATH]\n  else:\n    command = [PROGRAM_PATH, flag]\n  child = gtest_test_utils.Subprocess(command)\n  return child.exit_code, child.output\n\n\nclass GTestHelpTest(gtest_test_utils.TestCase):\n  \"\"\"Tests the --help flag and its equivalent forms.\"\"\"\n\n  def TestHelpFlag(self, flag):\n    \"\"\"Verifies correct behavior when help flag is specified.\n\n    The right message must be printed and the tests must\n    skipped when the given flag is specified.\n\n    Args:\n      flag:  A flag to pass to the binary or None.\n    \"\"\"\n\n    exit_code, output = RunWithFlag(flag)\n    if HAS_ABSL_FLAGS:\n      # The Abseil flags library prints the ProgramUsageMessage() with\n      # --help and returns 1.\n      self.assertEqual(1, exit_code)\n    else:\n      self.assertEqual(0, exit_code)\n\n    self.assertTrue(HELP_REGEX.search(output), output)\n\n    if IS_LINUX or IS_GNUHURD or IS_GNUKFREEBSD or IS_OPENBSD:\n      self.assertIn(STREAM_RESULT_TO_FLAG, output)\n    else:\n      self.assertNotIn(STREAM_RESULT_TO_FLAG, output)\n\n    if SUPPORTS_DEATH_TESTS and not IS_WINDOWS:\n      self.assertIn(DEATH_TEST_STYLE_FLAG, output)\n    else:\n      self.assertNotIn(DEATH_TEST_STYLE_FLAG, output)\n\n  def TestUnknownFlagWithAbseil(self, flag):\n    \"\"\"Verifies correct behavior when an unknown flag is specified.\n\n    The right message must be printed and the tests must\n    skipped when the given flag is specified.\n\n    Args:\n      flag:  A flag to pass to the binary or None.\n    \"\"\"\n    exit_code, output = RunWithFlag(flag)\n    self.assertEqual(1, exit_code)\n    self.assertIn('ERROR: Unknown command line flag', output)\n\n  def TestNonHelpFlag(self, flag):\n    \"\"\"Verifies correct behavior when no help flag is specified.\n\n    Verifies that when no help flag is specified, the tests are run\n    and the help message is not printed.\n\n    Args:\n      flag:  A flag to pass to the binary or None.\n    \"\"\"\n\n    exit_code, output = RunWithFlag(flag)\n    self.assertNotEqual(exit_code, 0)\n    self.assertFalse(HELP_REGEX.search(output), output)\n\n  def testPrintsHelpWithFullFlag(self):\n    self.TestHelpFlag('--help')\n\n  def testPrintsHelpWithUnrecognizedGoogleTestFlag(self):\n    # The behavior is slightly different when Abseil flags is\n    # used. Abseil flags rejects all unknown flags, while the builtin\n    # GTest flags implementation interprets an unknown flag with a\n    # '--gtest_' prefix as a request for help.\n    if HAS_ABSL_FLAGS:\n      self.TestUnknownFlagWithAbseil(UNKNOWN_GTEST_PREFIXED_FLAG)\n    else:\n      self.TestHelpFlag(UNKNOWN_GTEST_PREFIXED_FLAG)\n\n  def testRunsTestsWithoutHelpFlag(self):\n    \"\"\"Verifies that when no help flag is specified, the tests are run\n    and the help message is not printed.\"\"\"\n\n    self.TestNonHelpFlag(None)\n\n  def testRunsTestsWithGtestInternalFlag(self):\n    \"\"\"Verifies that the tests are run and no help message is printed when\n    a flag starting with Google Test prefix and 'internal_' is supplied.\"\"\"\n\n    self.TestNonHelpFlag(INTERNAL_FLAG_FOR_TESTING)\n\n\nif __name__ == '__main__':\n  if '--has_absl_flags' in sys.argv:\n    sys.argv.remove('--has_absl_flags')\n  gtest_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_help_test_.cc",
    "content": "// Copyright 2009, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// This program is meant to be run by gtest_help_test.py.  Do not run\n// it directly.\n\n#include \"gtest/gtest.h\"\n\n// When a help flag is specified, this program should skip the tests\n// and exit with 0; otherwise the following test will be executed,\n// causing this program to exit with a non-zero code.\nTEST(HelpFlagTest, ShouldNotBeRun) {\n  ASSERT_TRUE(false) << \"Tests shouldn't be run when --help is specified.\";\n}\n\n#if GTEST_HAS_DEATH_TEST\nTEST(DeathTest, UsedByPythonScriptToDetectSupportForDeathTestsInThisBinary) {}\n#endif\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_json_test_utils.py",
    "content": "# Copyright 2018, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Unit test utilities for gtest_json_output.\"\"\"\n\nimport re\n\n\ndef normalize(obj):\n  \"\"\"Normalize output object.\n\n  Args:\n     obj: Google Test's JSON output object to normalize.\n\n  Returns:\n     Normalized output without any references to transient information that may\n     change from run to run.\n  \"\"\"\n  def _normalize(key, value):\n    if key == 'time':\n      return re.sub(r'^\\d+(\\.\\d+)?s$', '*', value)\n    elif key == 'timestamp':\n      return re.sub(r'^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\dZ$', '*', value)\n    elif key == 'failure':\n      value = re.sub(r'^.*[/\\\\](.*:)\\d+\\n', '\\\\1*\\n', value)\n      return re.sub(r'Stack trace:\\n(.|\\n)*', 'Stack trace:\\n*', value)\n    elif key == 'file':\n      return re.sub(r'^.*[/\\\\](.*)', '\\\\1', value)\n    else:\n      return normalize(value)\n  if isinstance(obj, dict):\n    return {k: _normalize(k, v) for k, v in obj.items()}\n  if isinstance(obj, list):\n    return [normalize(x) for x in obj]\n  else:\n    return obj\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_list_output_unittest.py",
    "content": "#!/usr/bin/env python\n#\n# Copyright 2006, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"Unit test for Google Test's --gtest_list_tests flag.\n\nA user can ask Google Test to list all tests by specifying the\n--gtest_list_tests flag. If output is requested, via --gtest_output=xml\nor --gtest_output=json, the tests are listed, with extra information in the\noutput file.\nThis script tests such functionality by invoking gtest_list_output_unittest_\n (a program written with Google Test) the command line flags.\n\"\"\"\n\nimport os\nimport re\nfrom googletest.test import gtest_test_utils\n\nGTEST_LIST_TESTS_FLAG = '--gtest_list_tests'\nGTEST_OUTPUT_FLAG = '--gtest_output'\n\nEXPECTED_XML = \"\"\"<\\?xml version=\"1.0\" encoding=\"UTF-8\"\\?>\n<testsuites tests=\"16\" name=\"AllTests\">\n  <testsuite name=\"FooTest\" tests=\"2\">\n    <testcase name=\"Test1\" file=\".*gtest_list_output_unittest_.cc\" line=\"43\" />\n    <testcase name=\"Test2\" file=\".*gtest_list_output_unittest_.cc\" line=\"45\" />\n  </testsuite>\n  <testsuite name=\"FooTestFixture\" tests=\"2\">\n    <testcase name=\"Test3\" file=\".*gtest_list_output_unittest_.cc\" line=\"48\" />\n    <testcase name=\"Test4\" file=\".*gtest_list_output_unittest_.cc\" line=\"49\" />\n  </testsuite>\n  <testsuite name=\"TypedTest/0\" tests=\"2\">\n    <testcase name=\"Test7\" type_param=\"int\" file=\".*gtest_list_output_unittest_.cc\" line=\"60\" />\n    <testcase name=\"Test8\" type_param=\"int\" file=\".*gtest_list_output_unittest_.cc\" line=\"61\" />\n  </testsuite>\n  <testsuite name=\"TypedTest/1\" tests=\"2\">\n    <testcase name=\"Test7\" type_param=\"bool\" file=\".*gtest_list_output_unittest_.cc\" line=\"60\" />\n    <testcase name=\"Test8\" type_param=\"bool\" file=\".*gtest_list_output_unittest_.cc\" line=\"61\" />\n  </testsuite>\n  <testsuite name=\"Single/TypeParameterizedTestSuite/0\" tests=\"2\">\n    <testcase name=\"Test9\" type_param=\"int\" file=\".*gtest_list_output_unittest_.cc\" line=\"66\" />\n    <testcase name=\"Test10\" type_param=\"int\" file=\".*gtest_list_output_unittest_.cc\" line=\"67\" />\n  </testsuite>\n  <testsuite name=\"Single/TypeParameterizedTestSuite/1\" tests=\"2\">\n    <testcase name=\"Test9\" type_param=\"bool\" file=\".*gtest_list_output_unittest_.cc\" line=\"66\" />\n    <testcase name=\"Test10\" type_param=\"bool\" file=\".*gtest_list_output_unittest_.cc\" line=\"67\" />\n  </testsuite>\n  <testsuite name=\"ValueParam/ValueParamTest\" tests=\"4\">\n    <testcase name=\"Test5/0\" value_param=\"33\" file=\".*gtest_list_output_unittest_.cc\" line=\"52\" />\n    <testcase name=\"Test5/1\" value_param=\"42\" file=\".*gtest_list_output_unittest_.cc\" line=\"52\" />\n    <testcase name=\"Test6/0\" value_param=\"33\" file=\".*gtest_list_output_unittest_.cc\" line=\"53\" />\n    <testcase name=\"Test6/1\" value_param=\"42\" file=\".*gtest_list_output_unittest_.cc\" line=\"53\" />\n  </testsuite>\n</testsuites>\n\"\"\"\n\nEXPECTED_JSON = \"\"\"{\n  \"tests\": 16,\n  \"name\": \"AllTests\",\n  \"testsuites\": \\[\n    {\n      \"name\": \"FooTest\",\n      \"tests\": 2,\n      \"testsuite\": \\[\n        {\n          \"name\": \"Test1\",\n          \"file\": \".*gtest_list_output_unittest_.cc\",\n          \"line\": 43\n        },\n        {\n          \"name\": \"Test2\",\n          \"file\": \".*gtest_list_output_unittest_.cc\",\n          \"line\": 45\n        }\n      \\]\n    },\n    {\n      \"name\": \"FooTestFixture\",\n      \"tests\": 2,\n      \"testsuite\": \\[\n        {\n          \"name\": \"Test3\",\n          \"file\": \".*gtest_list_output_unittest_.cc\",\n          \"line\": 48\n        },\n        {\n          \"name\": \"Test4\",\n          \"file\": \".*gtest_list_output_unittest_.cc\",\n          \"line\": 49\n        }\n      \\]\n    },\n    {\n      \"name\": \"TypedTest\\\\\\\\/0\",\n      \"tests\": 2,\n      \"testsuite\": \\[\n        {\n          \"name\": \"Test7\",\n          \"type_param\": \"int\",\n          \"file\": \".*gtest_list_output_unittest_.cc\",\n          \"line\": 60\n        },\n        {\n          \"name\": \"Test8\",\n          \"type_param\": \"int\",\n          \"file\": \".*gtest_list_output_unittest_.cc\",\n          \"line\": 61\n        }\n      \\]\n    },\n    {\n      \"name\": \"TypedTest\\\\\\\\/1\",\n      \"tests\": 2,\n      \"testsuite\": \\[\n        {\n          \"name\": \"Test7\",\n          \"type_param\": \"bool\",\n          \"file\": \".*gtest_list_output_unittest_.cc\",\n          \"line\": 60\n        },\n        {\n          \"name\": \"Test8\",\n          \"type_param\": \"bool\",\n          \"file\": \".*gtest_list_output_unittest_.cc\",\n          \"line\": 61\n        }\n      \\]\n    },\n    {\n      \"name\": \"Single\\\\\\\\/TypeParameterizedTestSuite\\\\\\\\/0\",\n      \"tests\": 2,\n      \"testsuite\": \\[\n        {\n          \"name\": \"Test9\",\n          \"type_param\": \"int\",\n          \"file\": \".*gtest_list_output_unittest_.cc\",\n          \"line\": 66\n        },\n        {\n          \"name\": \"Test10\",\n          \"type_param\": \"int\",\n          \"file\": \".*gtest_list_output_unittest_.cc\",\n          \"line\": 67\n        }\n      \\]\n    },\n    {\n      \"name\": \"Single\\\\\\\\/TypeParameterizedTestSuite\\\\\\\\/1\",\n      \"tests\": 2,\n      \"testsuite\": \\[\n        {\n          \"name\": \"Test9\",\n          \"type_param\": \"bool\",\n          \"file\": \".*gtest_list_output_unittest_.cc\",\n          \"line\": 66\n        },\n        {\n          \"name\": \"Test10\",\n          \"type_param\": \"bool\",\n          \"file\": \".*gtest_list_output_unittest_.cc\",\n          \"line\": 67\n        }\n      \\]\n    },\n    {\n      \"name\": \"ValueParam\\\\\\\\/ValueParamTest\",\n      \"tests\": 4,\n      \"testsuite\": \\[\n        {\n          \"name\": \"Test5\\\\\\\\/0\",\n          \"value_param\": \"33\",\n          \"file\": \".*gtest_list_output_unittest_.cc\",\n          \"line\": 52\n        },\n        {\n          \"name\": \"Test5\\\\\\\\/1\",\n          \"value_param\": \"42\",\n          \"file\": \".*gtest_list_output_unittest_.cc\",\n          \"line\": 52\n        },\n        {\n          \"name\": \"Test6\\\\\\\\/0\",\n          \"value_param\": \"33\",\n          \"file\": \".*gtest_list_output_unittest_.cc\",\n          \"line\": 53\n        },\n        {\n          \"name\": \"Test6\\\\\\\\/1\",\n          \"value_param\": \"42\",\n          \"file\": \".*gtest_list_output_unittest_.cc\",\n          \"line\": 53\n        }\n      \\]\n    }\n  \\]\n}\n\"\"\"\n\n\nclass GTestListTestsOutputUnitTest(gtest_test_utils.TestCase):\n  \"\"\"Unit test for Google Test's list tests with output to file functionality.\n  \"\"\"\n\n  def testXml(self):\n    \"\"\"Verifies XML output for listing tests in a Google Test binary.\n\n    Runs a test program that generates an empty XML output, and\n    tests that the XML output is expected.\n    \"\"\"\n    self._TestOutput('xml', EXPECTED_XML)\n\n  def testJSON(self):\n    \"\"\"Verifies XML output for listing tests in a Google Test binary.\n\n    Runs a test program that generates an empty XML output, and\n    tests that the XML output is expected.\n    \"\"\"\n    self._TestOutput('json', EXPECTED_JSON)\n\n  def _GetOutput(self, out_format):\n    file_path = os.path.join(gtest_test_utils.GetTempDir(),\n                             'test_out.' + out_format)\n    gtest_prog_path = gtest_test_utils.GetTestExecutablePath(\n        'gtest_list_output_unittest_')\n\n    command = ([\n        gtest_prog_path,\n        '%s=%s:%s' % (GTEST_OUTPUT_FLAG, out_format, file_path),\n        '--gtest_list_tests'\n    ])\n    environ_copy = os.environ.copy()\n    p = gtest_test_utils.Subprocess(\n        command, env=environ_copy, working_dir=gtest_test_utils.GetTempDir())\n\n    self.assertTrue(p.exited)\n    self.assertEqual(0, p.exit_code)\n    self.assertTrue(os.path.isfile(file_path))\n    with open(file_path) as f:\n      result = f.read()\n    return result\n\n  def _TestOutput(self, test_format, expected_output):\n    actual = self._GetOutput(test_format)\n    actual_lines = actual.splitlines()\n    expected_lines = expected_output.splitlines()\n    line_count = 0\n    for actual_line in actual_lines:\n      expected_line = expected_lines[line_count]\n      expected_line_re = re.compile(expected_line.strip())\n      self.assertTrue(\n          expected_line_re.match(actual_line.strip()),\n          ('actual output of \"%s\",\\n'\n           'which does not match expected regex of \"%s\"\\n'\n           'on line %d' % (actual, expected_output, line_count)))\n      line_count = line_count + 1\n\n\nif __name__ == '__main__':\n  os.environ['GTEST_STACK_TRACE_DEPTH'] = '1'\n  gtest_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_list_output_unittest_.cc",
    "content": "// Copyright 2018, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Author: david.schuldenfrei@gmail.com (David Schuldenfrei)\n\n// Unit test for Google Test's --gtest_list_tests and --gtest_output flag.\n//\n// A user can ask Google Test to list all tests that will run,\n// and have the output saved in a Json/Xml file.\n// The tests will not be run after listing.\n//\n// This program will be invoked from a Python unit test.\n// Don't run it directly.\n\n#include \"gtest/gtest.h\"\n\nTEST(FooTest, Test1) {}\n\nTEST(FooTest, Test2) {}\n\nclass FooTestFixture : public ::testing::Test {};\nTEST_F(FooTestFixture, Test3) {}\nTEST_F(FooTestFixture, Test4) {}\n\nclass ValueParamTest : public ::testing::TestWithParam<int> {};\nTEST_P(ValueParamTest, Test5) {}\nTEST_P(ValueParamTest, Test6) {}\nINSTANTIATE_TEST_SUITE_P(ValueParam, ValueParamTest, ::testing::Values(33, 42));\n\ntemplate <typename T>\nclass TypedTest : public ::testing::Test {};\ntypedef testing::Types<int, bool> TypedTestTypes;\nTYPED_TEST_SUITE(TypedTest, TypedTestTypes);\nTYPED_TEST(TypedTest, Test7) {}\nTYPED_TEST(TypedTest, Test8) {}\n\ntemplate <typename T>\nclass TypeParameterizedTestSuite : public ::testing::Test {};\nTYPED_TEST_SUITE_P(TypeParameterizedTestSuite);\nTYPED_TEST_P(TypeParameterizedTestSuite, Test9) {}\nTYPED_TEST_P(TypeParameterizedTestSuite, Test10) {}\nREGISTER_TYPED_TEST_SUITE_P(TypeParameterizedTestSuite, Test9, Test10);\ntypedef testing::Types<int, bool> TypeParameterizedTestSuiteTypes;  // NOLINT\nINSTANTIATE_TYPED_TEST_SUITE_P(Single, TypeParameterizedTestSuite,\n                               TypeParameterizedTestSuiteTypes);\n\nint main(int argc, char **argv) {\n  ::testing::InitGoogleTest(&argc, argv);\n\n  return RUN_ALL_TESTS();\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_main_unittest.cc",
    "content": "// Copyright 2006, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"gtest/gtest.h\"\n\n// Tests that we don't have to define main() when we link to\n// gtest_main instead of gtest.\n\nnamespace {\n\nTEST(GTestMainTest, ShouldSucceed) {}\n\n}  // namespace\n\n// We are using the main() function defined in gtest_main.cc, so we\n// don't define it here.\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_no_test_unittest.cc",
    "content": "// Copyright 2006, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Tests that a Google Test program that has no test defined can run\n// successfully.\n\n#include \"gtest/gtest.h\"\n\nint main(int argc, char **argv) {\n  testing::InitGoogleTest(&argc, argv);\n\n  // An ad-hoc assertion outside of all tests.\n  //\n  // This serves three purposes:\n  //\n  // 1. It verifies that an ad-hoc assertion can be executed even if\n  //    no test is defined.\n  // 2. It verifies that a failed ad-hoc assertion causes the test\n  //    program to fail.\n  // 3. We had a bug where the XML output won't be generated if an\n  //    assertion is executed before RUN_ALL_TESTS() is called, even\n  //    though --gtest_output=xml is specified.  This makes sure the\n  //    bug is fixed and doesn't regress.\n  EXPECT_EQ(1, 2);\n\n  // The above EXPECT_EQ() should cause RUN_ALL_TESTS() to return non-zero.\n  return RUN_ALL_TESTS() ? 0 : 1;\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_pred_impl_unittest.cc",
    "content": "// Copyright 2006, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Regression test for gtest_pred_impl.h\n//\n// This file is generated by a script and quite long.  If you intend to\n// learn how Google Test works by reading its unit tests, read\n// gtest_unittest.cc instead.\n//\n// This is intended as a regression test for the Google Test predicate\n// assertions.  We compile it as part of the gtest_unittest target\n// only to keep the implementation tidy and compact, as it is quite\n// involved to set up the stage for testing Google Test using Google\n// Test itself.\n//\n// Currently, gtest_unittest takes ~11 seconds to run in the testing\n// daemon.  In the future, if it grows too large and needs much more\n// time to finish, we should consider separating this file into a\n// stand-alone regression test.\n\n#include <iostream>\n\n#include \"gtest/gtest-spi.h\"\n#include \"gtest/gtest.h\"\n\n// A user-defined data type.\nstruct Bool {\n  explicit Bool(int val) : value(val != 0) {}\n\n  bool operator>(int n) const { return value > Bool(n).value; }\n\n  Bool operator+(const Bool& rhs) const { return Bool(value + rhs.value); }\n\n  bool operator==(const Bool& rhs) const { return value == rhs.value; }\n\n  bool value;\n};\n\n// Enables Bool to be used in assertions.\nstd::ostream& operator<<(std::ostream& os, const Bool& x) {\n  return os << (x.value ? \"true\" : \"false\");\n}\n\n// Sample functions/functors for testing unary predicate assertions.\n\n// A unary predicate function.\ntemplate <typename T1>\nbool PredFunction1(T1 v1) {\n  return v1 > 0;\n}\n\n// The following two functions are needed because a compiler doesn't have\n// a context yet to know which template function must be instantiated.\nbool PredFunction1Int(int v1) { return v1 > 0; }\nbool PredFunction1Bool(Bool v1) { return v1 > 0; }\n\n// A unary predicate functor.\nstruct PredFunctor1 {\n  template <typename T1>\n  bool operator()(const T1& v1) {\n    return v1 > 0;\n  }\n};\n\n// A unary predicate-formatter function.\ntemplate <typename T1>\ntesting::AssertionResult PredFormatFunction1(const char* e1, const T1& v1) {\n  if (PredFunction1(v1)) return testing::AssertionSuccess();\n\n  return testing::AssertionFailure()\n         << e1 << \" is expected to be positive, but evaluates to \" << v1 << \".\";\n}\n\n// A unary predicate-formatter functor.\nstruct PredFormatFunctor1 {\n  template <typename T1>\n  testing::AssertionResult operator()(const char* e1, const T1& v1) const {\n    return PredFormatFunction1(e1, v1);\n  }\n};\n\n// Tests for {EXPECT|ASSERT}_PRED_FORMAT1.\n\nclass Predicate1Test : public testing::Test {\n protected:\n  void SetUp() override {\n    expected_to_finish_ = true;\n    finished_ = false;\n    n1_ = 0;\n  }\n\n  void TearDown() override {\n    // Verifies that each of the predicate's arguments was evaluated\n    // exactly once.\n    EXPECT_EQ(1, n1_) << \"The predicate assertion didn't evaluate argument 2 \"\n                         \"exactly once.\";\n\n    // Verifies that the control flow in the test function is expected.\n    if (expected_to_finish_ && !finished_) {\n      FAIL() << \"The predicate assertion unexpectedly aborted the test.\";\n    } else if (!expected_to_finish_ && finished_) {\n      FAIL() << \"The failed predicate assertion didn't abort the test \"\n                \"as expected.\";\n    }\n  }\n\n  // true if and only if the test function is expected to run to finish.\n  static bool expected_to_finish_;\n\n  // true if and only if the test function did run to finish.\n  static bool finished_;\n\n  static int n1_;\n};\n\nbool Predicate1Test::expected_to_finish_;\nbool Predicate1Test::finished_;\nint Predicate1Test::n1_;\n\ntypedef Predicate1Test EXPECT_PRED_FORMAT1Test;\ntypedef Predicate1Test ASSERT_PRED_FORMAT1Test;\ntypedef Predicate1Test EXPECT_PRED1Test;\ntypedef Predicate1Test ASSERT_PRED1Test;\n\n// Tests a successful EXPECT_PRED1 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(EXPECT_PRED1Test, FunctionOnBuiltInTypeSuccess) {\n  EXPECT_PRED1(PredFunction1Int, ++n1_);\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED1 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(EXPECT_PRED1Test, FunctionOnUserTypeSuccess) {\n  EXPECT_PRED1(PredFunction1Bool, Bool(++n1_));\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED1 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(EXPECT_PRED1Test, FunctorOnBuiltInTypeSuccess) {\n  EXPECT_PRED1(PredFunctor1(), ++n1_);\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED1 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(EXPECT_PRED1Test, FunctorOnUserTypeSuccess) {\n  EXPECT_PRED1(PredFunctor1(), Bool(++n1_));\n  finished_ = true;\n}\n\n// Tests a failed EXPECT_PRED1 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(EXPECT_PRED1Test, FunctionOnBuiltInTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED1(PredFunction1Int, n1_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED1 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(EXPECT_PRED1Test, FunctionOnUserTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED1(PredFunction1Bool, Bool(n1_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED1 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(EXPECT_PRED1Test, FunctorOnBuiltInTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED1(PredFunctor1(), n1_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED1 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(EXPECT_PRED1Test, FunctorOnUserTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED1(PredFunctor1(), Bool(n1_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a successful ASSERT_PRED1 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(ASSERT_PRED1Test, FunctionOnBuiltInTypeSuccess) {\n  ASSERT_PRED1(PredFunction1Int, ++n1_);\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED1 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(ASSERT_PRED1Test, FunctionOnUserTypeSuccess) {\n  ASSERT_PRED1(PredFunction1Bool, Bool(++n1_));\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED1 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(ASSERT_PRED1Test, FunctorOnBuiltInTypeSuccess) {\n  ASSERT_PRED1(PredFunctor1(), ++n1_);\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED1 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(ASSERT_PRED1Test, FunctorOnUserTypeSuccess) {\n  ASSERT_PRED1(PredFunctor1(), Bool(++n1_));\n  finished_ = true;\n}\n\n// Tests a failed ASSERT_PRED1 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(ASSERT_PRED1Test, FunctionOnBuiltInTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED1(PredFunction1Int, n1_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED1 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(ASSERT_PRED1Test, FunctionOnUserTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED1(PredFunction1Bool, Bool(n1_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED1 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(ASSERT_PRED1Test, FunctorOnBuiltInTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED1(PredFunctor1(), n1_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED1 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(ASSERT_PRED1Test, FunctorOnUserTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED1(PredFunctor1(), Bool(n1_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a successful EXPECT_PRED_FORMAT1 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnBuiltInTypeSuccess) {\n  EXPECT_PRED_FORMAT1(PredFormatFunction1, ++n1_);\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED_FORMAT1 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnUserTypeSuccess) {\n  EXPECT_PRED_FORMAT1(PredFormatFunction1, Bool(++n1_));\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED_FORMAT1 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnBuiltInTypeSuccess) {\n  EXPECT_PRED_FORMAT1(PredFormatFunctor1(), ++n1_);\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED_FORMAT1 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnUserTypeSuccess) {\n  EXPECT_PRED_FORMAT1(PredFormatFunctor1(), Bool(++n1_));\n  finished_ = true;\n}\n\n// Tests a failed EXPECT_PRED_FORMAT1 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnBuiltInTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT1(PredFormatFunction1, n1_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED_FORMAT1 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(EXPECT_PRED_FORMAT1Test, FunctionOnUserTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT1(PredFormatFunction1, Bool(n1_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED_FORMAT1 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnBuiltInTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT1(PredFormatFunctor1(), n1_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED_FORMAT1 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(EXPECT_PRED_FORMAT1Test, FunctorOnUserTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT1(PredFormatFunctor1(), Bool(n1_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a successful ASSERT_PRED_FORMAT1 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnBuiltInTypeSuccess) {\n  ASSERT_PRED_FORMAT1(PredFormatFunction1, ++n1_);\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED_FORMAT1 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnUserTypeSuccess) {\n  ASSERT_PRED_FORMAT1(PredFormatFunction1, Bool(++n1_));\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED_FORMAT1 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnBuiltInTypeSuccess) {\n  ASSERT_PRED_FORMAT1(PredFormatFunctor1(), ++n1_);\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED_FORMAT1 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnUserTypeSuccess) {\n  ASSERT_PRED_FORMAT1(PredFormatFunctor1(), Bool(++n1_));\n  finished_ = true;\n}\n\n// Tests a failed ASSERT_PRED_FORMAT1 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnBuiltInTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED_FORMAT1(PredFormatFunction1, n1_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED_FORMAT1 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(ASSERT_PRED_FORMAT1Test, FunctionOnUserTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED_FORMAT1(PredFormatFunction1, Bool(n1_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED_FORMAT1 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnBuiltInTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED_FORMAT1(PredFormatFunctor1(), n1_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED_FORMAT1 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(ASSERT_PRED_FORMAT1Test, FunctorOnUserTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED_FORMAT1(PredFormatFunctor1(), Bool(n1_++));\n        finished_ = true;\n      },\n      \"\");\n}\n// Sample functions/functors for testing binary predicate assertions.\n\n// A binary predicate function.\ntemplate <typename T1, typename T2>\nbool PredFunction2(T1 v1, T2 v2) {\n  return v1 + v2 > 0;\n}\n\n// The following two functions are needed because a compiler doesn't have\n// a context yet to know which template function must be instantiated.\nbool PredFunction2Int(int v1, int v2) { return v1 + v2 > 0; }\nbool PredFunction2Bool(Bool v1, Bool v2) { return v1 + v2 > 0; }\n\n// A binary predicate functor.\nstruct PredFunctor2 {\n  template <typename T1, typename T2>\n  bool operator()(const T1& v1, const T2& v2) {\n    return v1 + v2 > 0;\n  }\n};\n\n// A binary predicate-formatter function.\ntemplate <typename T1, typename T2>\ntesting::AssertionResult PredFormatFunction2(const char* e1, const char* e2,\n                                             const T1& v1, const T2& v2) {\n  if (PredFunction2(v1, v2)) return testing::AssertionSuccess();\n\n  return testing::AssertionFailure()\n         << e1 << \" + \" << e2\n         << \" is expected to be positive, but evaluates to \" << v1 + v2 << \".\";\n}\n\n// A binary predicate-formatter functor.\nstruct PredFormatFunctor2 {\n  template <typename T1, typename T2>\n  testing::AssertionResult operator()(const char* e1, const char* e2,\n                                      const T1& v1, const T2& v2) const {\n    return PredFormatFunction2(e1, e2, v1, v2);\n  }\n};\n\n// Tests for {EXPECT|ASSERT}_PRED_FORMAT2.\n\nclass Predicate2Test : public testing::Test {\n protected:\n  void SetUp() override {\n    expected_to_finish_ = true;\n    finished_ = false;\n    n1_ = n2_ = 0;\n  }\n\n  void TearDown() override {\n    // Verifies that each of the predicate's arguments was evaluated\n    // exactly once.\n    EXPECT_EQ(1, n1_) << \"The predicate assertion didn't evaluate argument 2 \"\n                         \"exactly once.\";\n    EXPECT_EQ(1, n2_) << \"The predicate assertion didn't evaluate argument 3 \"\n                         \"exactly once.\";\n\n    // Verifies that the control flow in the test function is expected.\n    if (expected_to_finish_ && !finished_) {\n      FAIL() << \"The predicate assertion unexpectedly aborted the test.\";\n    } else if (!expected_to_finish_ && finished_) {\n      FAIL() << \"The failed predicate assertion didn't abort the test \"\n                \"as expected.\";\n    }\n  }\n\n  // true if and only if the test function is expected to run to finish.\n  static bool expected_to_finish_;\n\n  // true if and only if the test function did run to finish.\n  static bool finished_;\n\n  static int n1_;\n  static int n2_;\n};\n\nbool Predicate2Test::expected_to_finish_;\nbool Predicate2Test::finished_;\nint Predicate2Test::n1_;\nint Predicate2Test::n2_;\n\ntypedef Predicate2Test EXPECT_PRED_FORMAT2Test;\ntypedef Predicate2Test ASSERT_PRED_FORMAT2Test;\ntypedef Predicate2Test EXPECT_PRED2Test;\ntypedef Predicate2Test ASSERT_PRED2Test;\n\n// Tests a successful EXPECT_PRED2 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(EXPECT_PRED2Test, FunctionOnBuiltInTypeSuccess) {\n  EXPECT_PRED2(PredFunction2Int, ++n1_, ++n2_);\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED2 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(EXPECT_PRED2Test, FunctionOnUserTypeSuccess) {\n  EXPECT_PRED2(PredFunction2Bool, Bool(++n1_), Bool(++n2_));\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED2 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(EXPECT_PRED2Test, FunctorOnBuiltInTypeSuccess) {\n  EXPECT_PRED2(PredFunctor2(), ++n1_, ++n2_);\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED2 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(EXPECT_PRED2Test, FunctorOnUserTypeSuccess) {\n  EXPECT_PRED2(PredFunctor2(), Bool(++n1_), Bool(++n2_));\n  finished_ = true;\n}\n\n// Tests a failed EXPECT_PRED2 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(EXPECT_PRED2Test, FunctionOnBuiltInTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED2(PredFunction2Int, n1_++, n2_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED2 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(EXPECT_PRED2Test, FunctionOnUserTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED2(PredFunction2Bool, Bool(n1_++), Bool(n2_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED2 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(EXPECT_PRED2Test, FunctorOnBuiltInTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED2(PredFunctor2(), n1_++, n2_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED2 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(EXPECT_PRED2Test, FunctorOnUserTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED2(PredFunctor2(), Bool(n1_++), Bool(n2_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a successful ASSERT_PRED2 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(ASSERT_PRED2Test, FunctionOnBuiltInTypeSuccess) {\n  ASSERT_PRED2(PredFunction2Int, ++n1_, ++n2_);\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED2 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(ASSERT_PRED2Test, FunctionOnUserTypeSuccess) {\n  ASSERT_PRED2(PredFunction2Bool, Bool(++n1_), Bool(++n2_));\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED2 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(ASSERT_PRED2Test, FunctorOnBuiltInTypeSuccess) {\n  ASSERT_PRED2(PredFunctor2(), ++n1_, ++n2_);\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED2 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(ASSERT_PRED2Test, FunctorOnUserTypeSuccess) {\n  ASSERT_PRED2(PredFunctor2(), Bool(++n1_), Bool(++n2_));\n  finished_ = true;\n}\n\n// Tests a failed ASSERT_PRED2 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(ASSERT_PRED2Test, FunctionOnBuiltInTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED2(PredFunction2Int, n1_++, n2_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED2 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(ASSERT_PRED2Test, FunctionOnUserTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED2(PredFunction2Bool, Bool(n1_++), Bool(n2_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED2 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(ASSERT_PRED2Test, FunctorOnBuiltInTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED2(PredFunctor2(), n1_++, n2_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED2 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(ASSERT_PRED2Test, FunctorOnUserTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED2(PredFunctor2(), Bool(n1_++), Bool(n2_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a successful EXPECT_PRED_FORMAT2 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnBuiltInTypeSuccess) {\n  EXPECT_PRED_FORMAT2(PredFormatFunction2, ++n1_, ++n2_);\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED_FORMAT2 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnUserTypeSuccess) {\n  EXPECT_PRED_FORMAT2(PredFormatFunction2, Bool(++n1_), Bool(++n2_));\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED_FORMAT2 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnBuiltInTypeSuccess) {\n  EXPECT_PRED_FORMAT2(PredFormatFunctor2(), ++n1_, ++n2_);\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED_FORMAT2 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnUserTypeSuccess) {\n  EXPECT_PRED_FORMAT2(PredFormatFunctor2(), Bool(++n1_), Bool(++n2_));\n  finished_ = true;\n}\n\n// Tests a failed EXPECT_PRED_FORMAT2 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnBuiltInTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT2(PredFormatFunction2, n1_++, n2_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED_FORMAT2 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(EXPECT_PRED_FORMAT2Test, FunctionOnUserTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT2(PredFormatFunction2, Bool(n1_++), Bool(n2_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED_FORMAT2 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnBuiltInTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT2(PredFormatFunctor2(), n1_++, n2_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED_FORMAT2 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(EXPECT_PRED_FORMAT2Test, FunctorOnUserTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT2(PredFormatFunctor2(), Bool(n1_++), Bool(n2_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a successful ASSERT_PRED_FORMAT2 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnBuiltInTypeSuccess) {\n  ASSERT_PRED_FORMAT2(PredFormatFunction2, ++n1_, ++n2_);\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED_FORMAT2 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnUserTypeSuccess) {\n  ASSERT_PRED_FORMAT2(PredFormatFunction2, Bool(++n1_), Bool(++n2_));\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED_FORMAT2 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnBuiltInTypeSuccess) {\n  ASSERT_PRED_FORMAT2(PredFormatFunctor2(), ++n1_, ++n2_);\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED_FORMAT2 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnUserTypeSuccess) {\n  ASSERT_PRED_FORMAT2(PredFormatFunctor2(), Bool(++n1_), Bool(++n2_));\n  finished_ = true;\n}\n\n// Tests a failed ASSERT_PRED_FORMAT2 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnBuiltInTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED_FORMAT2(PredFormatFunction2, n1_++, n2_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED_FORMAT2 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(ASSERT_PRED_FORMAT2Test, FunctionOnUserTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED_FORMAT2(PredFormatFunction2, Bool(n1_++), Bool(n2_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED_FORMAT2 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnBuiltInTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED_FORMAT2(PredFormatFunctor2(), n1_++, n2_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED_FORMAT2 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(ASSERT_PRED_FORMAT2Test, FunctorOnUserTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED_FORMAT2(PredFormatFunctor2(), Bool(n1_++), Bool(n2_++));\n        finished_ = true;\n      },\n      \"\");\n}\n// Sample functions/functors for testing ternary predicate assertions.\n\n// A ternary predicate function.\ntemplate <typename T1, typename T2, typename T3>\nbool PredFunction3(T1 v1, T2 v2, T3 v3) {\n  return v1 + v2 + v3 > 0;\n}\n\n// The following two functions are needed because a compiler doesn't have\n// a context yet to know which template function must be instantiated.\nbool PredFunction3Int(int v1, int v2, int v3) { return v1 + v2 + v3 > 0; }\nbool PredFunction3Bool(Bool v1, Bool v2, Bool v3) { return v1 + v2 + v3 > 0; }\n\n// A ternary predicate functor.\nstruct PredFunctor3 {\n  template <typename T1, typename T2, typename T3>\n  bool operator()(const T1& v1, const T2& v2, const T3& v3) {\n    return v1 + v2 + v3 > 0;\n  }\n};\n\n// A ternary predicate-formatter function.\ntemplate <typename T1, typename T2, typename T3>\ntesting::AssertionResult PredFormatFunction3(const char* e1, const char* e2,\n                                             const char* e3, const T1& v1,\n                                             const T2& v2, const T3& v3) {\n  if (PredFunction3(v1, v2, v3)) return testing::AssertionSuccess();\n\n  return testing::AssertionFailure()\n         << e1 << \" + \" << e2 << \" + \" << e3\n         << \" is expected to be positive, but evaluates to \" << v1 + v2 + v3\n         << \".\";\n}\n\n// A ternary predicate-formatter functor.\nstruct PredFormatFunctor3 {\n  template <typename T1, typename T2, typename T3>\n  testing::AssertionResult operator()(const char* e1, const char* e2,\n                                      const char* e3, const T1& v1,\n                                      const T2& v2, const T3& v3) const {\n    return PredFormatFunction3(e1, e2, e3, v1, v2, v3);\n  }\n};\n\n// Tests for {EXPECT|ASSERT}_PRED_FORMAT3.\n\nclass Predicate3Test : public testing::Test {\n protected:\n  void SetUp() override {\n    expected_to_finish_ = true;\n    finished_ = false;\n    n1_ = n2_ = n3_ = 0;\n  }\n\n  void TearDown() override {\n    // Verifies that each of the predicate's arguments was evaluated\n    // exactly once.\n    EXPECT_EQ(1, n1_) << \"The predicate assertion didn't evaluate argument 2 \"\n                         \"exactly once.\";\n    EXPECT_EQ(1, n2_) << \"The predicate assertion didn't evaluate argument 3 \"\n                         \"exactly once.\";\n    EXPECT_EQ(1, n3_) << \"The predicate assertion didn't evaluate argument 4 \"\n                         \"exactly once.\";\n\n    // Verifies that the control flow in the test function is expected.\n    if (expected_to_finish_ && !finished_) {\n      FAIL() << \"The predicate assertion unexpectedly aborted the test.\";\n    } else if (!expected_to_finish_ && finished_) {\n      FAIL() << \"The failed predicate assertion didn't abort the test \"\n                \"as expected.\";\n    }\n  }\n\n  // true if and only if the test function is expected to run to finish.\n  static bool expected_to_finish_;\n\n  // true if and only if the test function did run to finish.\n  static bool finished_;\n\n  static int n1_;\n  static int n2_;\n  static int n3_;\n};\n\nbool Predicate3Test::expected_to_finish_;\nbool Predicate3Test::finished_;\nint Predicate3Test::n1_;\nint Predicate3Test::n2_;\nint Predicate3Test::n3_;\n\ntypedef Predicate3Test EXPECT_PRED_FORMAT3Test;\ntypedef Predicate3Test ASSERT_PRED_FORMAT3Test;\ntypedef Predicate3Test EXPECT_PRED3Test;\ntypedef Predicate3Test ASSERT_PRED3Test;\n\n// Tests a successful EXPECT_PRED3 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(EXPECT_PRED3Test, FunctionOnBuiltInTypeSuccess) {\n  EXPECT_PRED3(PredFunction3Int, ++n1_, ++n2_, ++n3_);\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED3 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(EXPECT_PRED3Test, FunctionOnUserTypeSuccess) {\n  EXPECT_PRED3(PredFunction3Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_));\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED3 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(EXPECT_PRED3Test, FunctorOnBuiltInTypeSuccess) {\n  EXPECT_PRED3(PredFunctor3(), ++n1_, ++n2_, ++n3_);\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED3 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(EXPECT_PRED3Test, FunctorOnUserTypeSuccess) {\n  EXPECT_PRED3(PredFunctor3(), Bool(++n1_), Bool(++n2_), Bool(++n3_));\n  finished_ = true;\n}\n\n// Tests a failed EXPECT_PRED3 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(EXPECT_PRED3Test, FunctionOnBuiltInTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED3(PredFunction3Int, n1_++, n2_++, n3_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED3 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(EXPECT_PRED3Test, FunctionOnUserTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED3(PredFunction3Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED3 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(EXPECT_PRED3Test, FunctorOnBuiltInTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED3(PredFunctor3(), n1_++, n2_++, n3_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED3 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(EXPECT_PRED3Test, FunctorOnUserTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED3(PredFunctor3(), Bool(n1_++), Bool(n2_++), Bool(n3_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a successful ASSERT_PRED3 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(ASSERT_PRED3Test, FunctionOnBuiltInTypeSuccess) {\n  ASSERT_PRED3(PredFunction3Int, ++n1_, ++n2_, ++n3_);\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED3 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(ASSERT_PRED3Test, FunctionOnUserTypeSuccess) {\n  ASSERT_PRED3(PredFunction3Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_));\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED3 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(ASSERT_PRED3Test, FunctorOnBuiltInTypeSuccess) {\n  ASSERT_PRED3(PredFunctor3(), ++n1_, ++n2_, ++n3_);\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED3 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(ASSERT_PRED3Test, FunctorOnUserTypeSuccess) {\n  ASSERT_PRED3(PredFunctor3(), Bool(++n1_), Bool(++n2_), Bool(++n3_));\n  finished_ = true;\n}\n\n// Tests a failed ASSERT_PRED3 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(ASSERT_PRED3Test, FunctionOnBuiltInTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED3(PredFunction3Int, n1_++, n2_++, n3_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED3 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(ASSERT_PRED3Test, FunctionOnUserTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED3(PredFunction3Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED3 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(ASSERT_PRED3Test, FunctorOnBuiltInTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED3(PredFunctor3(), n1_++, n2_++, n3_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED3 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(ASSERT_PRED3Test, FunctorOnUserTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED3(PredFunctor3(), Bool(n1_++), Bool(n2_++), Bool(n3_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a successful EXPECT_PRED_FORMAT3 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnBuiltInTypeSuccess) {\n  EXPECT_PRED_FORMAT3(PredFormatFunction3, ++n1_, ++n2_, ++n3_);\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED_FORMAT3 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnUserTypeSuccess) {\n  EXPECT_PRED_FORMAT3(PredFormatFunction3, Bool(++n1_), Bool(++n2_),\n                      Bool(++n3_));\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED_FORMAT3 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnBuiltInTypeSuccess) {\n  EXPECT_PRED_FORMAT3(PredFormatFunctor3(), ++n1_, ++n2_, ++n3_);\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED_FORMAT3 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnUserTypeSuccess) {\n  EXPECT_PRED_FORMAT3(PredFormatFunctor3(), Bool(++n1_), Bool(++n2_),\n                      Bool(++n3_));\n  finished_ = true;\n}\n\n// Tests a failed EXPECT_PRED_FORMAT3 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnBuiltInTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT3(PredFormatFunction3, n1_++, n2_++, n3_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED_FORMAT3 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(EXPECT_PRED_FORMAT3Test, FunctionOnUserTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT3(PredFormatFunction3, Bool(n1_++), Bool(n2_++),\n                            Bool(n3_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED_FORMAT3 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnBuiltInTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT3(PredFormatFunctor3(), n1_++, n2_++, n3_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED_FORMAT3 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(EXPECT_PRED_FORMAT3Test, FunctorOnUserTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT3(PredFormatFunctor3(), Bool(n1_++), Bool(n2_++),\n                            Bool(n3_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a successful ASSERT_PRED_FORMAT3 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnBuiltInTypeSuccess) {\n  ASSERT_PRED_FORMAT3(PredFormatFunction3, ++n1_, ++n2_, ++n3_);\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED_FORMAT3 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnUserTypeSuccess) {\n  ASSERT_PRED_FORMAT3(PredFormatFunction3, Bool(++n1_), Bool(++n2_),\n                      Bool(++n3_));\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED_FORMAT3 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnBuiltInTypeSuccess) {\n  ASSERT_PRED_FORMAT3(PredFormatFunctor3(), ++n1_, ++n2_, ++n3_);\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED_FORMAT3 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnUserTypeSuccess) {\n  ASSERT_PRED_FORMAT3(PredFormatFunctor3(), Bool(++n1_), Bool(++n2_),\n                      Bool(++n3_));\n  finished_ = true;\n}\n\n// Tests a failed ASSERT_PRED_FORMAT3 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnBuiltInTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED_FORMAT3(PredFormatFunction3, n1_++, n2_++, n3_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED_FORMAT3 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(ASSERT_PRED_FORMAT3Test, FunctionOnUserTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED_FORMAT3(PredFormatFunction3, Bool(n1_++), Bool(n2_++),\n                            Bool(n3_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED_FORMAT3 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnBuiltInTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED_FORMAT3(PredFormatFunctor3(), n1_++, n2_++, n3_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED_FORMAT3 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(ASSERT_PRED_FORMAT3Test, FunctorOnUserTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED_FORMAT3(PredFormatFunctor3(), Bool(n1_++), Bool(n2_++),\n                            Bool(n3_++));\n        finished_ = true;\n      },\n      \"\");\n}\n// Sample functions/functors for testing 4-ary predicate assertions.\n\n// A 4-ary predicate function.\ntemplate <typename T1, typename T2, typename T3, typename T4>\nbool PredFunction4(T1 v1, T2 v2, T3 v3, T4 v4) {\n  return v1 + v2 + v3 + v4 > 0;\n}\n\n// The following two functions are needed because a compiler doesn't have\n// a context yet to know which template function must be instantiated.\nbool PredFunction4Int(int v1, int v2, int v3, int v4) {\n  return v1 + v2 + v3 + v4 > 0;\n}\nbool PredFunction4Bool(Bool v1, Bool v2, Bool v3, Bool v4) {\n  return v1 + v2 + v3 + v4 > 0;\n}\n\n// A 4-ary predicate functor.\nstruct PredFunctor4 {\n  template <typename T1, typename T2, typename T3, typename T4>\n  bool operator()(const T1& v1, const T2& v2, const T3& v3, const T4& v4) {\n    return v1 + v2 + v3 + v4 > 0;\n  }\n};\n\n// A 4-ary predicate-formatter function.\ntemplate <typename T1, typename T2, typename T3, typename T4>\ntesting::AssertionResult PredFormatFunction4(const char* e1, const char* e2,\n                                             const char* e3, const char* e4,\n                                             const T1& v1, const T2& v2,\n                                             const T3& v3, const T4& v4) {\n  if (PredFunction4(v1, v2, v3, v4)) return testing::AssertionSuccess();\n\n  return testing::AssertionFailure()\n         << e1 << \" + \" << e2 << \" + \" << e3 << \" + \" << e4\n         << \" is expected to be positive, but evaluates to \"\n         << v1 + v2 + v3 + v4 << \".\";\n}\n\n// A 4-ary predicate-formatter functor.\nstruct PredFormatFunctor4 {\n  template <typename T1, typename T2, typename T3, typename T4>\n  testing::AssertionResult operator()(const char* e1, const char* e2,\n                                      const char* e3, const char* e4,\n                                      const T1& v1, const T2& v2, const T3& v3,\n                                      const T4& v4) const {\n    return PredFormatFunction4(e1, e2, e3, e4, v1, v2, v3, v4);\n  }\n};\n\n// Tests for {EXPECT|ASSERT}_PRED_FORMAT4.\n\nclass Predicate4Test : public testing::Test {\n protected:\n  void SetUp() override {\n    expected_to_finish_ = true;\n    finished_ = false;\n    n1_ = n2_ = n3_ = n4_ = 0;\n  }\n\n  void TearDown() override {\n    // Verifies that each of the predicate's arguments was evaluated\n    // exactly once.\n    EXPECT_EQ(1, n1_) << \"The predicate assertion didn't evaluate argument 2 \"\n                         \"exactly once.\";\n    EXPECT_EQ(1, n2_) << \"The predicate assertion didn't evaluate argument 3 \"\n                         \"exactly once.\";\n    EXPECT_EQ(1, n3_) << \"The predicate assertion didn't evaluate argument 4 \"\n                         \"exactly once.\";\n    EXPECT_EQ(1, n4_) << \"The predicate assertion didn't evaluate argument 5 \"\n                         \"exactly once.\";\n\n    // Verifies that the control flow in the test function is expected.\n    if (expected_to_finish_ && !finished_) {\n      FAIL() << \"The predicate assertion unexpectedly aborted the test.\";\n    } else if (!expected_to_finish_ && finished_) {\n      FAIL() << \"The failed predicate assertion didn't abort the test \"\n                \"as expected.\";\n    }\n  }\n\n  // true if and only if the test function is expected to run to finish.\n  static bool expected_to_finish_;\n\n  // true if and only if the test function did run to finish.\n  static bool finished_;\n\n  static int n1_;\n  static int n2_;\n  static int n3_;\n  static int n4_;\n};\n\nbool Predicate4Test::expected_to_finish_;\nbool Predicate4Test::finished_;\nint Predicate4Test::n1_;\nint Predicate4Test::n2_;\nint Predicate4Test::n3_;\nint Predicate4Test::n4_;\n\ntypedef Predicate4Test EXPECT_PRED_FORMAT4Test;\ntypedef Predicate4Test ASSERT_PRED_FORMAT4Test;\ntypedef Predicate4Test EXPECT_PRED4Test;\ntypedef Predicate4Test ASSERT_PRED4Test;\n\n// Tests a successful EXPECT_PRED4 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(EXPECT_PRED4Test, FunctionOnBuiltInTypeSuccess) {\n  EXPECT_PRED4(PredFunction4Int, ++n1_, ++n2_, ++n3_, ++n4_);\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED4 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(EXPECT_PRED4Test, FunctionOnUserTypeSuccess) {\n  EXPECT_PRED4(PredFunction4Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_),\n               Bool(++n4_));\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED4 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(EXPECT_PRED4Test, FunctorOnBuiltInTypeSuccess) {\n  EXPECT_PRED4(PredFunctor4(), ++n1_, ++n2_, ++n3_, ++n4_);\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED4 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(EXPECT_PRED4Test, FunctorOnUserTypeSuccess) {\n  EXPECT_PRED4(PredFunctor4(), Bool(++n1_), Bool(++n2_), Bool(++n3_),\n               Bool(++n4_));\n  finished_ = true;\n}\n\n// Tests a failed EXPECT_PRED4 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(EXPECT_PRED4Test, FunctionOnBuiltInTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED4(PredFunction4Int, n1_++, n2_++, n3_++, n4_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED4 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(EXPECT_PRED4Test, FunctionOnUserTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED4(PredFunction4Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++),\n                     Bool(n4_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED4 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(EXPECT_PRED4Test, FunctorOnBuiltInTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED4(PredFunctor4(), n1_++, n2_++, n3_++, n4_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED4 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(EXPECT_PRED4Test, FunctorOnUserTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED4(PredFunctor4(), Bool(n1_++), Bool(n2_++), Bool(n3_++),\n                     Bool(n4_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a successful ASSERT_PRED4 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(ASSERT_PRED4Test, FunctionOnBuiltInTypeSuccess) {\n  ASSERT_PRED4(PredFunction4Int, ++n1_, ++n2_, ++n3_, ++n4_);\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED4 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(ASSERT_PRED4Test, FunctionOnUserTypeSuccess) {\n  ASSERT_PRED4(PredFunction4Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_),\n               Bool(++n4_));\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED4 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(ASSERT_PRED4Test, FunctorOnBuiltInTypeSuccess) {\n  ASSERT_PRED4(PredFunctor4(), ++n1_, ++n2_, ++n3_, ++n4_);\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED4 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(ASSERT_PRED4Test, FunctorOnUserTypeSuccess) {\n  ASSERT_PRED4(PredFunctor4(), Bool(++n1_), Bool(++n2_), Bool(++n3_),\n               Bool(++n4_));\n  finished_ = true;\n}\n\n// Tests a failed ASSERT_PRED4 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(ASSERT_PRED4Test, FunctionOnBuiltInTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED4(PredFunction4Int, n1_++, n2_++, n3_++, n4_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED4 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(ASSERT_PRED4Test, FunctionOnUserTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED4(PredFunction4Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++),\n                     Bool(n4_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED4 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(ASSERT_PRED4Test, FunctorOnBuiltInTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED4(PredFunctor4(), n1_++, n2_++, n3_++, n4_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED4 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(ASSERT_PRED4Test, FunctorOnUserTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED4(PredFunctor4(), Bool(n1_++), Bool(n2_++), Bool(n3_++),\n                     Bool(n4_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a successful EXPECT_PRED_FORMAT4 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(EXPECT_PRED_FORMAT4Test, FunctionOnBuiltInTypeSuccess) {\n  EXPECT_PRED_FORMAT4(PredFormatFunction4, ++n1_, ++n2_, ++n3_, ++n4_);\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED_FORMAT4 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(EXPECT_PRED_FORMAT4Test, FunctionOnUserTypeSuccess) {\n  EXPECT_PRED_FORMAT4(PredFormatFunction4, Bool(++n1_), Bool(++n2_),\n                      Bool(++n3_), Bool(++n4_));\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED_FORMAT4 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(EXPECT_PRED_FORMAT4Test, FunctorOnBuiltInTypeSuccess) {\n  EXPECT_PRED_FORMAT4(PredFormatFunctor4(), ++n1_, ++n2_, ++n3_, ++n4_);\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED_FORMAT4 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(EXPECT_PRED_FORMAT4Test, FunctorOnUserTypeSuccess) {\n  EXPECT_PRED_FORMAT4(PredFormatFunctor4(), Bool(++n1_), Bool(++n2_),\n                      Bool(++n3_), Bool(++n4_));\n  finished_ = true;\n}\n\n// Tests a failed EXPECT_PRED_FORMAT4 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(EXPECT_PRED_FORMAT4Test, FunctionOnBuiltInTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT4(PredFormatFunction4, n1_++, n2_++, n3_++, n4_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED_FORMAT4 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(EXPECT_PRED_FORMAT4Test, FunctionOnUserTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT4(PredFormatFunction4, Bool(n1_++), Bool(n2_++),\n                            Bool(n3_++), Bool(n4_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED_FORMAT4 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(EXPECT_PRED_FORMAT4Test, FunctorOnBuiltInTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT4(PredFormatFunctor4(), n1_++, n2_++, n3_++, n4_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED_FORMAT4 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(EXPECT_PRED_FORMAT4Test, FunctorOnUserTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT4(PredFormatFunctor4(), Bool(n1_++), Bool(n2_++),\n                            Bool(n3_++), Bool(n4_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a successful ASSERT_PRED_FORMAT4 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(ASSERT_PRED_FORMAT4Test, FunctionOnBuiltInTypeSuccess) {\n  ASSERT_PRED_FORMAT4(PredFormatFunction4, ++n1_, ++n2_, ++n3_, ++n4_);\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED_FORMAT4 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(ASSERT_PRED_FORMAT4Test, FunctionOnUserTypeSuccess) {\n  ASSERT_PRED_FORMAT4(PredFormatFunction4, Bool(++n1_), Bool(++n2_),\n                      Bool(++n3_), Bool(++n4_));\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED_FORMAT4 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnBuiltInTypeSuccess) {\n  ASSERT_PRED_FORMAT4(PredFormatFunctor4(), ++n1_, ++n2_, ++n3_, ++n4_);\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED_FORMAT4 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnUserTypeSuccess) {\n  ASSERT_PRED_FORMAT4(PredFormatFunctor4(), Bool(++n1_), Bool(++n2_),\n                      Bool(++n3_), Bool(++n4_));\n  finished_ = true;\n}\n\n// Tests a failed ASSERT_PRED_FORMAT4 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(ASSERT_PRED_FORMAT4Test, FunctionOnBuiltInTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED_FORMAT4(PredFormatFunction4, n1_++, n2_++, n3_++, n4_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED_FORMAT4 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(ASSERT_PRED_FORMAT4Test, FunctionOnUserTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED_FORMAT4(PredFormatFunction4, Bool(n1_++), Bool(n2_++),\n                            Bool(n3_++), Bool(n4_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED_FORMAT4 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnBuiltInTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED_FORMAT4(PredFormatFunctor4(), n1_++, n2_++, n3_++, n4_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED_FORMAT4 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(ASSERT_PRED_FORMAT4Test, FunctorOnUserTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED_FORMAT4(PredFormatFunctor4(), Bool(n1_++), Bool(n2_++),\n                            Bool(n3_++), Bool(n4_++));\n        finished_ = true;\n      },\n      \"\");\n}\n// Sample functions/functors for testing 5-ary predicate assertions.\n\n// A 5-ary predicate function.\ntemplate <typename T1, typename T2, typename T3, typename T4, typename T5>\nbool PredFunction5(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) {\n  return v1 + v2 + v3 + v4 + v5 > 0;\n}\n\n// The following two functions are needed because a compiler doesn't have\n// a context yet to know which template function must be instantiated.\nbool PredFunction5Int(int v1, int v2, int v3, int v4, int v5) {\n  return v1 + v2 + v3 + v4 + v5 > 0;\n}\nbool PredFunction5Bool(Bool v1, Bool v2, Bool v3, Bool v4, Bool v5) {\n  return v1 + v2 + v3 + v4 + v5 > 0;\n}\n\n// A 5-ary predicate functor.\nstruct PredFunctor5 {\n  template <typename T1, typename T2, typename T3, typename T4, typename T5>\n  bool operator()(const T1& v1, const T2& v2, const T3& v3, const T4& v4,\n                  const T5& v5) {\n    return v1 + v2 + v3 + v4 + v5 > 0;\n  }\n};\n\n// A 5-ary predicate-formatter function.\ntemplate <typename T1, typename T2, typename T3, typename T4, typename T5>\ntesting::AssertionResult PredFormatFunction5(const char* e1, const char* e2,\n                                             const char* e3, const char* e4,\n                                             const char* e5, const T1& v1,\n                                             const T2& v2, const T3& v3,\n                                             const T4& v4, const T5& v5) {\n  if (PredFunction5(v1, v2, v3, v4, v5)) return testing::AssertionSuccess();\n\n  return testing::AssertionFailure()\n         << e1 << \" + \" << e2 << \" + \" << e3 << \" + \" << e4 << \" + \" << e5\n         << \" is expected to be positive, but evaluates to \"\n         << v1 + v2 + v3 + v4 + v5 << \".\";\n}\n\n// A 5-ary predicate-formatter functor.\nstruct PredFormatFunctor5 {\n  template <typename T1, typename T2, typename T3, typename T4, typename T5>\n  testing::AssertionResult operator()(const char* e1, const char* e2,\n                                      const char* e3, const char* e4,\n                                      const char* e5, const T1& v1,\n                                      const T2& v2, const T3& v3, const T4& v4,\n                                      const T5& v5) const {\n    return PredFormatFunction5(e1, e2, e3, e4, e5, v1, v2, v3, v4, v5);\n  }\n};\n\n// Tests for {EXPECT|ASSERT}_PRED_FORMAT5.\n\nclass Predicate5Test : public testing::Test {\n protected:\n  void SetUp() override {\n    expected_to_finish_ = true;\n    finished_ = false;\n    n1_ = n2_ = n3_ = n4_ = n5_ = 0;\n  }\n\n  void TearDown() override {\n    // Verifies that each of the predicate's arguments was evaluated\n    // exactly once.\n    EXPECT_EQ(1, n1_) << \"The predicate assertion didn't evaluate argument 2 \"\n                         \"exactly once.\";\n    EXPECT_EQ(1, n2_) << \"The predicate assertion didn't evaluate argument 3 \"\n                         \"exactly once.\";\n    EXPECT_EQ(1, n3_) << \"The predicate assertion didn't evaluate argument 4 \"\n                         \"exactly once.\";\n    EXPECT_EQ(1, n4_) << \"The predicate assertion didn't evaluate argument 5 \"\n                         \"exactly once.\";\n    EXPECT_EQ(1, n5_) << \"The predicate assertion didn't evaluate argument 6 \"\n                         \"exactly once.\";\n\n    // Verifies that the control flow in the test function is expected.\n    if (expected_to_finish_ && !finished_) {\n      FAIL() << \"The predicate assertion unexpectedly aborted the test.\";\n    } else if (!expected_to_finish_ && finished_) {\n      FAIL() << \"The failed predicate assertion didn't abort the test \"\n                \"as expected.\";\n    }\n  }\n\n  // true if and only if the test function is expected to run to finish.\n  static bool expected_to_finish_;\n\n  // true if and only if the test function did run to finish.\n  static bool finished_;\n\n  static int n1_;\n  static int n2_;\n  static int n3_;\n  static int n4_;\n  static int n5_;\n};\n\nbool Predicate5Test::expected_to_finish_;\nbool Predicate5Test::finished_;\nint Predicate5Test::n1_;\nint Predicate5Test::n2_;\nint Predicate5Test::n3_;\nint Predicate5Test::n4_;\nint Predicate5Test::n5_;\n\ntypedef Predicate5Test EXPECT_PRED_FORMAT5Test;\ntypedef Predicate5Test ASSERT_PRED_FORMAT5Test;\ntypedef Predicate5Test EXPECT_PRED5Test;\ntypedef Predicate5Test ASSERT_PRED5Test;\n\n// Tests a successful EXPECT_PRED5 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(EXPECT_PRED5Test, FunctionOnBuiltInTypeSuccess) {\n  EXPECT_PRED5(PredFunction5Int, ++n1_, ++n2_, ++n3_, ++n4_, ++n5_);\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED5 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(EXPECT_PRED5Test, FunctionOnUserTypeSuccess) {\n  EXPECT_PRED5(PredFunction5Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_),\n               Bool(++n4_), Bool(++n5_));\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED5 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(EXPECT_PRED5Test, FunctorOnBuiltInTypeSuccess) {\n  EXPECT_PRED5(PredFunctor5(), ++n1_, ++n2_, ++n3_, ++n4_, ++n5_);\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED5 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(EXPECT_PRED5Test, FunctorOnUserTypeSuccess) {\n  EXPECT_PRED5(PredFunctor5(), Bool(++n1_), Bool(++n2_), Bool(++n3_),\n               Bool(++n4_), Bool(++n5_));\n  finished_ = true;\n}\n\n// Tests a failed EXPECT_PRED5 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(EXPECT_PRED5Test, FunctionOnBuiltInTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED5(PredFunction5Int, n1_++, n2_++, n3_++, n4_++, n5_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED5 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(EXPECT_PRED5Test, FunctionOnUserTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED5(PredFunction5Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++),\n                     Bool(n4_++), Bool(n5_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED5 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(EXPECT_PRED5Test, FunctorOnBuiltInTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED5(PredFunctor5(), n1_++, n2_++, n3_++, n4_++, n5_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED5 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(EXPECT_PRED5Test, FunctorOnUserTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED5(PredFunctor5(), Bool(n1_++), Bool(n2_++), Bool(n3_++),\n                     Bool(n4_++), Bool(n5_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a successful ASSERT_PRED5 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(ASSERT_PRED5Test, FunctionOnBuiltInTypeSuccess) {\n  ASSERT_PRED5(PredFunction5Int, ++n1_, ++n2_, ++n3_, ++n4_, ++n5_);\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED5 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(ASSERT_PRED5Test, FunctionOnUserTypeSuccess) {\n  ASSERT_PRED5(PredFunction5Bool, Bool(++n1_), Bool(++n2_), Bool(++n3_),\n               Bool(++n4_), Bool(++n5_));\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED5 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(ASSERT_PRED5Test, FunctorOnBuiltInTypeSuccess) {\n  ASSERT_PRED5(PredFunctor5(), ++n1_, ++n2_, ++n3_, ++n4_, ++n5_);\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED5 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(ASSERT_PRED5Test, FunctorOnUserTypeSuccess) {\n  ASSERT_PRED5(PredFunctor5(), Bool(++n1_), Bool(++n2_), Bool(++n3_),\n               Bool(++n4_), Bool(++n5_));\n  finished_ = true;\n}\n\n// Tests a failed ASSERT_PRED5 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(ASSERT_PRED5Test, FunctionOnBuiltInTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED5(PredFunction5Int, n1_++, n2_++, n3_++, n4_++, n5_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED5 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(ASSERT_PRED5Test, FunctionOnUserTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED5(PredFunction5Bool, Bool(n1_++), Bool(n2_++), Bool(n3_++),\n                     Bool(n4_++), Bool(n5_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED5 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(ASSERT_PRED5Test, FunctorOnBuiltInTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED5(PredFunctor5(), n1_++, n2_++, n3_++, n4_++, n5_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED5 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(ASSERT_PRED5Test, FunctorOnUserTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED5(PredFunctor5(), Bool(n1_++), Bool(n2_++), Bool(n3_++),\n                     Bool(n4_++), Bool(n5_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a successful EXPECT_PRED_FORMAT5 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(EXPECT_PRED_FORMAT5Test, FunctionOnBuiltInTypeSuccess) {\n  EXPECT_PRED_FORMAT5(PredFormatFunction5, ++n1_, ++n2_, ++n3_, ++n4_, ++n5_);\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED_FORMAT5 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(EXPECT_PRED_FORMAT5Test, FunctionOnUserTypeSuccess) {\n  EXPECT_PRED_FORMAT5(PredFormatFunction5, Bool(++n1_), Bool(++n2_),\n                      Bool(++n3_), Bool(++n4_), Bool(++n5_));\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED_FORMAT5 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(EXPECT_PRED_FORMAT5Test, FunctorOnBuiltInTypeSuccess) {\n  EXPECT_PRED_FORMAT5(PredFormatFunctor5(), ++n1_, ++n2_, ++n3_, ++n4_, ++n5_);\n  finished_ = true;\n}\n\n// Tests a successful EXPECT_PRED_FORMAT5 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(EXPECT_PRED_FORMAT5Test, FunctorOnUserTypeSuccess) {\n  EXPECT_PRED_FORMAT5(PredFormatFunctor5(), Bool(++n1_), Bool(++n2_),\n                      Bool(++n3_), Bool(++n4_), Bool(++n5_));\n  finished_ = true;\n}\n\n// Tests a failed EXPECT_PRED_FORMAT5 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(EXPECT_PRED_FORMAT5Test, FunctionOnBuiltInTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT5(PredFormatFunction5, n1_++, n2_++, n3_++, n4_++,\n                            n5_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED_FORMAT5 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(EXPECT_PRED_FORMAT5Test, FunctionOnUserTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT5(PredFormatFunction5, Bool(n1_++), Bool(n2_++),\n                            Bool(n3_++), Bool(n4_++), Bool(n5_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED_FORMAT5 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(EXPECT_PRED_FORMAT5Test, FunctorOnBuiltInTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT5(PredFormatFunctor5(), n1_++, n2_++, n3_++, n4_++,\n                            n5_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed EXPECT_PRED_FORMAT5 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(EXPECT_PRED_FORMAT5Test, FunctorOnUserTypeFailure) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT5(PredFormatFunctor5(), Bool(n1_++), Bool(n2_++),\n                            Bool(n3_++), Bool(n4_++), Bool(n5_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a successful ASSERT_PRED_FORMAT5 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(ASSERT_PRED_FORMAT5Test, FunctionOnBuiltInTypeSuccess) {\n  ASSERT_PRED_FORMAT5(PredFormatFunction5, ++n1_, ++n2_, ++n3_, ++n4_, ++n5_);\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED_FORMAT5 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(ASSERT_PRED_FORMAT5Test, FunctionOnUserTypeSuccess) {\n  ASSERT_PRED_FORMAT5(PredFormatFunction5, Bool(++n1_), Bool(++n2_),\n                      Bool(++n3_), Bool(++n4_), Bool(++n5_));\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED_FORMAT5 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnBuiltInTypeSuccess) {\n  ASSERT_PRED_FORMAT5(PredFormatFunctor5(), ++n1_, ++n2_, ++n3_, ++n4_, ++n5_);\n  finished_ = true;\n}\n\n// Tests a successful ASSERT_PRED_FORMAT5 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnUserTypeSuccess) {\n  ASSERT_PRED_FORMAT5(PredFormatFunctor5(), Bool(++n1_), Bool(++n2_),\n                      Bool(++n3_), Bool(++n4_), Bool(++n5_));\n  finished_ = true;\n}\n\n// Tests a failed ASSERT_PRED_FORMAT5 where the\n// predicate-formatter is a function on a built-in type (int).\nTEST_F(ASSERT_PRED_FORMAT5Test, FunctionOnBuiltInTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED_FORMAT5(PredFormatFunction5, n1_++, n2_++, n3_++, n4_++,\n                            n5_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED_FORMAT5 where the\n// predicate-formatter is a function on a user-defined type (Bool).\nTEST_F(ASSERT_PRED_FORMAT5Test, FunctionOnUserTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED_FORMAT5(PredFormatFunction5, Bool(n1_++), Bool(n2_++),\n                            Bool(n3_++), Bool(n4_++), Bool(n5_++));\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED_FORMAT5 where the\n// predicate-formatter is a functor on a built-in type (int).\nTEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnBuiltInTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED_FORMAT5(PredFormatFunctor5(), n1_++, n2_++, n3_++, n4_++,\n                            n5_++);\n        finished_ = true;\n      },\n      \"\");\n}\n\n// Tests a failed ASSERT_PRED_FORMAT5 where the\n// predicate-formatter is a functor on a user-defined type (Bool).\nTEST_F(ASSERT_PRED_FORMAT5Test, FunctorOnUserTypeFailure) {\n  expected_to_finish_ = false;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED_FORMAT5(PredFormatFunctor5(), Bool(n1_++), Bool(n2_++),\n                            Bool(n3_++), Bool(n4_++), Bool(n5_++));\n        finished_ = true;\n      },\n      \"\");\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_premature_exit_test.cc",
    "content": "// Copyright 2013, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// Tests that Google Test manipulates the premature-exit-detection\n// file correctly.\n\n#include <stdio.h>\n\n#include \"gtest/gtest.h\"\n\nusing ::testing::InitGoogleTest;\nusing ::testing::Test;\nusing ::testing::internal::posix::GetEnv;\nusing ::testing::internal::posix::Stat;\nusing ::testing::internal::posix::StatStruct;\n\nnamespace {\n\nclass PrematureExitTest : public Test {\n public:\n  // Returns true if and only if the given file exists.\n  static bool FileExists(const char* filepath) {\n    StatStruct stat;\n    return Stat(filepath, &stat) == 0;\n  }\n\n protected:\n  PrematureExitTest() {\n    premature_exit_file_path_ = GetEnv(\"TEST_PREMATURE_EXIT_FILE\");\n\n    // Normalize NULL to \"\" for ease of handling.\n    if (premature_exit_file_path_ == nullptr) {\n      premature_exit_file_path_ = \"\";\n    }\n  }\n\n  // Returns true if and only if the premature-exit file exists.\n  bool PrematureExitFileExists() const {\n    return FileExists(premature_exit_file_path_);\n  }\n\n  const char* premature_exit_file_path_;\n};\n\ntypedef PrematureExitTest PrematureExitDeathTest;\n\n// Tests that:\n//   - the premature-exit file exists during the execution of a\n//     death test (EXPECT_DEATH*), and\n//   - a death test doesn't interfere with the main test process's\n//     handling of the premature-exit file.\nTEST_F(PrematureExitDeathTest, FileExistsDuringExecutionOfDeathTest) {\n  if (*premature_exit_file_path_ == '\\0') {\n    return;\n  }\n\n  EXPECT_DEATH_IF_SUPPORTED(\n      {\n        // If the file exists, crash the process such that the main test\n        // process will catch the (expected) crash and report a success;\n        // otherwise don't crash, which will cause the main test process\n        // to report that the death test has failed.\n        if (PrematureExitFileExists()) {\n          exit(1);\n        }\n      },\n      \"\");\n}\n\n// Tests that the premature-exit file exists during the execution of a\n// normal (non-death) test.\nTEST_F(PrematureExitTest, PrematureExitFileExistsDuringTestExecution) {\n  if (*premature_exit_file_path_ == '\\0') {\n    return;\n  }\n\n  EXPECT_TRUE(PrematureExitFileExists())\n      << \" file \" << premature_exit_file_path_\n      << \" should exist during test execution, but doesn't.\";\n}\n\n}  // namespace\n\nint main(int argc, char** argv) {\n  InitGoogleTest(&argc, argv);\n  const int exit_code = RUN_ALL_TESTS();\n\n  // Test that the premature-exit file is deleted upon return from\n  // RUN_ALL_TESTS().\n  const char* const filepath = GetEnv(\"TEST_PREMATURE_EXIT_FILE\");\n  if (filepath != nullptr && *filepath != '\\0') {\n    if (PrematureExitTest::FileExists(filepath)) {\n      printf(\n          \"File %s shouldn't exist after the test program finishes, but does.\",\n          filepath);\n      return 1;\n    }\n  }\n\n  return exit_code;\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_prod_test.cc",
    "content": "// Copyright 2006, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// Unit test for gtest_prod.h.\n\n#include \"production.h\"\n#include \"gtest/gtest.h\"\n\n// Tests that private members can be accessed from a TEST declared as\n// a friend of the class.\nTEST(PrivateCodeTest, CanAccessPrivateMembers) {\n  PrivateCode a;\n  EXPECT_EQ(0, a.x_);\n\n  a.set_x(1);\n  EXPECT_EQ(1, a.x_);\n}\n\ntypedef testing::Test PrivateCodeFixtureTest;\n\n// Tests that private members can be accessed from a TEST_F declared\n// as a friend of the class.\nTEST_F(PrivateCodeFixtureTest, CanAccessPrivateMembers) {\n  PrivateCode a;\n  EXPECT_EQ(0, a.x_);\n\n  a.set_x(2);\n  EXPECT_EQ(2, a.x_);\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_repeat_test.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Tests the --gtest_repeat=number flag.\n\n#include <stdlib.h>\n\n#include <iostream>\n\n#include \"gtest/gtest.h\"\n#include \"src/gtest-internal-inl.h\"\n\nnamespace {\n\n// We need this when we are testing Google Test itself and therefore\n// cannot use Google Test assertions.\n#define GTEST_CHECK_INT_EQ_(expected, actual)                      \\\n  do {                                                             \\\n    const int expected_val = (expected);                           \\\n    const int actual_val = (actual);                               \\\n    if (::testing::internal::IsTrue(expected_val != actual_val)) { \\\n      ::std::cout << \"Value of: \" #actual \"\\n\"                     \\\n                  << \"  Actual: \" << actual_val << \"\\n\"            \\\n                  << \"Expected: \" #expected \"\\n\"                   \\\n                  << \"Which is: \" << expected_val << \"\\n\";         \\\n      ::testing::internal::posix::Abort();                         \\\n    }                                                              \\\n  } while (::testing::internal::AlwaysFalse())\n\n// Used for verifying that global environment set-up and tear-down are\n// inside the --gtest_repeat loop.\n\nint g_environment_set_up_count = 0;\nint g_environment_tear_down_count = 0;\n\nclass MyEnvironment : public testing::Environment {\n public:\n  MyEnvironment() {}\n  void SetUp() override { g_environment_set_up_count++; }\n  void TearDown() override { g_environment_tear_down_count++; }\n};\n\n// A test that should fail.\n\nint g_should_fail_count = 0;\n\nTEST(FooTest, ShouldFail) {\n  g_should_fail_count++;\n  EXPECT_EQ(0, 1) << \"Expected failure.\";\n}\n\n// A test that should pass.\n\nint g_should_pass_count = 0;\n\nTEST(FooTest, ShouldPass) { g_should_pass_count++; }\n\n// A test that contains a thread-safe death test and a fast death\n// test.  It should pass.\n\nint g_death_test_count = 0;\n\nTEST(BarDeathTest, ThreadSafeAndFast) {\n  g_death_test_count++;\n\n  GTEST_FLAG_SET(death_test_style, \"threadsafe\");\n  EXPECT_DEATH_IF_SUPPORTED(::testing::internal::posix::Abort(), \"\");\n\n  GTEST_FLAG_SET(death_test_style, \"fast\");\n  EXPECT_DEATH_IF_SUPPORTED(::testing::internal::posix::Abort(), \"\");\n}\n\nint g_param_test_count = 0;\n\nconst int kNumberOfParamTests = 10;\n\nclass MyParamTest : public testing::TestWithParam<int> {};\n\nTEST_P(MyParamTest, ShouldPass) {\n  GTEST_CHECK_INT_EQ_(g_param_test_count % kNumberOfParamTests, GetParam());\n  g_param_test_count++;\n}\nINSTANTIATE_TEST_SUITE_P(MyParamSequence, MyParamTest,\n                         testing::Range(0, kNumberOfParamTests));\n\n// Resets the count for each test.\nvoid ResetCounts() {\n  g_environment_set_up_count = 0;\n  g_environment_tear_down_count = 0;\n  g_should_fail_count = 0;\n  g_should_pass_count = 0;\n  g_death_test_count = 0;\n  g_param_test_count = 0;\n}\n\n// Checks that the count for each test is expected.\nvoid CheckCounts(int expected) {\n  GTEST_CHECK_INT_EQ_(expected, g_environment_set_up_count);\n  GTEST_CHECK_INT_EQ_(expected, g_environment_tear_down_count);\n  GTEST_CHECK_INT_EQ_(expected, g_should_fail_count);\n  GTEST_CHECK_INT_EQ_(expected, g_should_pass_count);\n  GTEST_CHECK_INT_EQ_(expected, g_death_test_count);\n  GTEST_CHECK_INT_EQ_(expected * kNumberOfParamTests, g_param_test_count);\n}\n\n// Tests the behavior of Google Test when --gtest_repeat is not specified.\nvoid TestRepeatUnspecified() {\n  ResetCounts();\n  GTEST_CHECK_INT_EQ_(1, RUN_ALL_TESTS());\n  CheckCounts(1);\n}\n\n// Tests the behavior of Google Test when --gtest_repeat has the given value.\nvoid TestRepeat(int repeat) {\n  GTEST_FLAG_SET(repeat, repeat);\n  GTEST_FLAG_SET(recreate_environments_when_repeating, true);\n\n  ResetCounts();\n  GTEST_CHECK_INT_EQ_(repeat > 0 ? 1 : 0, RUN_ALL_TESTS());\n  CheckCounts(repeat);\n}\n\n// Tests using --gtest_repeat when --gtest_filter specifies an empty\n// set of tests.\nvoid TestRepeatWithEmptyFilter(int repeat) {\n  GTEST_FLAG_SET(repeat, repeat);\n  GTEST_FLAG_SET(recreate_environments_when_repeating, true);\n  GTEST_FLAG_SET(filter, \"None\");\n\n  ResetCounts();\n  GTEST_CHECK_INT_EQ_(0, RUN_ALL_TESTS());\n  CheckCounts(0);\n}\n\n// Tests using --gtest_repeat when --gtest_filter specifies a set of\n// successful tests.\nvoid TestRepeatWithFilterForSuccessfulTests(int repeat) {\n  GTEST_FLAG_SET(repeat, repeat);\n  GTEST_FLAG_SET(recreate_environments_when_repeating, true);\n  GTEST_FLAG_SET(filter, \"*-*ShouldFail\");\n\n  ResetCounts();\n  GTEST_CHECK_INT_EQ_(0, RUN_ALL_TESTS());\n  GTEST_CHECK_INT_EQ_(repeat, g_environment_set_up_count);\n  GTEST_CHECK_INT_EQ_(repeat, g_environment_tear_down_count);\n  GTEST_CHECK_INT_EQ_(0, g_should_fail_count);\n  GTEST_CHECK_INT_EQ_(repeat, g_should_pass_count);\n  GTEST_CHECK_INT_EQ_(repeat, g_death_test_count);\n  GTEST_CHECK_INT_EQ_(repeat * kNumberOfParamTests, g_param_test_count);\n}\n\n// Tests using --gtest_repeat when --gtest_filter specifies a set of\n// failed tests.\nvoid TestRepeatWithFilterForFailedTests(int repeat) {\n  GTEST_FLAG_SET(repeat, repeat);\n  GTEST_FLAG_SET(recreate_environments_when_repeating, true);\n  GTEST_FLAG_SET(filter, \"*ShouldFail\");\n\n  ResetCounts();\n  GTEST_CHECK_INT_EQ_(1, RUN_ALL_TESTS());\n  GTEST_CHECK_INT_EQ_(repeat, g_environment_set_up_count);\n  GTEST_CHECK_INT_EQ_(repeat, g_environment_tear_down_count);\n  GTEST_CHECK_INT_EQ_(repeat, g_should_fail_count);\n  GTEST_CHECK_INT_EQ_(0, g_should_pass_count);\n  GTEST_CHECK_INT_EQ_(0, g_death_test_count);\n  GTEST_CHECK_INT_EQ_(0, g_param_test_count);\n}\n\n}  // namespace\n\nint main(int argc, char **argv) {\n  testing::InitGoogleTest(&argc, argv);\n\n  testing::AddGlobalTestEnvironment(new MyEnvironment);\n\n  TestRepeatUnspecified();\n  TestRepeat(0);\n  TestRepeat(1);\n  TestRepeat(5);\n\n  TestRepeatWithEmptyFilter(2);\n  TestRepeatWithEmptyFilter(3);\n\n  TestRepeatWithFilterForSuccessfulTests(3);\n\n  TestRepeatWithFilterForFailedTests(4);\n\n  // It would be nice to verify that the tests indeed loop forever\n  // when GTEST_FLAG(repeat) is negative, but this test will be quite\n  // complicated to write.  Since this flag is for interactive\n  // debugging only and doesn't affect the normal test result, such a\n  // test would be an overkill.\n\n  printf(\"PASS\\n\");\n  return 0;\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_skip_check_output_test.py",
    "content": "#!/usr/bin/env python\n#\n# Copyright 2019 Google LLC.  All Rights Reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"Tests Google Test's gtest skip in environment setup  behavior.\n\nThis script invokes gtest_skip_in_environment_setup_test_ and verifies its\noutput.\n\"\"\"\n\nimport re\n\nfrom googletest.test import gtest_test_utils\n\n# Path to the gtest_skip_in_environment_setup_test binary\nEXE_PATH = gtest_test_utils.GetTestExecutablePath('gtest_skip_test')\n\nOUTPUT = gtest_test_utils.Subprocess([EXE_PATH]).output\n\n\n# Test.\nclass SkipEntireEnvironmentTest(gtest_test_utils.TestCase):\n\n  def testSkipEntireEnvironmentTest(self):\n    self.assertIn('Skipped\\nskipping single test\\n', OUTPUT)\n    skip_fixture = 'Skipped\\nskipping all tests for this fixture\\n'\n    self.assertIsNotNone(\n        re.search(skip_fixture + '.*' + skip_fixture, OUTPUT, flags=re.DOTALL),\n        repr(OUTPUT))\n    self.assertNotIn('FAILED', OUTPUT)\n\n\nif __name__ == '__main__':\n  gtest_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_skip_environment_check_output_test.py",
    "content": "#!/usr/bin/env python\n#\n# Copyright 2019 Google LLC.  All Rights Reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"Tests Google Test's gtest skip in environment setup  behavior.\n\nThis script invokes gtest_skip_in_environment_setup_test_ and verifies its\noutput.\n\"\"\"\n\nfrom googletest.test import gtest_test_utils\n\n# Path to the gtest_skip_in_environment_setup_test binary\nEXE_PATH = gtest_test_utils.GetTestExecutablePath(\n    'gtest_skip_in_environment_setup_test')\n\nOUTPUT = gtest_test_utils.Subprocess([EXE_PATH]).output\n\n\n# Test.\nclass SkipEntireEnvironmentTest(gtest_test_utils.TestCase):\n\n  def testSkipEntireEnvironmentTest(self):\n    self.assertIn('Skipping the entire environment', OUTPUT)\n    self.assertNotIn('FAILED', OUTPUT)\n\n\nif __name__ == '__main__':\n  gtest_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_skip_in_environment_setup_test.cc",
    "content": "// Copyright 2019, Google LLC.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google LLC. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// This test verifies that skipping in the environment results in the\n// testcases being skipped.\n\n#include <iostream>\n\n#include \"gtest/gtest.h\"\n\nclass SetupEnvironment : public testing::Environment {\n public:\n  void SetUp() override { GTEST_SKIP() << \"Skipping the entire environment\"; }\n};\n\nTEST(Test, AlwaysFails) { EXPECT_EQ(true, false); }\n\nint main(int argc, char **argv) {\n  testing::InitGoogleTest(&argc, argv);\n\n  testing::AddGlobalTestEnvironment(new SetupEnvironment());\n\n  return RUN_ALL_TESTS();\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_skip_test.cc",
    "content": "// Copyright 2008 Google Inc.\n// All Rights Reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Author: arseny.aprelev@gmail.com (Arseny Aprelev)\n//\n\n#include \"gtest/gtest.h\"\n\nusing ::testing::Test;\n\nTEST(SkipTest, DoesSkip) {\n  GTEST_SKIP() << \"skipping single test\";\n  EXPECT_EQ(0, 1);\n}\n\nclass Fixture : public Test {\n protected:\n  void SetUp() override {\n    GTEST_SKIP() << \"skipping all tests for this fixture\";\n  }\n};\n\nTEST_F(Fixture, SkipsOneTest) { EXPECT_EQ(5, 7); }\n\nTEST_F(Fixture, SkipsAnotherTest) { EXPECT_EQ(99, 100); }\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_sole_header_test.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// This test verifies that it's possible to use Google Test by including\n// the gtest.h header file alone.\n\n#include \"gtest/gtest.h\"\n\nnamespace {\n\nvoid Subroutine() { EXPECT_EQ(42, 42); }\n\nTEST(NoFatalFailureTest, ExpectNoFatalFailure) {\n  EXPECT_NO_FATAL_FAILURE(;);\n  EXPECT_NO_FATAL_FAILURE(SUCCEED());\n  EXPECT_NO_FATAL_FAILURE(Subroutine());\n  EXPECT_NO_FATAL_FAILURE({ SUCCEED(); });\n}\n\nTEST(NoFatalFailureTest, AssertNoFatalFailure) {\n  ASSERT_NO_FATAL_FAILURE(;);\n  ASSERT_NO_FATAL_FAILURE(SUCCEED());\n  ASSERT_NO_FATAL_FAILURE(Subroutine());\n  ASSERT_NO_FATAL_FAILURE({ SUCCEED(); });\n}\n\n}  // namespace\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_stress_test.cc",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Tests that SCOPED_TRACE() and various Google Test assertions can be\n// used in a large number of threads concurrently.\n\n#include <vector>\n\n#include \"gtest/gtest.h\"\n#include \"src/gtest-internal-inl.h\"\n\n#if GTEST_IS_THREADSAFE\n\nnamespace testing {\nnamespace {\n\nusing internal::Notification;\nusing internal::TestPropertyKeyIs;\nusing internal::ThreadWithParam;\n\n// In order to run tests in this file, for platforms where Google Test is\n// thread safe, implement ThreadWithParam. See the description of its API\n// in gtest-port.h, where it is defined for already supported platforms.\n\n// How many threads to create?\nconst int kThreadCount = 50;\n\nstd::string IdToKey(int id, const char* suffix) {\n  Message key;\n  key << \"key_\" << id << \"_\" << suffix;\n  return key.GetString();\n}\n\nstd::string IdToString(int id) {\n  Message id_message;\n  id_message << id;\n  return id_message.GetString();\n}\n\nvoid ExpectKeyAndValueWereRecordedForId(\n    const std::vector<TestProperty>& properties, int id, const char* suffix) {\n  TestPropertyKeyIs matches_key(IdToKey(id, suffix).c_str());\n  const std::vector<TestProperty>::const_iterator property =\n      std::find_if(properties.begin(), properties.end(), matches_key);\n  ASSERT_TRUE(property != properties.end())\n      << \"expecting \" << suffix << \" value for id \" << id;\n  EXPECT_STREQ(IdToString(id).c_str(), property->value());\n}\n\n// Calls a large number of Google Test assertions, where exactly one of them\n// will fail.\nvoid ManyAsserts(int id) {\n  GTEST_LOG_(INFO) << \"Thread #\" << id << \" running...\";\n\n  SCOPED_TRACE(Message() << \"Thread #\" << id);\n\n  for (int i = 0; i < kThreadCount; i++) {\n    SCOPED_TRACE(Message() << \"Iteration #\" << i);\n\n    // A bunch of assertions that should succeed.\n    EXPECT_TRUE(true);\n    ASSERT_FALSE(false) << \"This shouldn't fail.\";\n    EXPECT_STREQ(\"a\", \"a\");\n    ASSERT_LE(5, 6);\n    EXPECT_EQ(i, i) << \"This shouldn't fail.\";\n\n    // RecordProperty() should interact safely with other threads as well.\n    // The shared_key forces property updates.\n    Test::RecordProperty(IdToKey(id, \"string\").c_str(), IdToString(id).c_str());\n    Test::RecordProperty(IdToKey(id, \"int\").c_str(), id);\n    Test::RecordProperty(\"shared_key\", IdToString(id).c_str());\n\n    // This assertion should fail kThreadCount times per thread.  It\n    // is for testing whether Google Test can handle failed assertions in a\n    // multi-threaded context.\n    EXPECT_LT(i, 0) << \"This should always fail.\";\n  }\n}\n\nvoid CheckTestFailureCount(int expected_failures) {\n  const TestInfo* const info = UnitTest::GetInstance()->current_test_info();\n  const TestResult* const result = info->result();\n  GTEST_CHECK_(expected_failures == result->total_part_count())\n      << \"Logged \" << result->total_part_count() << \" failures \"\n      << \" vs. \" << expected_failures << \" expected\";\n}\n\n// Tests using SCOPED_TRACE() and Google Test assertions in many threads\n// concurrently.\nTEST(StressTest, CanUseScopedTraceAndAssertionsInManyThreads) {\n  {\n    std::unique_ptr<ThreadWithParam<int> > threads[kThreadCount];\n    Notification threads_can_start;\n    for (int i = 0; i != kThreadCount; i++)\n      threads[i].reset(\n          new ThreadWithParam<int>(&ManyAsserts, i, &threads_can_start));\n\n    threads_can_start.Notify();\n\n    // Blocks until all the threads are done.\n    for (int i = 0; i != kThreadCount; i++) threads[i]->Join();\n  }\n\n  // Ensures that kThreadCount*kThreadCount failures have been reported.\n  const TestInfo* const info = UnitTest::GetInstance()->current_test_info();\n  const TestResult* const result = info->result();\n\n  std::vector<TestProperty> properties;\n  // We have no access to the TestResult's list of properties but we can\n  // copy them one by one.\n  for (int i = 0; i < result->test_property_count(); ++i)\n    properties.push_back(result->GetTestProperty(i));\n\n  EXPECT_EQ(kThreadCount * 2 + 1, result->test_property_count())\n      << \"String and int values recorded on each thread, \"\n      << \"as well as one shared_key\";\n  for (int i = 0; i < kThreadCount; ++i) {\n    ExpectKeyAndValueWereRecordedForId(properties, i, \"string\");\n    ExpectKeyAndValueWereRecordedForId(properties, i, \"int\");\n  }\n  CheckTestFailureCount(kThreadCount * kThreadCount);\n}\n\nvoid FailingThread(bool is_fatal) {\n  if (is_fatal)\n    FAIL() << \"Fatal failure in some other thread. \"\n           << \"(This failure is expected.)\";\n  else\n    ADD_FAILURE() << \"Non-fatal failure in some other thread. \"\n                  << \"(This failure is expected.)\";\n}\n\nvoid GenerateFatalFailureInAnotherThread(bool is_fatal) {\n  ThreadWithParam<bool> thread(&FailingThread, is_fatal, nullptr);\n  thread.Join();\n}\n\nTEST(NoFatalFailureTest, ExpectNoFatalFailureIgnoresFailuresInOtherThreads) {\n  EXPECT_NO_FATAL_FAILURE(GenerateFatalFailureInAnotherThread(true));\n  // We should only have one failure (the one from\n  // GenerateFatalFailureInAnotherThread()), since the EXPECT_NO_FATAL_FAILURE\n  // should succeed.\n  CheckTestFailureCount(1);\n}\n\nvoid AssertNoFatalFailureIgnoresFailuresInOtherThreads() {\n  ASSERT_NO_FATAL_FAILURE(GenerateFatalFailureInAnotherThread(true));\n}\nTEST(NoFatalFailureTest, AssertNoFatalFailureIgnoresFailuresInOtherThreads) {\n  // Using a subroutine, to make sure, that the test continues.\n  AssertNoFatalFailureIgnoresFailuresInOtherThreads();\n  // We should only have one failure (the one from\n  // GenerateFatalFailureInAnotherThread()), since the EXPECT_NO_FATAL_FAILURE\n  // should succeed.\n  CheckTestFailureCount(1);\n}\n\nTEST(FatalFailureTest, ExpectFatalFailureIgnoresFailuresInOtherThreads) {\n  // This statement should fail, since the current thread doesn't generate a\n  // fatal failure, only another one does.\n  EXPECT_FATAL_FAILURE(GenerateFatalFailureInAnotherThread(true), \"expected\");\n  CheckTestFailureCount(2);\n}\n\nTEST(FatalFailureOnAllThreadsTest, ExpectFatalFailureOnAllThreads) {\n  // This statement should succeed, because failures in all threads are\n  // considered.\n  EXPECT_FATAL_FAILURE_ON_ALL_THREADS(GenerateFatalFailureInAnotherThread(true),\n                                      \"expected\");\n  CheckTestFailureCount(0);\n  // We need to add a failure, because main() checks that there are failures.\n  // But when only this test is run, we shouldn't have any failures.\n  ADD_FAILURE() << \"This is an expected non-fatal failure.\";\n}\n\nTEST(NonFatalFailureTest, ExpectNonFatalFailureIgnoresFailuresInOtherThreads) {\n  // This statement should fail, since the current thread doesn't generate a\n  // fatal failure, only another one does.\n  EXPECT_NONFATAL_FAILURE(GenerateFatalFailureInAnotherThread(false),\n                          \"expected\");\n  CheckTestFailureCount(2);\n}\n\nTEST(NonFatalFailureOnAllThreadsTest, ExpectNonFatalFailureOnAllThreads) {\n  // This statement should succeed, because failures in all threads are\n  // considered.\n  EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(\n      GenerateFatalFailureInAnotherThread(false), \"expected\");\n  CheckTestFailureCount(0);\n  // We need to add a failure, because main() checks that there are failures,\n  // But when only this test is run, we shouldn't have any failures.\n  ADD_FAILURE() << \"This is an expected non-fatal failure.\";\n}\n\n}  // namespace\n}  // namespace testing\n\nint main(int argc, char** argv) {\n  testing::InitGoogleTest(&argc, argv);\n\n  const int result = RUN_ALL_TESTS();  // Expected to fail.\n  GTEST_CHECK_(result == 1) << \"RUN_ALL_TESTS() did not fail as expected\";\n\n  printf(\"\\nPASS\\n\");\n  return 0;\n}\n\n#else\nTEST(StressTest,\n     DISABLED_ThreadSafetyTestsAreSkippedWhenGoogleTestIsNotThreadSafe) {}\n\nint main(int argc, char **argv) {\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n#endif  // GTEST_IS_THREADSAFE\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_test_macro_stack_footprint_test.cc",
    "content": "// Copyright 2013, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// Each TEST() expands to some static registration logic.  GCC puts all\n// such static initialization logic for a translation unit in a common,\n// internal function.  Since Google's build system restricts how much\n// stack space a function can use, there's a limit on how many TEST()s\n// one can put in a single C++ test file.  This test ensures that a large\n// number of TEST()s can be defined in the same translation unit.\n\n#include \"gtest/gtest.h\"\n\n// This macro defines 10 dummy tests.\n#define TEN_TESTS_(test_case_name) \\\n  TEST(test_case_name, T0) {}      \\\n  TEST(test_case_name, T1) {}      \\\n  TEST(test_case_name, T2) {}      \\\n  TEST(test_case_name, T3) {}      \\\n  TEST(test_case_name, T4) {}      \\\n  TEST(test_case_name, T5) {}      \\\n  TEST(test_case_name, T6) {}      \\\n  TEST(test_case_name, T7) {}      \\\n  TEST(test_case_name, T8) {}      \\\n  TEST(test_case_name, T9) {}\n\n// This macro defines 100 dummy tests.\n#define HUNDRED_TESTS_(test_case_name_prefix) \\\n  TEN_TESTS_(test_case_name_prefix##0)        \\\n  TEN_TESTS_(test_case_name_prefix##1)        \\\n  TEN_TESTS_(test_case_name_prefix##2)        \\\n  TEN_TESTS_(test_case_name_prefix##3)        \\\n  TEN_TESTS_(test_case_name_prefix##4)        \\\n  TEN_TESTS_(test_case_name_prefix##5)        \\\n  TEN_TESTS_(test_case_name_prefix##6)        \\\n  TEN_TESTS_(test_case_name_prefix##7)        \\\n  TEN_TESTS_(test_case_name_prefix##8)        \\\n  TEN_TESTS_(test_case_name_prefix##9)\n\n// This macro defines 1000 dummy tests.\n#define THOUSAND_TESTS_(test_case_name_prefix) \\\n  HUNDRED_TESTS_(test_case_name_prefix##0)     \\\n  HUNDRED_TESTS_(test_case_name_prefix##1)     \\\n  HUNDRED_TESTS_(test_case_name_prefix##2)     \\\n  HUNDRED_TESTS_(test_case_name_prefix##3)     \\\n  HUNDRED_TESTS_(test_case_name_prefix##4)     \\\n  HUNDRED_TESTS_(test_case_name_prefix##5)     \\\n  HUNDRED_TESTS_(test_case_name_prefix##6)     \\\n  HUNDRED_TESTS_(test_case_name_prefix##7)     \\\n  HUNDRED_TESTS_(test_case_name_prefix##8)     \\\n  HUNDRED_TESTS_(test_case_name_prefix##9)\n\n// Ensures that we can define 1000 TEST()s in the same translation\n// unit.\nTHOUSAND_TESTS_(T)\n\nint main(int argc, char **argv) {\n  testing::InitGoogleTest(&argc, argv);\n\n  // We don't actually need to run the dummy tests - the purpose is to\n  // ensure that they compile.\n  return 0;\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_test_utils.py",
    "content": "# Copyright 2006, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Unit test utilities for Google C++ Testing and Mocking Framework.\"\"\"\n# Suppresses the 'Import not at the top of the file' lint complaint.\n# pylint: disable-msg=C6204\n\nimport os\nimport subprocess\nimport sys\n\nIS_WINDOWS = os.name == 'nt'\nIS_CYGWIN = os.name == 'posix' and 'CYGWIN' in os.uname()[0]\nIS_OS2 = os.name == 'os2'\n\nimport atexit\nimport shutil\nimport tempfile\nimport unittest as _test_module\n# pylint: enable-msg=C6204\n\nGTEST_OUTPUT_VAR_NAME = 'GTEST_OUTPUT'\n\n# The environment variable for specifying the path to the premature-exit file.\nPREMATURE_EXIT_FILE_ENV_VAR = 'TEST_PREMATURE_EXIT_FILE'\n\nenviron = os.environ.copy()\n\n\ndef SetEnvVar(env_var, value):\n  \"\"\"Sets/unsets an environment variable to a given value.\"\"\"\n\n  if value is not None:\n    environ[env_var] = value\n  elif env_var in environ:\n    del environ[env_var]\n\n\n# Here we expose a class from a particular module, depending on the\n# environment. The comment suppresses the 'Invalid variable name' lint\n# complaint.\nTestCase = _test_module.TestCase  # pylint: disable=C6409\n\n# Initially maps a flag to its default value. After\n# _ParseAndStripGTestFlags() is called, maps a flag to its actual value.\n_flag_map = {'source_dir': os.path.dirname(sys.argv[0]),\n             'build_dir': os.path.dirname(sys.argv[0])}\n_gtest_flags_are_parsed = False\n\n\ndef _ParseAndStripGTestFlags(argv):\n  \"\"\"Parses and strips Google Test flags from argv.  This is idempotent.\"\"\"\n\n  # Suppresses the lint complaint about a global variable since we need it\n  # here to maintain module-wide state.\n  global _gtest_flags_are_parsed  # pylint: disable=W0603\n  if _gtest_flags_are_parsed:\n    return\n\n  _gtest_flags_are_parsed = True\n  for flag in _flag_map:\n    # The environment variable overrides the default value.\n    if flag.upper() in os.environ:\n      _flag_map[flag] = os.environ[flag.upper()]\n\n    # The command line flag overrides the environment variable.\n    i = 1  # Skips the program name.\n    while i < len(argv):\n      prefix = '--' + flag + '='\n      if argv[i].startswith(prefix):\n        _flag_map[flag] = argv[i][len(prefix):]\n        del argv[i]\n        break\n      else:\n        # We don't increment i in case we just found a --gtest_* flag\n        # and removed it from argv.\n        i += 1\n\n\ndef GetFlag(flag):\n  \"\"\"Returns the value of the given flag.\"\"\"\n\n  # In case GetFlag() is called before Main(), we always call\n  # _ParseAndStripGTestFlags() here to make sure the --gtest_* flags\n  # are parsed.\n  _ParseAndStripGTestFlags(sys.argv)\n\n  return _flag_map[flag]\n\n\ndef GetSourceDir():\n  \"\"\"Returns the absolute path of the directory where the .py files are.\"\"\"\n\n  return os.path.abspath(GetFlag('source_dir'))\n\n\ndef GetBuildDir():\n  \"\"\"Returns the absolute path of the directory where the test binaries are.\"\"\"\n\n  return os.path.abspath(GetFlag('build_dir'))\n\n\n_temp_dir = None\n\ndef _RemoveTempDir():\n  if _temp_dir:\n    shutil.rmtree(_temp_dir, ignore_errors=True)\n\natexit.register(_RemoveTempDir)\n\n\ndef GetTempDir():\n  global _temp_dir\n  if not _temp_dir:\n    _temp_dir = tempfile.mkdtemp()\n  return _temp_dir\n\n\ndef GetTestExecutablePath(executable_name, build_dir=None):\n  \"\"\"Returns the absolute path of the test binary given its name.\n\n  The function will print a message and abort the program if the resulting file\n  doesn't exist.\n\n  Args:\n    executable_name: name of the test binary that the test script runs.\n    build_dir:       directory where to look for executables, by default\n                     the result of GetBuildDir().\n\n  Returns:\n    The absolute path of the test binary.\n  \"\"\"\n\n  path = os.path.abspath(os.path.join(build_dir or GetBuildDir(),\n                                      executable_name))\n  if (IS_WINDOWS or IS_CYGWIN or IS_OS2) and not path.endswith('.exe'):\n    path += '.exe'\n\n  if not os.path.exists(path):\n    message = (\n        'Unable to find the test binary \"%s\". Please make sure to provide\\n'\n        'a path to the binary via the --build_dir flag or the BUILD_DIR\\n'\n        'environment variable.' % path)\n    print(message, file=sys.stderr)\n    sys.exit(1)\n\n  return path\n\n\ndef GetExitStatus(exit_code):\n  \"\"\"Returns the argument to exit(), or -1 if exit() wasn't called.\n\n  Args:\n    exit_code: the result value of os.system(command).\n  \"\"\"\n\n  if os.name == 'nt':\n    # On Windows, os.WEXITSTATUS() doesn't work and os.system() returns\n    # the argument to exit() directly.\n    return exit_code\n  else:\n    # On Unix, os.WEXITSTATUS() must be used to extract the exit status\n    # from the result of os.system().\n    if os.WIFEXITED(exit_code):\n      return os.WEXITSTATUS(exit_code)\n    else:\n      return -1\n\n\nclass Subprocess:\n  def __init__(self, command, working_dir=None, capture_stderr=True, env=None):\n    \"\"\"Changes into a specified directory, if provided, and executes a command.\n\n    Restores the old directory afterwards.\n\n    Args:\n      command:        The command to run, in the form of sys.argv.\n      working_dir:    The directory to change into.\n      capture_stderr: Determines whether to capture stderr in the output member\n                      or to discard it.\n      env:            Dictionary with environment to pass to the subprocess.\n\n    Returns:\n      An object that represents outcome of the executed process. It has the\n      following attributes:\n        terminated_by_signal   True if and only if the child process has been\n                               terminated by a signal.\n        exited                 True if and only if the child process exited\n                               normally.\n        exit_code              The code with which the child process exited.\n        output                 Child process's stdout and stderr output\n                               combined in a string.\n    \"\"\"\n\n    if capture_stderr:\n      stderr = subprocess.STDOUT\n    else:\n      stderr = subprocess.PIPE\n\n    p = subprocess.Popen(command,\n                         stdout=subprocess.PIPE, stderr=stderr,\n                         cwd=working_dir, universal_newlines=True, env=env)\n    # communicate returns a tuple with the file object for the child's\n    # output.\n    self.output = p.communicate()[0]\n    self._return_code = p.returncode\n\n    if bool(self._return_code & 0x80000000):\n      self.terminated_by_signal = True\n      self.exited = False\n    else:\n      self.terminated_by_signal = False\n      self.exited = True\n      self.exit_code = self._return_code\n\n\ndef Main():\n  \"\"\"Runs the unit test.\"\"\"\n\n  # We must call _ParseAndStripGTestFlags() before calling\n  # unittest.main().  Otherwise the latter will be confused by the\n  # --gtest_* flags.\n  _ParseAndStripGTestFlags(sys.argv)\n  # The tested binaries should not be writing XML output files unless the\n  # script explicitly instructs them to.\n  if GTEST_OUTPUT_VAR_NAME in os.environ:\n    del os.environ[GTEST_OUTPUT_VAR_NAME]\n\n  _test_module.main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_testbridge_test.py",
    "content": "#!/usr/bin/env python\n#\n# Copyright 2018 Google LLC. All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\"\"\"Verifies that Google Test uses filter provided via testbridge.\"\"\"\n\nimport os\n\nfrom googletest.test import gtest_test_utils\n\nbinary_name = 'gtest_testbridge_test_'\nCOMMAND = gtest_test_utils.GetTestExecutablePath(binary_name)\nTESTBRIDGE_NAME = 'TESTBRIDGE_TEST_ONLY'\n\n\ndef Assert(condition):\n  if not condition:\n    raise AssertionError\n\n\nclass GTestTestFilterTest(gtest_test_utils.TestCase):\n\n  def testTestExecutionIsFiltered(self):\n    \"\"\"Tests that the test filter is picked up from the testbridge env var.\"\"\"\n    subprocess_env = os.environ.copy()\n\n    subprocess_env[TESTBRIDGE_NAME] = '*.TestThatSucceeds'\n    p = gtest_test_utils.Subprocess(COMMAND, env=subprocess_env)\n\n    self.assertEquals(0, p.exit_code)\n\n    Assert('filter = *.TestThatSucceeds' in p.output)\n    Assert('[       OK ] TestFilterTest.TestThatSucceeds' in p.output)\n    Assert('[  PASSED  ] 1 test.' in p.output)\n\n\nif __name__ == '__main__':\n  gtest_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_testbridge_test_.cc",
    "content": "// Copyright 2018, Google LLC.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// This program is meant to be run by gtest_test_filter_test.py.  Do not run\n// it directly.\n\n#include \"gtest/gtest.h\"\n\n// These tests are used to detect if filtering is working. Only\n// 'TestThatSucceeds' should ever run.\n\nTEST(TestFilterTest, TestThatSucceeds) {}\n\nTEST(TestFilterTest, TestThatFails) {\n  ASSERT_TRUE(false) << \"This test should never be run.\";\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_throw_on_failure_ex_test.cc",
    "content": "// Copyright 2009, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Tests Google Test's throw-on-failure mode with exceptions enabled.\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <stdexcept>\n\n#include \"gtest/gtest.h\"\n\n// Prints the given failure message and exits the program with\n// non-zero.  We use this instead of a Google Test assertion to\n// indicate a failure, as the latter is been tested and cannot be\n// relied on.\nvoid Fail(const char* msg) {\n  printf(\"FAILURE: %s\\n\", msg);\n  fflush(stdout);\n  exit(1);\n}\n\n// Tests that an assertion failure throws a subclass of\n// std::runtime_error.\nvoid TestFailureThrowsRuntimeError() {\n  GTEST_FLAG_SET(throw_on_failure, true);\n\n  // A successful assertion shouldn't throw.\n  try {\n    EXPECT_EQ(3, 3);\n  } catch (...) {\n    Fail(\"A successful assertion wrongfully threw.\");\n  }\n\n  // A failed assertion should throw a subclass of std::runtime_error.\n  try {\n    EXPECT_EQ(2, 3) << \"Expected failure\";\n  } catch (const std::runtime_error& e) {\n    if (strstr(e.what(), \"Expected failure\") != nullptr) return;\n\n    printf(\"%s\",\n           \"A failed assertion did throw an exception of the right type, \"\n           \"but the message is incorrect.  Instead of containing \\\"Expected \"\n           \"failure\\\", it is:\\n\");\n    Fail(e.what());\n  } catch (...) {\n    Fail(\"A failed assertion threw the wrong type of exception.\");\n  }\n  Fail(\"A failed assertion should've thrown but didn't.\");\n}\n\nint main(int argc, char** argv) {\n  testing::InitGoogleTest(&argc, argv);\n\n  // We want to ensure that people can use Google Test assertions in\n  // other testing frameworks, as long as they initialize Google Test\n  // properly and set the thrown-on-failure mode.  Therefore, we don't\n  // use Google Test's constructs for defining and running tests\n  // (e.g. TEST and RUN_ALL_TESTS) here.\n\n  TestFailureThrowsRuntimeError();\n  return 0;\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_unittest.cc",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// Tests for Google Test itself.  This verifies that the basic constructs of\n// Google Test work.\n\n#include \"gtest/gtest.h\"\n\n// Verifies that the command line flag variables can be accessed in\n// code once \"gtest.h\" has been #included.\n// Do not move it after other gtest #includes.\nTEST(CommandLineFlagsTest, CanBeAccessedInCodeOnceGTestHIsIncluded) {\n  bool dummy =\n      GTEST_FLAG_GET(also_run_disabled_tests) ||\n      GTEST_FLAG_GET(break_on_failure) || GTEST_FLAG_GET(catch_exceptions) ||\n      GTEST_FLAG_GET(color) != \"unknown\" || GTEST_FLAG_GET(fail_fast) ||\n      GTEST_FLAG_GET(filter) != \"unknown\" || GTEST_FLAG_GET(list_tests) ||\n      GTEST_FLAG_GET(output) != \"unknown\" || GTEST_FLAG_GET(brief) ||\n      GTEST_FLAG_GET(print_time) || GTEST_FLAG_GET(random_seed) ||\n      GTEST_FLAG_GET(repeat) > 0 ||\n      GTEST_FLAG_GET(recreate_environments_when_repeating) ||\n      GTEST_FLAG_GET(show_internal_stack_frames) || GTEST_FLAG_GET(shuffle) ||\n      GTEST_FLAG_GET(stack_trace_depth) > 0 ||\n      GTEST_FLAG_GET(stream_result_to) != \"unknown\" ||\n      GTEST_FLAG_GET(throw_on_failure);\n  EXPECT_TRUE(dummy || !dummy);  // Suppresses warning that dummy is unused.\n}\n\n#include <limits.h>  // For INT_MAX.\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n\n#include <cstdint>\n#include <map>\n#include <ostream>\n#include <string>\n#include <type_traits>\n#include <unordered_set>\n#include <vector>\n\n#include \"gtest/gtest-spi.h\"\n#include \"src/gtest-internal-inl.h\"\n\nnamespace testing {\nnamespace internal {\n\n#if GTEST_CAN_STREAM_RESULTS_\n\nclass StreamingListenerTest : public Test {\n public:\n  class FakeSocketWriter : public StreamingListener::AbstractSocketWriter {\n   public:\n    // Sends a string to the socket.\n    void Send(const std::string& message) override { output_ += message; }\n\n    std::string output_;\n  };\n\n  StreamingListenerTest()\n      : fake_sock_writer_(new FakeSocketWriter),\n        streamer_(fake_sock_writer_),\n        test_info_obj_(\"FooTest\", \"Bar\", nullptr, nullptr,\n                       CodeLocation(__FILE__, __LINE__), nullptr, nullptr) {}\n\n protected:\n  std::string* output() { return &(fake_sock_writer_->output_); }\n\n  FakeSocketWriter* const fake_sock_writer_;\n  StreamingListener streamer_;\n  UnitTest unit_test_;\n  TestInfo test_info_obj_;  // The name test_info_ was taken by testing::Test.\n};\n\nTEST_F(StreamingListenerTest, OnTestProgramEnd) {\n  *output() = \"\";\n  streamer_.OnTestProgramEnd(unit_test_);\n  EXPECT_EQ(\"event=TestProgramEnd&passed=1\\n\", *output());\n}\n\nTEST_F(StreamingListenerTest, OnTestIterationEnd) {\n  *output() = \"\";\n  streamer_.OnTestIterationEnd(unit_test_, 42);\n  EXPECT_EQ(\"event=TestIterationEnd&passed=1&elapsed_time=0ms\\n\", *output());\n}\n\nTEST_F(StreamingListenerTest, OnTestSuiteStart) {\n  *output() = \"\";\n  streamer_.OnTestSuiteStart(TestSuite(\"FooTest\", \"Bar\", nullptr, nullptr));\n  EXPECT_EQ(\"event=TestCaseStart&name=FooTest\\n\", *output());\n}\n\nTEST_F(StreamingListenerTest, OnTestSuiteEnd) {\n  *output() = \"\";\n  streamer_.OnTestSuiteEnd(TestSuite(\"FooTest\", \"Bar\", nullptr, nullptr));\n  EXPECT_EQ(\"event=TestCaseEnd&passed=1&elapsed_time=0ms\\n\", *output());\n}\n\nTEST_F(StreamingListenerTest, OnTestStart) {\n  *output() = \"\";\n  streamer_.OnTestStart(test_info_obj_);\n  EXPECT_EQ(\"event=TestStart&name=Bar\\n\", *output());\n}\n\nTEST_F(StreamingListenerTest, OnTestEnd) {\n  *output() = \"\";\n  streamer_.OnTestEnd(test_info_obj_);\n  EXPECT_EQ(\"event=TestEnd&passed=1&elapsed_time=0ms\\n\", *output());\n}\n\nTEST_F(StreamingListenerTest, OnTestPartResult) {\n  *output() = \"\";\n  streamer_.OnTestPartResult(TestPartResult(TestPartResult::kFatalFailure,\n                                            \"foo.cc\", 42, \"failed=\\n&%\"));\n\n  // Meta characters in the failure message should be properly escaped.\n  EXPECT_EQ(\n      \"event=TestPartResult&file=foo.cc&line=42&message=failed%3D%0A%26%25\\n\",\n      *output());\n}\n\n#endif  // GTEST_CAN_STREAM_RESULTS_\n\n// Provides access to otherwise private parts of the TestEventListeners class\n// that are needed to test it.\nclass TestEventListenersAccessor {\n public:\n  static TestEventListener* GetRepeater(TestEventListeners* listeners) {\n    return listeners->repeater();\n  }\n\n  static void SetDefaultResultPrinter(TestEventListeners* listeners,\n                                      TestEventListener* listener) {\n    listeners->SetDefaultResultPrinter(listener);\n  }\n  static void SetDefaultXmlGenerator(TestEventListeners* listeners,\n                                     TestEventListener* listener) {\n    listeners->SetDefaultXmlGenerator(listener);\n  }\n\n  static bool EventForwardingEnabled(const TestEventListeners& listeners) {\n    return listeners.EventForwardingEnabled();\n  }\n\n  static void SuppressEventForwarding(TestEventListeners* listeners) {\n    listeners->SuppressEventForwarding();\n  }\n};\n\nclass UnitTestRecordPropertyTestHelper : public Test {\n protected:\n  UnitTestRecordPropertyTestHelper() {}\n\n  // Forwards to UnitTest::RecordProperty() to bypass access controls.\n  void UnitTestRecordProperty(const char* key, const std::string& value) {\n    unit_test_.RecordProperty(key, value);\n  }\n\n  UnitTest unit_test_;\n};\n\n}  // namespace internal\n}  // namespace testing\n\nusing testing::AssertionFailure;\nusing testing::AssertionResult;\nusing testing::AssertionSuccess;\nusing testing::DoubleLE;\nusing testing::EmptyTestEventListener;\nusing testing::Environment;\nusing testing::FloatLE;\nusing testing::IsNotSubstring;\nusing testing::IsSubstring;\nusing testing::kMaxStackTraceDepth;\nusing testing::Message;\nusing testing::ScopedFakeTestPartResultReporter;\nusing testing::StaticAssertTypeEq;\nusing testing::Test;\nusing testing::TestEventListeners;\nusing testing::TestInfo;\nusing testing::TestPartResult;\nusing testing::TestPartResultArray;\nusing testing::TestProperty;\nusing testing::TestResult;\nusing testing::TestSuite;\nusing testing::TimeInMillis;\nusing testing::UnitTest;\nusing testing::internal::AlwaysFalse;\nusing testing::internal::AlwaysTrue;\nusing testing::internal::AppendUserMessage;\nusing testing::internal::ArrayAwareFind;\nusing testing::internal::ArrayEq;\nusing testing::internal::CodePointToUtf8;\nusing testing::internal::CopyArray;\nusing testing::internal::CountIf;\nusing testing::internal::EqFailure;\nusing testing::internal::FloatingPoint;\nusing testing::internal::ForEach;\nusing testing::internal::FormatEpochTimeInMillisAsIso8601;\nusing testing::internal::FormatTimeInMillisAsSeconds;\nusing testing::internal::GetCurrentOsStackTraceExceptTop;\nusing testing::internal::GetElementOr;\nusing testing::internal::GetNextRandomSeed;\nusing testing::internal::GetRandomSeedFromFlag;\nusing testing::internal::GetTestTypeId;\nusing testing::internal::GetTimeInMillis;\nusing testing::internal::GetTypeId;\nusing testing::internal::GetUnitTestImpl;\nusing testing::internal::GTestFlagSaver;\nusing testing::internal::HasDebugStringAndShortDebugString;\nusing testing::internal::Int32FromEnvOrDie;\nusing testing::internal::IsContainer;\nusing testing::internal::IsContainerTest;\nusing testing::internal::IsNotContainer;\nusing testing::internal::kMaxRandomSeed;\nusing testing::internal::kTestTypeIdInGoogleTest;\nusing testing::internal::NativeArray;\nusing testing::internal::OsStackTraceGetter;\nusing testing::internal::OsStackTraceGetterInterface;\nusing testing::internal::ParseFlag;\nusing testing::internal::RelationToSourceCopy;\nusing testing::internal::RelationToSourceReference;\nusing testing::internal::ShouldRunTestOnShard;\nusing testing::internal::ShouldShard;\nusing testing::internal::ShouldUseColor;\nusing testing::internal::Shuffle;\nusing testing::internal::ShuffleRange;\nusing testing::internal::SkipPrefix;\nusing testing::internal::StreamableToString;\nusing testing::internal::String;\nusing testing::internal::TestEventListenersAccessor;\nusing testing::internal::TestResultAccessor;\nusing testing::internal::UnitTestImpl;\nusing testing::internal::WideStringToUtf8;\nusing testing::internal::edit_distance::CalculateOptimalEdits;\nusing testing::internal::edit_distance::CreateUnifiedDiff;\nusing testing::internal::edit_distance::EditType;\n\n#if GTEST_HAS_STREAM_REDIRECTION\nusing testing::internal::CaptureStdout;\nusing testing::internal::GetCapturedStdout;\n#endif\n\n#if GTEST_IS_THREADSAFE\nusing testing::internal::ThreadWithParam;\n#endif\n\nclass TestingVector : public std::vector<int> {};\n\n::std::ostream& operator<<(::std::ostream& os, const TestingVector& vector) {\n  os << \"{ \";\n  for (size_t i = 0; i < vector.size(); i++) {\n    os << vector[i] << \" \";\n  }\n  os << \"}\";\n  return os;\n}\n\n// This line tests that we can define tests in an unnamed namespace.\nnamespace {\n\nTEST(GetRandomSeedFromFlagTest, HandlesZero) {\n  const int seed = GetRandomSeedFromFlag(0);\n  EXPECT_LE(1, seed);\n  EXPECT_LE(seed, static_cast<int>(kMaxRandomSeed));\n}\n\nTEST(GetRandomSeedFromFlagTest, PreservesValidSeed) {\n  EXPECT_EQ(1, GetRandomSeedFromFlag(1));\n  EXPECT_EQ(2, GetRandomSeedFromFlag(2));\n  EXPECT_EQ(kMaxRandomSeed - 1, GetRandomSeedFromFlag(kMaxRandomSeed - 1));\n  EXPECT_EQ(static_cast<int>(kMaxRandomSeed),\n            GetRandomSeedFromFlag(kMaxRandomSeed));\n}\n\nTEST(GetRandomSeedFromFlagTest, NormalizesInvalidSeed) {\n  const int seed1 = GetRandomSeedFromFlag(-1);\n  EXPECT_LE(1, seed1);\n  EXPECT_LE(seed1, static_cast<int>(kMaxRandomSeed));\n\n  const int seed2 = GetRandomSeedFromFlag(kMaxRandomSeed + 1);\n  EXPECT_LE(1, seed2);\n  EXPECT_LE(seed2, static_cast<int>(kMaxRandomSeed));\n}\n\nTEST(GetNextRandomSeedTest, WorksForValidInput) {\n  EXPECT_EQ(2, GetNextRandomSeed(1));\n  EXPECT_EQ(3, GetNextRandomSeed(2));\n  EXPECT_EQ(static_cast<int>(kMaxRandomSeed),\n            GetNextRandomSeed(kMaxRandomSeed - 1));\n  EXPECT_EQ(1, GetNextRandomSeed(kMaxRandomSeed));\n\n  // We deliberately don't test GetNextRandomSeed() with invalid\n  // inputs, as that requires death tests, which are expensive.  This\n  // is fine as GetNextRandomSeed() is internal and has a\n  // straightforward definition.\n}\n\nstatic void ClearCurrentTestPartResults() {\n  TestResultAccessor::ClearTestPartResults(\n      GetUnitTestImpl()->current_test_result());\n}\n\n// Tests GetTypeId.\n\nTEST(GetTypeIdTest, ReturnsSameValueForSameType) {\n  EXPECT_EQ(GetTypeId<int>(), GetTypeId<int>());\n  EXPECT_EQ(GetTypeId<Test>(), GetTypeId<Test>());\n}\n\nclass SubClassOfTest : public Test {};\nclass AnotherSubClassOfTest : public Test {};\n\nTEST(GetTypeIdTest, ReturnsDifferentValuesForDifferentTypes) {\n  EXPECT_NE(GetTypeId<int>(), GetTypeId<const int>());\n  EXPECT_NE(GetTypeId<int>(), GetTypeId<char>());\n  EXPECT_NE(GetTypeId<int>(), GetTestTypeId());\n  EXPECT_NE(GetTypeId<SubClassOfTest>(), GetTestTypeId());\n  EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTestTypeId());\n  EXPECT_NE(GetTypeId<AnotherSubClassOfTest>(), GetTypeId<SubClassOfTest>());\n}\n\n// Verifies that GetTestTypeId() returns the same value, no matter it\n// is called from inside Google Test or outside of it.\nTEST(GetTestTypeIdTest, ReturnsTheSameValueInsideOrOutsideOfGoogleTest) {\n  EXPECT_EQ(kTestTypeIdInGoogleTest, GetTestTypeId());\n}\n\n// Tests CanonicalizeForStdLibVersioning.\n\nusing ::testing::internal::CanonicalizeForStdLibVersioning;\n\nTEST(CanonicalizeForStdLibVersioning, LeavesUnversionedNamesUnchanged) {\n  EXPECT_EQ(\"std::bind\", CanonicalizeForStdLibVersioning(\"std::bind\"));\n  EXPECT_EQ(\"std::_\", CanonicalizeForStdLibVersioning(\"std::_\"));\n  EXPECT_EQ(\"std::__foo\", CanonicalizeForStdLibVersioning(\"std::__foo\"));\n  EXPECT_EQ(\"gtl::__1::x\", CanonicalizeForStdLibVersioning(\"gtl::__1::x\"));\n  EXPECT_EQ(\"__1::x\", CanonicalizeForStdLibVersioning(\"__1::x\"));\n  EXPECT_EQ(\"::__1::x\", CanonicalizeForStdLibVersioning(\"::__1::x\"));\n}\n\nTEST(CanonicalizeForStdLibVersioning, ElidesDoubleUnderNames) {\n  EXPECT_EQ(\"std::bind\", CanonicalizeForStdLibVersioning(\"std::__1::bind\"));\n  EXPECT_EQ(\"std::_\", CanonicalizeForStdLibVersioning(\"std::__1::_\"));\n\n  EXPECT_EQ(\"std::bind\", CanonicalizeForStdLibVersioning(\"std::__g::bind\"));\n  EXPECT_EQ(\"std::_\", CanonicalizeForStdLibVersioning(\"std::__g::_\"));\n\n  EXPECT_EQ(\"std::bind\",\n            CanonicalizeForStdLibVersioning(\"std::__google::bind\"));\n  EXPECT_EQ(\"std::_\", CanonicalizeForStdLibVersioning(\"std::__google::_\"));\n}\n\n// Tests FormatTimeInMillisAsSeconds().\n\nTEST(FormatTimeInMillisAsSecondsTest, FormatsZero) {\n  EXPECT_EQ(\"0\", FormatTimeInMillisAsSeconds(0));\n}\n\nTEST(FormatTimeInMillisAsSecondsTest, FormatsPositiveNumber) {\n  EXPECT_EQ(\"0.003\", FormatTimeInMillisAsSeconds(3));\n  EXPECT_EQ(\"0.01\", FormatTimeInMillisAsSeconds(10));\n  EXPECT_EQ(\"0.2\", FormatTimeInMillisAsSeconds(200));\n  EXPECT_EQ(\"1.2\", FormatTimeInMillisAsSeconds(1200));\n  EXPECT_EQ(\"3\", FormatTimeInMillisAsSeconds(3000));\n}\n\nTEST(FormatTimeInMillisAsSecondsTest, FormatsNegativeNumber) {\n  EXPECT_EQ(\"-0.003\", FormatTimeInMillisAsSeconds(-3));\n  EXPECT_EQ(\"-0.01\", FormatTimeInMillisAsSeconds(-10));\n  EXPECT_EQ(\"-0.2\", FormatTimeInMillisAsSeconds(-200));\n  EXPECT_EQ(\"-1.2\", FormatTimeInMillisAsSeconds(-1200));\n  EXPECT_EQ(\"-3\", FormatTimeInMillisAsSeconds(-3000));\n}\n\n// Tests FormatEpochTimeInMillisAsIso8601().  The correctness of conversion\n// for particular dates below was verified in Python using\n// datetime.datetime.fromutctimestamp(<timestamp>/1000).\n\n// FormatEpochTimeInMillisAsIso8601 depends on the current timezone, so we\n// have to set up a particular timezone to obtain predictable results.\nclass FormatEpochTimeInMillisAsIso8601Test : public Test {\n public:\n  // On Cygwin, GCC doesn't allow unqualified integer literals to exceed\n  // 32 bits, even when 64-bit integer types are available.  We have to\n  // force the constants to have a 64-bit type here.\n  static const TimeInMillis kMillisPerSec = 1000;\n\n private:\n  void SetUp() override {\n    saved_tz_ = nullptr;\n\n    GTEST_DISABLE_MSC_DEPRECATED_PUSH_(/* getenv, strdup: deprecated */)\n    if (getenv(\"TZ\")) saved_tz_ = strdup(getenv(\"TZ\"));\n    GTEST_DISABLE_MSC_DEPRECATED_POP_()\n\n    // Set up the time zone for FormatEpochTimeInMillisAsIso8601 to use.  We\n    // cannot use the local time zone because the function's output depends\n    // on the time zone.\n    SetTimeZone(\"UTC+00\");\n  }\n\n  void TearDown() override {\n    SetTimeZone(saved_tz_);\n    free(const_cast<char*>(saved_tz_));\n    saved_tz_ = nullptr;\n  }\n\n  static void SetTimeZone(const char* time_zone) {\n    // tzset() distinguishes between the TZ variable being present and empty\n    // and not being present, so we have to consider the case of time_zone\n    // being NULL.\n#if _MSC_VER || GTEST_OS_WINDOWS_MINGW\n    // ...Unless it's MSVC, whose standard library's _putenv doesn't\n    // distinguish between an empty and a missing variable.\n    const std::string env_var =\n        std::string(\"TZ=\") + (time_zone ? time_zone : \"\");\n    _putenv(env_var.c_str());\n    GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996 /* deprecated function */)\n    tzset();\n    GTEST_DISABLE_MSC_WARNINGS_POP_()\n#else\n#if GTEST_OS_LINUX_ANDROID && __ANDROID_API__ < 21\n    // Work around KitKat bug in tzset by setting \"UTC\" before setting \"UTC+00\".\n    // See https://github.com/android/ndk/issues/1604.\n    setenv(\"TZ\", \"UTC\", 1);\n    tzset();\n#endif\n    if (time_zone) {\n      setenv((\"TZ\"), time_zone, 1);\n    } else {\n      unsetenv(\"TZ\");\n    }\n    tzset();\n#endif\n  }\n\n  const char* saved_tz_;\n};\n\nconst TimeInMillis FormatEpochTimeInMillisAsIso8601Test::kMillisPerSec;\n\nTEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsTwoDigitSegments) {\n  EXPECT_EQ(\"2011-10-31T18:52:42.000\",\n            FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec));\n}\n\nTEST_F(FormatEpochTimeInMillisAsIso8601Test, IncludesMillisecondsAfterDot) {\n  EXPECT_EQ(\"2011-10-31T18:52:42.234\",\n            FormatEpochTimeInMillisAsIso8601(1320087162 * kMillisPerSec + 234));\n}\n\nTEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsLeadingZeroes) {\n  EXPECT_EQ(\"2011-09-03T05:07:02.000\",\n            FormatEpochTimeInMillisAsIso8601(1315026422 * kMillisPerSec));\n}\n\nTEST_F(FormatEpochTimeInMillisAsIso8601Test, Prints24HourTime) {\n  EXPECT_EQ(\"2011-09-28T17:08:22.000\",\n            FormatEpochTimeInMillisAsIso8601(1317229702 * kMillisPerSec));\n}\n\nTEST_F(FormatEpochTimeInMillisAsIso8601Test, PrintsEpochStart) {\n  EXPECT_EQ(\"1970-01-01T00:00:00.000\", FormatEpochTimeInMillisAsIso8601(0));\n}\n\n#ifdef __BORLANDC__\n// Silences warnings: \"Condition is always true\", \"Unreachable code\"\n#pragma option push -w-ccc -w-rch\n#endif\n\n// Tests that the LHS of EXPECT_EQ or ASSERT_EQ can be used as a null literal\n// when the RHS is a pointer type.\nTEST(NullLiteralTest, LHSAllowsNullLiterals) {\n  EXPECT_EQ(0, static_cast<void*>(nullptr));     // NOLINT\n  ASSERT_EQ(0, static_cast<void*>(nullptr));     // NOLINT\n  EXPECT_EQ(NULL, static_cast<void*>(nullptr));  // NOLINT\n  ASSERT_EQ(NULL, static_cast<void*>(nullptr));  // NOLINT\n  EXPECT_EQ(nullptr, static_cast<void*>(nullptr));\n  ASSERT_EQ(nullptr, static_cast<void*>(nullptr));\n\n  const int* const p = nullptr;\n  EXPECT_EQ(0, p);     // NOLINT\n  ASSERT_EQ(0, p);     // NOLINT\n  EXPECT_EQ(NULL, p);  // NOLINT\n  ASSERT_EQ(NULL, p);  // NOLINT\n  EXPECT_EQ(nullptr, p);\n  ASSERT_EQ(nullptr, p);\n}\n\nstruct ConvertToAll {\n  template <typename T>\n  operator T() const {  // NOLINT\n    return T();\n  }\n};\n\nstruct ConvertToPointer {\n  template <class T>\n  operator T*() const {  // NOLINT\n    return nullptr;\n  }\n};\n\nstruct ConvertToAllButNoPointers {\n  template <typename T,\n            typename std::enable_if<!std::is_pointer<T>::value, int>::type = 0>\n  operator T() const {  // NOLINT\n    return T();\n  }\n};\n\nstruct MyType {};\ninline bool operator==(MyType const&, MyType const&) { return true; }\n\nTEST(NullLiteralTest, ImplicitConversion) {\n  EXPECT_EQ(ConvertToPointer{}, static_cast<void*>(nullptr));\n#if !defined(__GNUC__) || defined(__clang__)\n  // Disabled due to GCC bug gcc.gnu.org/PR89580\n  EXPECT_EQ(ConvertToAll{}, static_cast<void*>(nullptr));\n#endif\n  EXPECT_EQ(ConvertToAll{}, MyType{});\n  EXPECT_EQ(ConvertToAllButNoPointers{}, MyType{});\n}\n\n#ifdef __clang__\n#pragma clang diagnostic push\n#if __has_warning(\"-Wzero-as-null-pointer-constant\")\n#pragma clang diagnostic error \"-Wzero-as-null-pointer-constant\"\n#endif\n#endif\n\nTEST(NullLiteralTest, NoConversionNoWarning) {\n  // Test that gtests detection and handling of null pointer constants\n  // doesn't trigger a warning when '0' isn't actually used as null.\n  EXPECT_EQ(0, 0);\n  ASSERT_EQ(0, 0);\n}\n\n#ifdef __clang__\n#pragma clang diagnostic pop\n#endif\n\n#ifdef __BORLANDC__\n// Restores warnings after previous \"#pragma option push\" suppressed them.\n#pragma option pop\n#endif\n\n//\n// Tests CodePointToUtf8().\n\n// Tests that the NUL character L'\\0' is encoded correctly.\nTEST(CodePointToUtf8Test, CanEncodeNul) {\n  EXPECT_EQ(\"\", CodePointToUtf8(L'\\0'));\n}\n\n// Tests that ASCII characters are encoded correctly.\nTEST(CodePointToUtf8Test, CanEncodeAscii) {\n  EXPECT_EQ(\"a\", CodePointToUtf8(L'a'));\n  EXPECT_EQ(\"Z\", CodePointToUtf8(L'Z'));\n  EXPECT_EQ(\"&\", CodePointToUtf8(L'&'));\n  EXPECT_EQ(\"\\x7F\", CodePointToUtf8(L'\\x7F'));\n}\n\n// Tests that Unicode code-points that have 8 to 11 bits are encoded\n// as 110xxxxx 10xxxxxx.\nTEST(CodePointToUtf8Test, CanEncode8To11Bits) {\n  // 000 1101 0011 => 110-00011 10-010011\n  EXPECT_EQ(\"\\xC3\\x93\", CodePointToUtf8(L'\\xD3'));\n\n  // 101 0111 0110 => 110-10101 10-110110\n  // Some compilers (e.g., GCC on MinGW) cannot handle non-ASCII codepoints\n  // in wide strings and wide chars. In order to accommodate them, we have to\n  // introduce such character constants as integers.\n  EXPECT_EQ(\"\\xD5\\xB6\", CodePointToUtf8(static_cast<wchar_t>(0x576)));\n}\n\n// Tests that Unicode code-points that have 12 to 16 bits are encoded\n// as 1110xxxx 10xxxxxx 10xxxxxx.\nTEST(CodePointToUtf8Test, CanEncode12To16Bits) {\n  // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011\n  EXPECT_EQ(\"\\xE0\\xA3\\x93\", CodePointToUtf8(static_cast<wchar_t>(0x8D3)));\n\n  // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101\n  EXPECT_EQ(\"\\xEC\\x9D\\x8D\", CodePointToUtf8(static_cast<wchar_t>(0xC74D)));\n}\n\n#if !GTEST_WIDE_STRING_USES_UTF16_\n// Tests in this group require a wchar_t to hold > 16 bits, and thus\n// are skipped on Windows, and Cygwin, where a wchar_t is\n// 16-bit wide. This code may not compile on those systems.\n\n// Tests that Unicode code-points that have 17 to 21 bits are encoded\n// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx.\nTEST(CodePointToUtf8Test, CanEncode17To21Bits) {\n  // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011\n  EXPECT_EQ(\"\\xF0\\x90\\xA3\\x93\", CodePointToUtf8(L'\\x108D3'));\n\n  // 0 0001 0000 0100 0000 0000 => 11110-000 10-010000 10-010000 10-000000\n  EXPECT_EQ(\"\\xF0\\x90\\x90\\x80\", CodePointToUtf8(L'\\x10400'));\n\n  // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100\n  EXPECT_EQ(\"\\xF4\\x88\\x98\\xB4\", CodePointToUtf8(L'\\x108634'));\n}\n\n// Tests that encoding an invalid code-point generates the expected result.\nTEST(CodePointToUtf8Test, CanEncodeInvalidCodePoint) {\n  EXPECT_EQ(\"(Invalid Unicode 0x1234ABCD)\", CodePointToUtf8(L'\\x1234ABCD'));\n}\n\n#endif  // !GTEST_WIDE_STRING_USES_UTF16_\n\n// Tests WideStringToUtf8().\n\n// Tests that the NUL character L'\\0' is encoded correctly.\nTEST(WideStringToUtf8Test, CanEncodeNul) {\n  EXPECT_STREQ(\"\", WideStringToUtf8(L\"\", 0).c_str());\n  EXPECT_STREQ(\"\", WideStringToUtf8(L\"\", -1).c_str());\n}\n\n// Tests that ASCII strings are encoded correctly.\nTEST(WideStringToUtf8Test, CanEncodeAscii) {\n  EXPECT_STREQ(\"a\", WideStringToUtf8(L\"a\", 1).c_str());\n  EXPECT_STREQ(\"ab\", WideStringToUtf8(L\"ab\", 2).c_str());\n  EXPECT_STREQ(\"a\", WideStringToUtf8(L\"a\", -1).c_str());\n  EXPECT_STREQ(\"ab\", WideStringToUtf8(L\"ab\", -1).c_str());\n}\n\n// Tests that Unicode code-points that have 8 to 11 bits are encoded\n// as 110xxxxx 10xxxxxx.\nTEST(WideStringToUtf8Test, CanEncode8To11Bits) {\n  // 000 1101 0011 => 110-00011 10-010011\n  EXPECT_STREQ(\"\\xC3\\x93\", WideStringToUtf8(L\"\\xD3\", 1).c_str());\n  EXPECT_STREQ(\"\\xC3\\x93\", WideStringToUtf8(L\"\\xD3\", -1).c_str());\n\n  // 101 0111 0110 => 110-10101 10-110110\n  const wchar_t s[] = {0x576, '\\0'};\n  EXPECT_STREQ(\"\\xD5\\xB6\", WideStringToUtf8(s, 1).c_str());\n  EXPECT_STREQ(\"\\xD5\\xB6\", WideStringToUtf8(s, -1).c_str());\n}\n\n// Tests that Unicode code-points that have 12 to 16 bits are encoded\n// as 1110xxxx 10xxxxxx 10xxxxxx.\nTEST(WideStringToUtf8Test, CanEncode12To16Bits) {\n  // 0000 1000 1101 0011 => 1110-0000 10-100011 10-010011\n  const wchar_t s1[] = {0x8D3, '\\0'};\n  EXPECT_STREQ(\"\\xE0\\xA3\\x93\", WideStringToUtf8(s1, 1).c_str());\n  EXPECT_STREQ(\"\\xE0\\xA3\\x93\", WideStringToUtf8(s1, -1).c_str());\n\n  // 1100 0111 0100 1101 => 1110-1100 10-011101 10-001101\n  const wchar_t s2[] = {0xC74D, '\\0'};\n  EXPECT_STREQ(\"\\xEC\\x9D\\x8D\", WideStringToUtf8(s2, 1).c_str());\n  EXPECT_STREQ(\"\\xEC\\x9D\\x8D\", WideStringToUtf8(s2, -1).c_str());\n}\n\n// Tests that the conversion stops when the function encounters \\0 character.\nTEST(WideStringToUtf8Test, StopsOnNulCharacter) {\n  EXPECT_STREQ(\"ABC\", WideStringToUtf8(L\"ABC\\0XYZ\", 100).c_str());\n}\n\n// Tests that the conversion stops when the function reaches the limit\n// specified by the 'length' parameter.\nTEST(WideStringToUtf8Test, StopsWhenLengthLimitReached) {\n  EXPECT_STREQ(\"ABC\", WideStringToUtf8(L\"ABCDEF\", 3).c_str());\n}\n\n#if !GTEST_WIDE_STRING_USES_UTF16_\n// Tests that Unicode code-points that have 17 to 21 bits are encoded\n// as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx. This code may not compile\n// on the systems using UTF-16 encoding.\nTEST(WideStringToUtf8Test, CanEncode17To21Bits) {\n  // 0 0001 0000 1000 1101 0011 => 11110-000 10-010000 10-100011 10-010011\n  EXPECT_STREQ(\"\\xF0\\x90\\xA3\\x93\", WideStringToUtf8(L\"\\x108D3\", 1).c_str());\n  EXPECT_STREQ(\"\\xF0\\x90\\xA3\\x93\", WideStringToUtf8(L\"\\x108D3\", -1).c_str());\n\n  // 1 0000 1000 0110 0011 0100 => 11110-100 10-001000 10-011000 10-110100\n  EXPECT_STREQ(\"\\xF4\\x88\\x98\\xB4\", WideStringToUtf8(L\"\\x108634\", 1).c_str());\n  EXPECT_STREQ(\"\\xF4\\x88\\x98\\xB4\", WideStringToUtf8(L\"\\x108634\", -1).c_str());\n}\n\n// Tests that encoding an invalid code-point generates the expected result.\nTEST(WideStringToUtf8Test, CanEncodeInvalidCodePoint) {\n  EXPECT_STREQ(\"(Invalid Unicode 0xABCDFF)\",\n               WideStringToUtf8(L\"\\xABCDFF\", -1).c_str());\n}\n#else   // !GTEST_WIDE_STRING_USES_UTF16_\n// Tests that surrogate pairs are encoded correctly on the systems using\n// UTF-16 encoding in the wide strings.\nTEST(WideStringToUtf8Test, CanEncodeValidUtf16SUrrogatePairs) {\n  const wchar_t s[] = {0xD801, 0xDC00, '\\0'};\n  EXPECT_STREQ(\"\\xF0\\x90\\x90\\x80\", WideStringToUtf8(s, -1).c_str());\n}\n\n// Tests that encoding an invalid UTF-16 surrogate pair\n// generates the expected result.\nTEST(WideStringToUtf8Test, CanEncodeInvalidUtf16SurrogatePair) {\n  // Leading surrogate is at the end of the string.\n  const wchar_t s1[] = {0xD800, '\\0'};\n  EXPECT_STREQ(\"\\xED\\xA0\\x80\", WideStringToUtf8(s1, -1).c_str());\n  // Leading surrogate is not followed by the trailing surrogate.\n  const wchar_t s2[] = {0xD800, 'M', '\\0'};\n  EXPECT_STREQ(\"\\xED\\xA0\\x80M\", WideStringToUtf8(s2, -1).c_str());\n  // Trailing surrogate appearas without a leading surrogate.\n  const wchar_t s3[] = {0xDC00, 'P', 'Q', 'R', '\\0'};\n  EXPECT_STREQ(\"\\xED\\xB0\\x80PQR\", WideStringToUtf8(s3, -1).c_str());\n}\n#endif  // !GTEST_WIDE_STRING_USES_UTF16_\n\n// Tests that codepoint concatenation works correctly.\n#if !GTEST_WIDE_STRING_USES_UTF16_\nTEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {\n  const wchar_t s[] = {0x108634, 0xC74D, '\\n', 0x576, 0x8D3, 0x108634, '\\0'};\n  EXPECT_STREQ(\n      \"\\xF4\\x88\\x98\\xB4\"\n      \"\\xEC\\x9D\\x8D\"\n      \"\\n\"\n      \"\\xD5\\xB6\"\n      \"\\xE0\\xA3\\x93\"\n      \"\\xF4\\x88\\x98\\xB4\",\n      WideStringToUtf8(s, -1).c_str());\n}\n#else\nTEST(WideStringToUtf8Test, ConcatenatesCodepointsCorrectly) {\n  const wchar_t s[] = {0xC74D, '\\n', 0x576, 0x8D3, '\\0'};\n  EXPECT_STREQ(\n      \"\\xEC\\x9D\\x8D\"\n      \"\\n\"\n      \"\\xD5\\xB6\"\n      \"\\xE0\\xA3\\x93\",\n      WideStringToUtf8(s, -1).c_str());\n}\n#endif  // !GTEST_WIDE_STRING_USES_UTF16_\n\n// Tests the Random class.\n\nTEST(RandomDeathTest, GeneratesCrashesOnInvalidRange) {\n  testing::internal::Random random(42);\n  EXPECT_DEATH_IF_SUPPORTED(random.Generate(0),\n                            \"Cannot generate a number in the range \\\\[0, 0\\\\)\");\n  EXPECT_DEATH_IF_SUPPORTED(\n      random.Generate(testing::internal::Random::kMaxRange + 1),\n      \"Generation of a number in \\\\[0, 2147483649\\\\) was requested, \"\n      \"but this can only generate numbers in \\\\[0, 2147483648\\\\)\");\n}\n\nTEST(RandomTest, GeneratesNumbersWithinRange) {\n  constexpr uint32_t kRange = 10000;\n  testing::internal::Random random(12345);\n  for (int i = 0; i < 10; i++) {\n    EXPECT_LT(random.Generate(kRange), kRange) << \" for iteration \" << i;\n  }\n\n  testing::internal::Random random2(testing::internal::Random::kMaxRange);\n  for (int i = 0; i < 10; i++) {\n    EXPECT_LT(random2.Generate(kRange), kRange) << \" for iteration \" << i;\n  }\n}\n\nTEST(RandomTest, RepeatsWhenReseeded) {\n  constexpr int kSeed = 123;\n  constexpr int kArraySize = 10;\n  constexpr uint32_t kRange = 10000;\n  uint32_t values[kArraySize];\n\n  testing::internal::Random random(kSeed);\n  for (int i = 0; i < kArraySize; i++) {\n    values[i] = random.Generate(kRange);\n  }\n\n  random.Reseed(kSeed);\n  for (int i = 0; i < kArraySize; i++) {\n    EXPECT_EQ(values[i], random.Generate(kRange)) << \" for iteration \" << i;\n  }\n}\n\n// Tests STL container utilities.\n\n// Tests CountIf().\n\nstatic bool IsPositive(int n) { return n > 0; }\n\nTEST(ContainerUtilityTest, CountIf) {\n  std::vector<int> v;\n  EXPECT_EQ(0, CountIf(v, IsPositive));  // Works for an empty container.\n\n  v.push_back(-1);\n  v.push_back(0);\n  EXPECT_EQ(0, CountIf(v, IsPositive));  // Works when no value satisfies.\n\n  v.push_back(2);\n  v.push_back(-10);\n  v.push_back(10);\n  EXPECT_EQ(2, CountIf(v, IsPositive));\n}\n\n// Tests ForEach().\n\nstatic int g_sum = 0;\nstatic void Accumulate(int n) { g_sum += n; }\n\nTEST(ContainerUtilityTest, ForEach) {\n  std::vector<int> v;\n  g_sum = 0;\n  ForEach(v, Accumulate);\n  EXPECT_EQ(0, g_sum);  // Works for an empty container;\n\n  g_sum = 0;\n  v.push_back(1);\n  ForEach(v, Accumulate);\n  EXPECT_EQ(1, g_sum);  // Works for a container with one element.\n\n  g_sum = 0;\n  v.push_back(20);\n  v.push_back(300);\n  ForEach(v, Accumulate);\n  EXPECT_EQ(321, g_sum);\n}\n\n// Tests GetElementOr().\nTEST(ContainerUtilityTest, GetElementOr) {\n  std::vector<char> a;\n  EXPECT_EQ('x', GetElementOr(a, 0, 'x'));\n\n  a.push_back('a');\n  a.push_back('b');\n  EXPECT_EQ('a', GetElementOr(a, 0, 'x'));\n  EXPECT_EQ('b', GetElementOr(a, 1, 'x'));\n  EXPECT_EQ('x', GetElementOr(a, -2, 'x'));\n  EXPECT_EQ('x', GetElementOr(a, 2, 'x'));\n}\n\nTEST(ContainerUtilityDeathTest, ShuffleRange) {\n  std::vector<int> a;\n  a.push_back(0);\n  a.push_back(1);\n  a.push_back(2);\n  testing::internal::Random random(1);\n\n  EXPECT_DEATH_IF_SUPPORTED(\n      ShuffleRange(&random, -1, 1, &a),\n      \"Invalid shuffle range start -1: must be in range \\\\[0, 3\\\\]\");\n  EXPECT_DEATH_IF_SUPPORTED(\n      ShuffleRange(&random, 4, 4, &a),\n      \"Invalid shuffle range start 4: must be in range \\\\[0, 3\\\\]\");\n  EXPECT_DEATH_IF_SUPPORTED(\n      ShuffleRange(&random, 3, 2, &a),\n      \"Invalid shuffle range finish 2: must be in range \\\\[3, 3\\\\]\");\n  EXPECT_DEATH_IF_SUPPORTED(\n      ShuffleRange(&random, 3, 4, &a),\n      \"Invalid shuffle range finish 4: must be in range \\\\[3, 3\\\\]\");\n}\n\nclass VectorShuffleTest : public Test {\n protected:\n  static const size_t kVectorSize = 20;\n\n  VectorShuffleTest() : random_(1) {\n    for (int i = 0; i < static_cast<int>(kVectorSize); i++) {\n      vector_.push_back(i);\n    }\n  }\n\n  static bool VectorIsCorrupt(const TestingVector& vector) {\n    if (kVectorSize != vector.size()) {\n      return true;\n    }\n\n    bool found_in_vector[kVectorSize] = {false};\n    for (size_t i = 0; i < vector.size(); i++) {\n      const int e = vector[i];\n      if (e < 0 || e >= static_cast<int>(kVectorSize) || found_in_vector[e]) {\n        return true;\n      }\n      found_in_vector[e] = true;\n    }\n\n    // Vector size is correct, elements' range is correct, no\n    // duplicate elements.  Therefore no corruption has occurred.\n    return false;\n  }\n\n  static bool VectorIsNotCorrupt(const TestingVector& vector) {\n    return !VectorIsCorrupt(vector);\n  }\n\n  static bool RangeIsShuffled(const TestingVector& vector, int begin, int end) {\n    for (int i = begin; i < end; i++) {\n      if (i != vector[static_cast<size_t>(i)]) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  static bool RangeIsUnshuffled(const TestingVector& vector, int begin,\n                                int end) {\n    return !RangeIsShuffled(vector, begin, end);\n  }\n\n  static bool VectorIsShuffled(const TestingVector& vector) {\n    return RangeIsShuffled(vector, 0, static_cast<int>(vector.size()));\n  }\n\n  static bool VectorIsUnshuffled(const TestingVector& vector) {\n    return !VectorIsShuffled(vector);\n  }\n\n  testing::internal::Random random_;\n  TestingVector vector_;\n};  // class VectorShuffleTest\n\nconst size_t VectorShuffleTest::kVectorSize;\n\nTEST_F(VectorShuffleTest, HandlesEmptyRange) {\n  // Tests an empty range at the beginning...\n  ShuffleRange(&random_, 0, 0, &vector_);\n  ASSERT_PRED1(VectorIsNotCorrupt, vector_);\n  ASSERT_PRED1(VectorIsUnshuffled, vector_);\n\n  // ...in the middle...\n  ShuffleRange(&random_, kVectorSize / 2, kVectorSize / 2, &vector_);\n  ASSERT_PRED1(VectorIsNotCorrupt, vector_);\n  ASSERT_PRED1(VectorIsUnshuffled, vector_);\n\n  // ...at the end...\n  ShuffleRange(&random_, kVectorSize - 1, kVectorSize - 1, &vector_);\n  ASSERT_PRED1(VectorIsNotCorrupt, vector_);\n  ASSERT_PRED1(VectorIsUnshuffled, vector_);\n\n  // ...and past the end.\n  ShuffleRange(&random_, kVectorSize, kVectorSize, &vector_);\n  ASSERT_PRED1(VectorIsNotCorrupt, vector_);\n  ASSERT_PRED1(VectorIsUnshuffled, vector_);\n}\n\nTEST_F(VectorShuffleTest, HandlesRangeOfSizeOne) {\n  // Tests a size one range at the beginning...\n  ShuffleRange(&random_, 0, 1, &vector_);\n  ASSERT_PRED1(VectorIsNotCorrupt, vector_);\n  ASSERT_PRED1(VectorIsUnshuffled, vector_);\n\n  // ...in the middle...\n  ShuffleRange(&random_, kVectorSize / 2, kVectorSize / 2 + 1, &vector_);\n  ASSERT_PRED1(VectorIsNotCorrupt, vector_);\n  ASSERT_PRED1(VectorIsUnshuffled, vector_);\n\n  // ...and at the end.\n  ShuffleRange(&random_, kVectorSize - 1, kVectorSize, &vector_);\n  ASSERT_PRED1(VectorIsNotCorrupt, vector_);\n  ASSERT_PRED1(VectorIsUnshuffled, vector_);\n}\n\n// Because we use our own random number generator and a fixed seed,\n// we can guarantee that the following \"random\" tests will succeed.\n\nTEST_F(VectorShuffleTest, ShufflesEntireVector) {\n  Shuffle(&random_, &vector_);\n  ASSERT_PRED1(VectorIsNotCorrupt, vector_);\n  EXPECT_FALSE(VectorIsUnshuffled(vector_)) << vector_;\n\n  // Tests the first and last elements in particular to ensure that\n  // there are no off-by-one problems in our shuffle algorithm.\n  EXPECT_NE(0, vector_[0]);\n  EXPECT_NE(static_cast<int>(kVectorSize - 1), vector_[kVectorSize - 1]);\n}\n\nTEST_F(VectorShuffleTest, ShufflesStartOfVector) {\n  const int kRangeSize = kVectorSize / 2;\n\n  ShuffleRange(&random_, 0, kRangeSize, &vector_);\n\n  ASSERT_PRED1(VectorIsNotCorrupt, vector_);\n  EXPECT_PRED3(RangeIsShuffled, vector_, 0, kRangeSize);\n  EXPECT_PRED3(RangeIsUnshuffled, vector_, kRangeSize,\n               static_cast<int>(kVectorSize));\n}\n\nTEST_F(VectorShuffleTest, ShufflesEndOfVector) {\n  const int kRangeSize = kVectorSize / 2;\n  ShuffleRange(&random_, kRangeSize, kVectorSize, &vector_);\n\n  ASSERT_PRED1(VectorIsNotCorrupt, vector_);\n  EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);\n  EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize,\n               static_cast<int>(kVectorSize));\n}\n\nTEST_F(VectorShuffleTest, ShufflesMiddleOfVector) {\n  const int kRangeSize = static_cast<int>(kVectorSize) / 3;\n  ShuffleRange(&random_, kRangeSize, 2 * kRangeSize, &vector_);\n\n  ASSERT_PRED1(VectorIsNotCorrupt, vector_);\n  EXPECT_PRED3(RangeIsUnshuffled, vector_, 0, kRangeSize);\n  EXPECT_PRED3(RangeIsShuffled, vector_, kRangeSize, 2 * kRangeSize);\n  EXPECT_PRED3(RangeIsUnshuffled, vector_, 2 * kRangeSize,\n               static_cast<int>(kVectorSize));\n}\n\nTEST_F(VectorShuffleTest, ShufflesRepeatably) {\n  TestingVector vector2;\n  for (size_t i = 0; i < kVectorSize; i++) {\n    vector2.push_back(static_cast<int>(i));\n  }\n\n  random_.Reseed(1234);\n  Shuffle(&random_, &vector_);\n  random_.Reseed(1234);\n  Shuffle(&random_, &vector2);\n\n  ASSERT_PRED1(VectorIsNotCorrupt, vector_);\n  ASSERT_PRED1(VectorIsNotCorrupt, vector2);\n\n  for (size_t i = 0; i < kVectorSize; i++) {\n    EXPECT_EQ(vector_[i], vector2[i]) << \" where i is \" << i;\n  }\n}\n\n// Tests the size of the AssertHelper class.\n\nTEST(AssertHelperTest, AssertHelperIsSmall) {\n  // To avoid breaking clients that use lots of assertions in one\n  // function, we cannot grow the size of AssertHelper.\n  EXPECT_LE(sizeof(testing::internal::AssertHelper), sizeof(void*));\n}\n\n// Tests String::EndsWithCaseInsensitive().\nTEST(StringTest, EndsWithCaseInsensitive) {\n  EXPECT_TRUE(String::EndsWithCaseInsensitive(\"foobar\", \"BAR\"));\n  EXPECT_TRUE(String::EndsWithCaseInsensitive(\"foobaR\", \"bar\"));\n  EXPECT_TRUE(String::EndsWithCaseInsensitive(\"foobar\", \"\"));\n  EXPECT_TRUE(String::EndsWithCaseInsensitive(\"\", \"\"));\n\n  EXPECT_FALSE(String::EndsWithCaseInsensitive(\"Foobar\", \"foo\"));\n  EXPECT_FALSE(String::EndsWithCaseInsensitive(\"foobar\", \"Foo\"));\n  EXPECT_FALSE(String::EndsWithCaseInsensitive(\"\", \"foo\"));\n}\n\n// C++Builder's preprocessor is buggy; it fails to expand macros that\n// appear in macro parameters after wide char literals.  Provide an alias\n// for NULL as a workaround.\nstatic const wchar_t* const kNull = nullptr;\n\n// Tests String::CaseInsensitiveWideCStringEquals\nTEST(StringTest, CaseInsensitiveWideCStringEquals) {\n  EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(nullptr, nullptr));\n  EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L\"\"));\n  EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L\"\", kNull));\n  EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(kNull, L\"foobar\"));\n  EXPECT_FALSE(String::CaseInsensitiveWideCStringEquals(L\"foobar\", kNull));\n  EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L\"foobar\", L\"foobar\"));\n  EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L\"foobar\", L\"FOOBAR\"));\n  EXPECT_TRUE(String::CaseInsensitiveWideCStringEquals(L\"FOOBAR\", L\"foobar\"));\n}\n\n#if GTEST_OS_WINDOWS\n\n// Tests String::ShowWideCString().\nTEST(StringTest, ShowWideCString) {\n  EXPECT_STREQ(\"(null)\", String::ShowWideCString(NULL).c_str());\n  EXPECT_STREQ(\"\", String::ShowWideCString(L\"\").c_str());\n  EXPECT_STREQ(\"foo\", String::ShowWideCString(L\"foo\").c_str());\n}\n\n#if GTEST_OS_WINDOWS_MOBILE\nTEST(StringTest, AnsiAndUtf16Null) {\n  EXPECT_EQ(NULL, String::AnsiToUtf16(NULL));\n  EXPECT_EQ(NULL, String::Utf16ToAnsi(NULL));\n}\n\nTEST(StringTest, AnsiAndUtf16ConvertBasic) {\n  const char* ansi = String::Utf16ToAnsi(L\"str\");\n  EXPECT_STREQ(\"str\", ansi);\n  delete[] ansi;\n  const WCHAR* utf16 = String::AnsiToUtf16(\"str\");\n  EXPECT_EQ(0, wcsncmp(L\"str\", utf16, 3));\n  delete[] utf16;\n}\n\nTEST(StringTest, AnsiAndUtf16ConvertPathChars) {\n  const char* ansi = String::Utf16ToAnsi(L\".:\\\\ \\\"*?\");\n  EXPECT_STREQ(\".:\\\\ \\\"*?\", ansi);\n  delete[] ansi;\n  const WCHAR* utf16 = String::AnsiToUtf16(\".:\\\\ \\\"*?\");\n  EXPECT_EQ(0, wcsncmp(L\".:\\\\ \\\"*?\", utf16, 3));\n  delete[] utf16;\n}\n#endif  // GTEST_OS_WINDOWS_MOBILE\n\n#endif  // GTEST_OS_WINDOWS\n\n// Tests TestProperty construction.\nTEST(TestPropertyTest, StringValue) {\n  TestProperty property(\"key\", \"1\");\n  EXPECT_STREQ(\"key\", property.key());\n  EXPECT_STREQ(\"1\", property.value());\n}\n\n// Tests TestProperty replacing a value.\nTEST(TestPropertyTest, ReplaceStringValue) {\n  TestProperty property(\"key\", \"1\");\n  EXPECT_STREQ(\"1\", property.value());\n  property.SetValue(\"2\");\n  EXPECT_STREQ(\"2\", property.value());\n}\n\n// AddFatalFailure() and AddNonfatalFailure() must be stand-alone\n// functions (i.e. their definitions cannot be inlined at the call\n// sites), or C++Builder won't compile the code.\nstatic void AddFatalFailure() { FAIL() << \"Expected fatal failure.\"; }\n\nstatic void AddNonfatalFailure() {\n  ADD_FAILURE() << \"Expected non-fatal failure.\";\n}\n\nclass ScopedFakeTestPartResultReporterTest : public Test {\n public:  // Must be public and not protected due to a bug in g++ 3.4.2.\n  enum FailureMode { FATAL_FAILURE, NONFATAL_FAILURE };\n  static void AddFailure(FailureMode failure) {\n    if (failure == FATAL_FAILURE) {\n      AddFatalFailure();\n    } else {\n      AddNonfatalFailure();\n    }\n  }\n};\n\n// Tests that ScopedFakeTestPartResultReporter intercepts test\n// failures.\nTEST_F(ScopedFakeTestPartResultReporterTest, InterceptsTestFailures) {\n  TestPartResultArray results;\n  {\n    ScopedFakeTestPartResultReporter reporter(\n        ScopedFakeTestPartResultReporter::INTERCEPT_ONLY_CURRENT_THREAD,\n        &results);\n    AddFailure(NONFATAL_FAILURE);\n    AddFailure(FATAL_FAILURE);\n  }\n\n  EXPECT_EQ(2, results.size());\n  EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());\n  EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());\n}\n\nTEST_F(ScopedFakeTestPartResultReporterTest, DeprecatedConstructor) {\n  TestPartResultArray results;\n  {\n    // Tests, that the deprecated constructor still works.\n    ScopedFakeTestPartResultReporter reporter(&results);\n    AddFailure(NONFATAL_FAILURE);\n  }\n  EXPECT_EQ(1, results.size());\n}\n\n#if GTEST_IS_THREADSAFE\n\nclass ScopedFakeTestPartResultReporterWithThreadsTest\n    : public ScopedFakeTestPartResultReporterTest {\n protected:\n  static void AddFailureInOtherThread(FailureMode failure) {\n    ThreadWithParam<FailureMode> thread(&AddFailure, failure, nullptr);\n    thread.Join();\n  }\n};\n\nTEST_F(ScopedFakeTestPartResultReporterWithThreadsTest,\n       InterceptsTestFailuresInAllThreads) {\n  TestPartResultArray results;\n  {\n    ScopedFakeTestPartResultReporter reporter(\n        ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, &results);\n    AddFailure(NONFATAL_FAILURE);\n    AddFailure(FATAL_FAILURE);\n    AddFailureInOtherThread(NONFATAL_FAILURE);\n    AddFailureInOtherThread(FATAL_FAILURE);\n  }\n\n  EXPECT_EQ(4, results.size());\n  EXPECT_TRUE(results.GetTestPartResult(0).nonfatally_failed());\n  EXPECT_TRUE(results.GetTestPartResult(1).fatally_failed());\n  EXPECT_TRUE(results.GetTestPartResult(2).nonfatally_failed());\n  EXPECT_TRUE(results.GetTestPartResult(3).fatally_failed());\n}\n\n#endif  // GTEST_IS_THREADSAFE\n\n// Tests EXPECT_FATAL_FAILURE{,ON_ALL_THREADS}.  Makes sure that they\n// work even if the failure is generated in a called function rather than\n// the current context.\n\ntypedef ScopedFakeTestPartResultReporterTest ExpectFatalFailureTest;\n\nTEST_F(ExpectFatalFailureTest, CatchesFatalFaliure) {\n  EXPECT_FATAL_FAILURE(AddFatalFailure(), \"Expected fatal failure.\");\n}\n\nTEST_F(ExpectFatalFailureTest, AcceptsStdStringObject) {\n  EXPECT_FATAL_FAILURE(AddFatalFailure(),\n                       ::std::string(\"Expected fatal failure.\"));\n}\n\nTEST_F(ExpectFatalFailureTest, CatchesFatalFailureOnAllThreads) {\n  // We have another test below to verify that the macro catches fatal\n  // failures generated on another thread.\n  EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFatalFailure(),\n                                      \"Expected fatal failure.\");\n}\n\n#ifdef __BORLANDC__\n// Silences warnings: \"Condition is always true\"\n#pragma option push -w-ccc\n#endif\n\n// Tests that EXPECT_FATAL_FAILURE() can be used in a non-void\n// function even when the statement in it contains ASSERT_*.\n\nint NonVoidFunction() {\n  EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), \"\");\n  EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), \"\");\n  return 0;\n}\n\nTEST_F(ExpectFatalFailureTest, CanBeUsedInNonVoidFunction) {\n  NonVoidFunction();\n}\n\n// Tests that EXPECT_FATAL_FAILURE(statement, ...) doesn't abort the\n// current function even though 'statement' generates a fatal failure.\n\nvoid DoesNotAbortHelper(bool* aborted) {\n  EXPECT_FATAL_FAILURE(ASSERT_TRUE(false), \"\");\n  EXPECT_FATAL_FAILURE_ON_ALL_THREADS(FAIL(), \"\");\n\n  *aborted = false;\n}\n\n#ifdef __BORLANDC__\n// Restores warnings after previous \"#pragma option push\" suppressed them.\n#pragma option pop\n#endif\n\nTEST_F(ExpectFatalFailureTest, DoesNotAbort) {\n  bool aborted = true;\n  DoesNotAbortHelper(&aborted);\n  EXPECT_FALSE(aborted);\n}\n\n// Tests that the EXPECT_FATAL_FAILURE{,_ON_ALL_THREADS} accepts a\n// statement that contains a macro which expands to code containing an\n// unprotected comma.\n\nstatic int global_var = 0;\n#define GTEST_USE_UNPROTECTED_COMMA_ global_var++, global_var++\n\nTEST_F(ExpectFatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {\n#ifndef __BORLANDC__\n  // ICE's in C++Builder.\n  EXPECT_FATAL_FAILURE(\n      {\n        GTEST_USE_UNPROTECTED_COMMA_;\n        AddFatalFailure();\n      },\n      \"\");\n#endif\n\n  EXPECT_FATAL_FAILURE_ON_ALL_THREADS(\n      {\n        GTEST_USE_UNPROTECTED_COMMA_;\n        AddFatalFailure();\n      },\n      \"\");\n}\n\n// Tests EXPECT_NONFATAL_FAILURE{,ON_ALL_THREADS}.\n\ntypedef ScopedFakeTestPartResultReporterTest ExpectNonfatalFailureTest;\n\nTEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailure) {\n  EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(), \"Expected non-fatal failure.\");\n}\n\nTEST_F(ExpectNonfatalFailureTest, AcceptsStdStringObject) {\n  EXPECT_NONFATAL_FAILURE(AddNonfatalFailure(),\n                          ::std::string(\"Expected non-fatal failure.\"));\n}\n\nTEST_F(ExpectNonfatalFailureTest, CatchesNonfatalFailureOnAllThreads) {\n  // We have another test below to verify that the macro catches\n  // non-fatal failures generated on another thread.\n  EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(AddNonfatalFailure(),\n                                         \"Expected non-fatal failure.\");\n}\n\n// Tests that the EXPECT_NONFATAL_FAILURE{,_ON_ALL_THREADS} accepts a\n// statement that contains a macro which expands to code containing an\n// unprotected comma.\nTEST_F(ExpectNonfatalFailureTest, AcceptsMacroThatExpandsToUnprotectedComma) {\n  EXPECT_NONFATAL_FAILURE(\n      {\n        GTEST_USE_UNPROTECTED_COMMA_;\n        AddNonfatalFailure();\n      },\n      \"\");\n\n  EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(\n      {\n        GTEST_USE_UNPROTECTED_COMMA_;\n        AddNonfatalFailure();\n      },\n      \"\");\n}\n\n#if GTEST_IS_THREADSAFE\n\ntypedef ScopedFakeTestPartResultReporterWithThreadsTest\n    ExpectFailureWithThreadsTest;\n\nTEST_F(ExpectFailureWithThreadsTest, ExpectFatalFailureOnAllThreads) {\n  EXPECT_FATAL_FAILURE_ON_ALL_THREADS(AddFailureInOtherThread(FATAL_FAILURE),\n                                      \"Expected fatal failure.\");\n}\n\nTEST_F(ExpectFailureWithThreadsTest, ExpectNonFatalFailureOnAllThreads) {\n  EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(\n      AddFailureInOtherThread(NONFATAL_FAILURE), \"Expected non-fatal failure.\");\n}\n\n#endif  // GTEST_IS_THREADSAFE\n\n// Tests the TestProperty class.\n\nTEST(TestPropertyTest, ConstructorWorks) {\n  const TestProperty property(\"key\", \"value\");\n  EXPECT_STREQ(\"key\", property.key());\n  EXPECT_STREQ(\"value\", property.value());\n}\n\nTEST(TestPropertyTest, SetValue) {\n  TestProperty property(\"key\", \"value_1\");\n  EXPECT_STREQ(\"key\", property.key());\n  property.SetValue(\"value_2\");\n  EXPECT_STREQ(\"key\", property.key());\n  EXPECT_STREQ(\"value_2\", property.value());\n}\n\n// Tests the TestResult class\n\n// The test fixture for testing TestResult.\nclass TestResultTest : public Test {\n protected:\n  typedef std::vector<TestPartResult> TPRVector;\n\n  // We make use of 2 TestPartResult objects,\n  TestPartResult *pr1, *pr2;\n\n  // ... and 3 TestResult objects.\n  TestResult *r0, *r1, *r2;\n\n  void SetUp() override {\n    // pr1 is for success.\n    pr1 = new TestPartResult(TestPartResult::kSuccess, \"foo/bar.cc\", 10,\n                             \"Success!\");\n\n    // pr2 is for fatal failure.\n    pr2 = new TestPartResult(TestPartResult::kFatalFailure, \"foo/bar.cc\",\n                             -1,  // This line number means \"unknown\"\n                             \"Failure!\");\n\n    // Creates the TestResult objects.\n    r0 = new TestResult();\n    r1 = new TestResult();\n    r2 = new TestResult();\n\n    // In order to test TestResult, we need to modify its internal\n    // state, in particular the TestPartResult vector it holds.\n    // test_part_results() returns a const reference to this vector.\n    // We cast it to a non-const object s.t. it can be modified\n    TPRVector* results1 =\n        const_cast<TPRVector*>(&TestResultAccessor::test_part_results(*r1));\n    TPRVector* results2 =\n        const_cast<TPRVector*>(&TestResultAccessor::test_part_results(*r2));\n\n    // r0 is an empty TestResult.\n\n    // r1 contains a single SUCCESS TestPartResult.\n    results1->push_back(*pr1);\n\n    // r2 contains a SUCCESS, and a FAILURE.\n    results2->push_back(*pr1);\n    results2->push_back(*pr2);\n  }\n\n  void TearDown() override {\n    delete pr1;\n    delete pr2;\n\n    delete r0;\n    delete r1;\n    delete r2;\n  }\n\n  // Helper that compares two TestPartResults.\n  static void CompareTestPartResult(const TestPartResult& expected,\n                                    const TestPartResult& actual) {\n    EXPECT_EQ(expected.type(), actual.type());\n    EXPECT_STREQ(expected.file_name(), actual.file_name());\n    EXPECT_EQ(expected.line_number(), actual.line_number());\n    EXPECT_STREQ(expected.summary(), actual.summary());\n    EXPECT_STREQ(expected.message(), actual.message());\n    EXPECT_EQ(expected.passed(), actual.passed());\n    EXPECT_EQ(expected.failed(), actual.failed());\n    EXPECT_EQ(expected.nonfatally_failed(), actual.nonfatally_failed());\n    EXPECT_EQ(expected.fatally_failed(), actual.fatally_failed());\n  }\n};\n\n// Tests TestResult::total_part_count().\nTEST_F(TestResultTest, total_part_count) {\n  ASSERT_EQ(0, r0->total_part_count());\n  ASSERT_EQ(1, r1->total_part_count());\n  ASSERT_EQ(2, r2->total_part_count());\n}\n\n// Tests TestResult::Passed().\nTEST_F(TestResultTest, Passed) {\n  ASSERT_TRUE(r0->Passed());\n  ASSERT_TRUE(r1->Passed());\n  ASSERT_FALSE(r2->Passed());\n}\n\n// Tests TestResult::Failed().\nTEST_F(TestResultTest, Failed) {\n  ASSERT_FALSE(r0->Failed());\n  ASSERT_FALSE(r1->Failed());\n  ASSERT_TRUE(r2->Failed());\n}\n\n// Tests TestResult::GetTestPartResult().\n\ntypedef TestResultTest TestResultDeathTest;\n\nTEST_F(TestResultDeathTest, GetTestPartResult) {\n  CompareTestPartResult(*pr1, r2->GetTestPartResult(0));\n  CompareTestPartResult(*pr2, r2->GetTestPartResult(1));\n  EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(2), \"\");\n  EXPECT_DEATH_IF_SUPPORTED(r2->GetTestPartResult(-1), \"\");\n}\n\n// Tests TestResult has no properties when none are added.\nTEST(TestResultPropertyTest, NoPropertiesFoundWhenNoneAreAdded) {\n  TestResult test_result;\n  ASSERT_EQ(0, test_result.test_property_count());\n}\n\n// Tests TestResult has the expected property when added.\nTEST(TestResultPropertyTest, OnePropertyFoundWhenAdded) {\n  TestResult test_result;\n  TestProperty property(\"key_1\", \"1\");\n  TestResultAccessor::RecordProperty(&test_result, \"testcase\", property);\n  ASSERT_EQ(1, test_result.test_property_count());\n  const TestProperty& actual_property = test_result.GetTestProperty(0);\n  EXPECT_STREQ(\"key_1\", actual_property.key());\n  EXPECT_STREQ(\"1\", actual_property.value());\n}\n\n// Tests TestResult has multiple properties when added.\nTEST(TestResultPropertyTest, MultiplePropertiesFoundWhenAdded) {\n  TestResult test_result;\n  TestProperty property_1(\"key_1\", \"1\");\n  TestProperty property_2(\"key_2\", \"2\");\n  TestResultAccessor::RecordProperty(&test_result, \"testcase\", property_1);\n  TestResultAccessor::RecordProperty(&test_result, \"testcase\", property_2);\n  ASSERT_EQ(2, test_result.test_property_count());\n  const TestProperty& actual_property_1 = test_result.GetTestProperty(0);\n  EXPECT_STREQ(\"key_1\", actual_property_1.key());\n  EXPECT_STREQ(\"1\", actual_property_1.value());\n\n  const TestProperty& actual_property_2 = test_result.GetTestProperty(1);\n  EXPECT_STREQ(\"key_2\", actual_property_2.key());\n  EXPECT_STREQ(\"2\", actual_property_2.value());\n}\n\n// Tests TestResult::RecordProperty() overrides values for duplicate keys.\nTEST(TestResultPropertyTest, OverridesValuesForDuplicateKeys) {\n  TestResult test_result;\n  TestProperty property_1_1(\"key_1\", \"1\");\n  TestProperty property_2_1(\"key_2\", \"2\");\n  TestProperty property_1_2(\"key_1\", \"12\");\n  TestProperty property_2_2(\"key_2\", \"22\");\n  TestResultAccessor::RecordProperty(&test_result, \"testcase\", property_1_1);\n  TestResultAccessor::RecordProperty(&test_result, \"testcase\", property_2_1);\n  TestResultAccessor::RecordProperty(&test_result, \"testcase\", property_1_2);\n  TestResultAccessor::RecordProperty(&test_result, \"testcase\", property_2_2);\n\n  ASSERT_EQ(2, test_result.test_property_count());\n  const TestProperty& actual_property_1 = test_result.GetTestProperty(0);\n  EXPECT_STREQ(\"key_1\", actual_property_1.key());\n  EXPECT_STREQ(\"12\", actual_property_1.value());\n\n  const TestProperty& actual_property_2 = test_result.GetTestProperty(1);\n  EXPECT_STREQ(\"key_2\", actual_property_2.key());\n  EXPECT_STREQ(\"22\", actual_property_2.value());\n}\n\n// Tests TestResult::GetTestProperty().\nTEST(TestResultPropertyTest, GetTestProperty) {\n  TestResult test_result;\n  TestProperty property_1(\"key_1\", \"1\");\n  TestProperty property_2(\"key_2\", \"2\");\n  TestProperty property_3(\"key_3\", \"3\");\n  TestResultAccessor::RecordProperty(&test_result, \"testcase\", property_1);\n  TestResultAccessor::RecordProperty(&test_result, \"testcase\", property_2);\n  TestResultAccessor::RecordProperty(&test_result, \"testcase\", property_3);\n\n  const TestProperty& fetched_property_1 = test_result.GetTestProperty(0);\n  const TestProperty& fetched_property_2 = test_result.GetTestProperty(1);\n  const TestProperty& fetched_property_3 = test_result.GetTestProperty(2);\n\n  EXPECT_STREQ(\"key_1\", fetched_property_1.key());\n  EXPECT_STREQ(\"1\", fetched_property_1.value());\n\n  EXPECT_STREQ(\"key_2\", fetched_property_2.key());\n  EXPECT_STREQ(\"2\", fetched_property_2.value());\n\n  EXPECT_STREQ(\"key_3\", fetched_property_3.key());\n  EXPECT_STREQ(\"3\", fetched_property_3.value());\n\n  EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(3), \"\");\n  EXPECT_DEATH_IF_SUPPORTED(test_result.GetTestProperty(-1), \"\");\n}\n\n// Tests the Test class.\n//\n// It's difficult to test every public method of this class (we are\n// already stretching the limit of Google Test by using it to test itself!).\n// Fortunately, we don't have to do that, as we are already testing\n// the functionalities of the Test class extensively by using Google Test\n// alone.\n//\n// Therefore, this section only contains one test.\n\n// Tests that GTestFlagSaver works on Windows and Mac.\n\nclass GTestFlagSaverTest : public Test {\n protected:\n  // Saves the Google Test flags such that we can restore them later, and\n  // then sets them to their default values.  This will be called\n  // before the first test in this test case is run.\n  static void SetUpTestSuite() {\n    saver_ = new GTestFlagSaver;\n\n    GTEST_FLAG_SET(also_run_disabled_tests, false);\n    GTEST_FLAG_SET(break_on_failure, false);\n    GTEST_FLAG_SET(catch_exceptions, false);\n    GTEST_FLAG_SET(death_test_use_fork, false);\n    GTEST_FLAG_SET(color, \"auto\");\n    GTEST_FLAG_SET(fail_fast, false);\n    GTEST_FLAG_SET(filter, \"\");\n    GTEST_FLAG_SET(list_tests, false);\n    GTEST_FLAG_SET(output, \"\");\n    GTEST_FLAG_SET(brief, false);\n    GTEST_FLAG_SET(print_time, true);\n    GTEST_FLAG_SET(random_seed, 0);\n    GTEST_FLAG_SET(repeat, 1);\n    GTEST_FLAG_SET(recreate_environments_when_repeating, true);\n    GTEST_FLAG_SET(shuffle, false);\n    GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth);\n    GTEST_FLAG_SET(stream_result_to, \"\");\n    GTEST_FLAG_SET(throw_on_failure, false);\n  }\n\n  // Restores the Google Test flags that the tests have modified.  This will\n  // be called after the last test in this test case is run.\n  static void TearDownTestSuite() {\n    delete saver_;\n    saver_ = nullptr;\n  }\n\n  // Verifies that the Google Test flags have their default values, and then\n  // modifies each of them.\n  void VerifyAndModifyFlags() {\n    EXPECT_FALSE(GTEST_FLAG_GET(also_run_disabled_tests));\n    EXPECT_FALSE(GTEST_FLAG_GET(break_on_failure));\n    EXPECT_FALSE(GTEST_FLAG_GET(catch_exceptions));\n    EXPECT_STREQ(\"auto\", GTEST_FLAG_GET(color).c_str());\n    EXPECT_FALSE(GTEST_FLAG_GET(death_test_use_fork));\n    EXPECT_FALSE(GTEST_FLAG_GET(fail_fast));\n    EXPECT_STREQ(\"\", GTEST_FLAG_GET(filter).c_str());\n    EXPECT_FALSE(GTEST_FLAG_GET(list_tests));\n    EXPECT_STREQ(\"\", GTEST_FLAG_GET(output).c_str());\n    EXPECT_FALSE(GTEST_FLAG_GET(brief));\n    EXPECT_TRUE(GTEST_FLAG_GET(print_time));\n    EXPECT_EQ(0, GTEST_FLAG_GET(random_seed));\n    EXPECT_EQ(1, GTEST_FLAG_GET(repeat));\n    EXPECT_TRUE(GTEST_FLAG_GET(recreate_environments_when_repeating));\n    EXPECT_FALSE(GTEST_FLAG_GET(shuffle));\n    EXPECT_EQ(kMaxStackTraceDepth, GTEST_FLAG_GET(stack_trace_depth));\n    EXPECT_STREQ(\"\", GTEST_FLAG_GET(stream_result_to).c_str());\n    EXPECT_FALSE(GTEST_FLAG_GET(throw_on_failure));\n\n    GTEST_FLAG_SET(also_run_disabled_tests, true);\n    GTEST_FLAG_SET(break_on_failure, true);\n    GTEST_FLAG_SET(catch_exceptions, true);\n    GTEST_FLAG_SET(color, \"no\");\n    GTEST_FLAG_SET(death_test_use_fork, true);\n    GTEST_FLAG_SET(fail_fast, true);\n    GTEST_FLAG_SET(filter, \"abc\");\n    GTEST_FLAG_SET(list_tests, true);\n    GTEST_FLAG_SET(output, \"xml:foo.xml\");\n    GTEST_FLAG_SET(brief, true);\n    GTEST_FLAG_SET(print_time, false);\n    GTEST_FLAG_SET(random_seed, 1);\n    GTEST_FLAG_SET(repeat, 100);\n    GTEST_FLAG_SET(recreate_environments_when_repeating, false);\n    GTEST_FLAG_SET(shuffle, true);\n    GTEST_FLAG_SET(stack_trace_depth, 1);\n    GTEST_FLAG_SET(stream_result_to, \"localhost:1234\");\n    GTEST_FLAG_SET(throw_on_failure, true);\n  }\n\n private:\n  // For saving Google Test flags during this test case.\n  static GTestFlagSaver* saver_;\n};\n\nGTestFlagSaver* GTestFlagSaverTest::saver_ = nullptr;\n\n// Google Test doesn't guarantee the order of tests.  The following two\n// tests are designed to work regardless of their order.\n\n// Modifies the Google Test flags in the test body.\nTEST_F(GTestFlagSaverTest, ModifyGTestFlags) { VerifyAndModifyFlags(); }\n\n// Verifies that the Google Test flags in the body of the previous test were\n// restored to their original values.\nTEST_F(GTestFlagSaverTest, VerifyGTestFlags) { VerifyAndModifyFlags(); }\n\n// Sets an environment variable with the given name to the given\n// value.  If the value argument is \"\", unsets the environment\n// variable.  The caller must ensure that both arguments are not NULL.\nstatic void SetEnv(const char* name, const char* value) {\n#if GTEST_OS_WINDOWS_MOBILE\n  // Environment variables are not supported on Windows CE.\n  return;\n#elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9)\n  // C++Builder's putenv only stores a pointer to its parameter; we have to\n  // ensure that the string remains valid as long as it might be needed.\n  // We use an std::map to do so.\n  static std::map<std::string, std::string*> added_env;\n\n  // Because putenv stores a pointer to the string buffer, we can't delete the\n  // previous string (if present) until after it's replaced.\n  std::string* prev_env = NULL;\n  if (added_env.find(name) != added_env.end()) {\n    prev_env = added_env[name];\n  }\n  added_env[name] =\n      new std::string((Message() << name << \"=\" << value).GetString());\n\n  // The standard signature of putenv accepts a 'char*' argument. Other\n  // implementations, like C++Builder's, accept a 'const char*'.\n  // We cast away the 'const' since that would work for both variants.\n  putenv(const_cast<char*>(added_env[name]->c_str()));\n  delete prev_env;\n#elif GTEST_OS_WINDOWS  // If we are on Windows proper.\n  _putenv((Message() << name << \"=\" << value).GetString().c_str());\n#else\n  if (*value == '\\0') {\n    unsetenv(name);\n  } else {\n    setenv(name, value, 1);\n  }\n#endif  // GTEST_OS_WINDOWS_MOBILE\n}\n\n#if !GTEST_OS_WINDOWS_MOBILE\n// Environment variables are not supported on Windows CE.\n\nusing testing::internal::Int32FromGTestEnv;\n\n// Tests Int32FromGTestEnv().\n\n// Tests that Int32FromGTestEnv() returns the default value when the\n// environment variable is not set.\nTEST(Int32FromGTestEnvTest, ReturnsDefaultWhenVariableIsNotSet) {\n  SetEnv(GTEST_FLAG_PREFIX_UPPER_ \"TEMP\", \"\");\n  EXPECT_EQ(10, Int32FromGTestEnv(\"temp\", 10));\n}\n\n#if !defined(GTEST_GET_INT32_FROM_ENV_)\n\n// Tests that Int32FromGTestEnv() returns the default value when the\n// environment variable overflows as an Int32.\nTEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueOverflows) {\n  printf(\"(expecting 2 warnings)\\n\");\n\n  SetEnv(GTEST_FLAG_PREFIX_UPPER_ \"TEMP\", \"12345678987654321\");\n  EXPECT_EQ(20, Int32FromGTestEnv(\"temp\", 20));\n\n  SetEnv(GTEST_FLAG_PREFIX_UPPER_ \"TEMP\", \"-12345678987654321\");\n  EXPECT_EQ(30, Int32FromGTestEnv(\"temp\", 30));\n}\n\n// Tests that Int32FromGTestEnv() returns the default value when the\n// environment variable does not represent a valid decimal integer.\nTEST(Int32FromGTestEnvTest, ReturnsDefaultWhenValueIsInvalid) {\n  printf(\"(expecting 2 warnings)\\n\");\n\n  SetEnv(GTEST_FLAG_PREFIX_UPPER_ \"TEMP\", \"A1\");\n  EXPECT_EQ(40, Int32FromGTestEnv(\"temp\", 40));\n\n  SetEnv(GTEST_FLAG_PREFIX_UPPER_ \"TEMP\", \"12X\");\n  EXPECT_EQ(50, Int32FromGTestEnv(\"temp\", 50));\n}\n\n#endif  // !defined(GTEST_GET_INT32_FROM_ENV_)\n\n// Tests that Int32FromGTestEnv() parses and returns the value of the\n// environment variable when it represents a valid decimal integer in\n// the range of an Int32.\nTEST(Int32FromGTestEnvTest, ParsesAndReturnsValidValue) {\n  SetEnv(GTEST_FLAG_PREFIX_UPPER_ \"TEMP\", \"123\");\n  EXPECT_EQ(123, Int32FromGTestEnv(\"temp\", 0));\n\n  SetEnv(GTEST_FLAG_PREFIX_UPPER_ \"TEMP\", \"-321\");\n  EXPECT_EQ(-321, Int32FromGTestEnv(\"temp\", 0));\n}\n#endif  // !GTEST_OS_WINDOWS_MOBILE\n\n// Tests ParseFlag().\n\n// Tests that ParseInt32Flag() returns false and doesn't change the\n// output value when the flag has wrong format\nTEST(ParseInt32FlagTest, ReturnsFalseForInvalidFlag) {\n  int32_t value = 123;\n  EXPECT_FALSE(ParseFlag(\"--a=100\", \"b\", &value));\n  EXPECT_EQ(123, value);\n\n  EXPECT_FALSE(ParseFlag(\"a=100\", \"a\", &value));\n  EXPECT_EQ(123, value);\n}\n\n// Tests that ParseFlag() returns false and doesn't change the\n// output value when the flag overflows as an Int32.\nTEST(ParseInt32FlagTest, ReturnsDefaultWhenValueOverflows) {\n  printf(\"(expecting 2 warnings)\\n\");\n\n  int32_t value = 123;\n  EXPECT_FALSE(ParseFlag(\"--abc=12345678987654321\", \"abc\", &value));\n  EXPECT_EQ(123, value);\n\n  EXPECT_FALSE(ParseFlag(\"--abc=-12345678987654321\", \"abc\", &value));\n  EXPECT_EQ(123, value);\n}\n\n// Tests that ParseInt32Flag() returns false and doesn't change the\n// output value when the flag does not represent a valid decimal\n// integer.\nTEST(ParseInt32FlagTest, ReturnsDefaultWhenValueIsInvalid) {\n  printf(\"(expecting 2 warnings)\\n\");\n\n  int32_t value = 123;\n  EXPECT_FALSE(ParseFlag(\"--abc=A1\", \"abc\", &value));\n  EXPECT_EQ(123, value);\n\n  EXPECT_FALSE(ParseFlag(\"--abc=12X\", \"abc\", &value));\n  EXPECT_EQ(123, value);\n}\n\n// Tests that ParseInt32Flag() parses the value of the flag and\n// returns true when the flag represents a valid decimal integer in\n// the range of an Int32.\nTEST(ParseInt32FlagTest, ParsesAndReturnsValidValue) {\n  int32_t value = 123;\n  EXPECT_TRUE(ParseFlag(\"--\" GTEST_FLAG_PREFIX_ \"abc=456\", \"abc\", &value));\n  EXPECT_EQ(456, value);\n\n  EXPECT_TRUE(ParseFlag(\"--\" GTEST_FLAG_PREFIX_ \"abc=-789\", \"abc\", &value));\n  EXPECT_EQ(-789, value);\n}\n\n// Tests that Int32FromEnvOrDie() parses the value of the var or\n// returns the correct default.\n// Environment variables are not supported on Windows CE.\n#if !GTEST_OS_WINDOWS_MOBILE\nTEST(Int32FromEnvOrDieTest, ParsesAndReturnsValidValue) {\n  EXPECT_EQ(333, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ \"UnsetVar\", 333));\n  SetEnv(GTEST_FLAG_PREFIX_UPPER_ \"UnsetVar\", \"123\");\n  EXPECT_EQ(123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ \"UnsetVar\", 333));\n  SetEnv(GTEST_FLAG_PREFIX_UPPER_ \"UnsetVar\", \"-123\");\n  EXPECT_EQ(-123, Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ \"UnsetVar\", 333));\n}\n#endif  // !GTEST_OS_WINDOWS_MOBILE\n\n// Tests that Int32FromEnvOrDie() aborts with an error message\n// if the variable is not an int32_t.\nTEST(Int32FromEnvOrDieDeathTest, AbortsOnFailure) {\n  SetEnv(GTEST_FLAG_PREFIX_UPPER_ \"VAR\", \"xxx\");\n  EXPECT_DEATH_IF_SUPPORTED(\n      Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ \"VAR\", 123), \".*\");\n}\n\n// Tests that Int32FromEnvOrDie() aborts with an error message\n// if the variable cannot be represented by an int32_t.\nTEST(Int32FromEnvOrDieDeathTest, AbortsOnInt32Overflow) {\n  SetEnv(GTEST_FLAG_PREFIX_UPPER_ \"VAR\", \"1234567891234567891234\");\n  EXPECT_DEATH_IF_SUPPORTED(\n      Int32FromEnvOrDie(GTEST_FLAG_PREFIX_UPPER_ \"VAR\", 123), \".*\");\n}\n\n// Tests that ShouldRunTestOnShard() selects all tests\n// where there is 1 shard.\nTEST(ShouldRunTestOnShardTest, IsPartitionWhenThereIsOneShard) {\n  EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 0));\n  EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 1));\n  EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 2));\n  EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 3));\n  EXPECT_TRUE(ShouldRunTestOnShard(1, 0, 4));\n}\n\nclass ShouldShardTest : public testing::Test {\n protected:\n  void SetUp() override {\n    index_var_ = GTEST_FLAG_PREFIX_UPPER_ \"INDEX\";\n    total_var_ = GTEST_FLAG_PREFIX_UPPER_ \"TOTAL\";\n  }\n\n  void TearDown() override {\n    SetEnv(index_var_, \"\");\n    SetEnv(total_var_, \"\");\n  }\n\n  const char* index_var_;\n  const char* total_var_;\n};\n\n// Tests that sharding is disabled if neither of the environment variables\n// are set.\nTEST_F(ShouldShardTest, ReturnsFalseWhenNeitherEnvVarIsSet) {\n  SetEnv(index_var_, \"\");\n  SetEnv(total_var_, \"\");\n\n  EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));\n  EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));\n}\n\n// Tests that sharding is not enabled if total_shards  == 1.\nTEST_F(ShouldShardTest, ReturnsFalseWhenTotalShardIsOne) {\n  SetEnv(index_var_, \"0\");\n  SetEnv(total_var_, \"1\");\n  EXPECT_FALSE(ShouldShard(total_var_, index_var_, false));\n  EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));\n}\n\n// Tests that sharding is enabled if total_shards > 1 and\n// we are not in a death test subprocess.\n// Environment variables are not supported on Windows CE.\n#if !GTEST_OS_WINDOWS_MOBILE\nTEST_F(ShouldShardTest, WorksWhenShardEnvVarsAreValid) {\n  SetEnv(index_var_, \"4\");\n  SetEnv(total_var_, \"22\");\n  EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));\n  EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));\n\n  SetEnv(index_var_, \"8\");\n  SetEnv(total_var_, \"9\");\n  EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));\n  EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));\n\n  SetEnv(index_var_, \"0\");\n  SetEnv(total_var_, \"9\");\n  EXPECT_TRUE(ShouldShard(total_var_, index_var_, false));\n  EXPECT_FALSE(ShouldShard(total_var_, index_var_, true));\n}\n#endif  // !GTEST_OS_WINDOWS_MOBILE\n\n// Tests that we exit in error if the sharding values are not valid.\n\ntypedef ShouldShardTest ShouldShardDeathTest;\n\nTEST_F(ShouldShardDeathTest, AbortsWhenShardingEnvVarsAreInvalid) {\n  SetEnv(index_var_, \"4\");\n  SetEnv(total_var_, \"4\");\n  EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), \".*\");\n\n  SetEnv(index_var_, \"4\");\n  SetEnv(total_var_, \"-2\");\n  EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), \".*\");\n\n  SetEnv(index_var_, \"5\");\n  SetEnv(total_var_, \"\");\n  EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), \".*\");\n\n  SetEnv(index_var_, \"\");\n  SetEnv(total_var_, \"5\");\n  EXPECT_DEATH_IF_SUPPORTED(ShouldShard(total_var_, index_var_, false), \".*\");\n}\n\n// Tests that ShouldRunTestOnShard is a partition when 5\n// shards are used.\nTEST(ShouldRunTestOnShardTest, IsPartitionWhenThereAreFiveShards) {\n  // Choose an arbitrary number of tests and shards.\n  const int num_tests = 17;\n  const int num_shards = 5;\n\n  // Check partitioning: each test should be on exactly 1 shard.\n  for (int test_id = 0; test_id < num_tests; test_id++) {\n    int prev_selected_shard_index = -1;\n    for (int shard_index = 0; shard_index < num_shards; shard_index++) {\n      if (ShouldRunTestOnShard(num_shards, shard_index, test_id)) {\n        if (prev_selected_shard_index < 0) {\n          prev_selected_shard_index = shard_index;\n        } else {\n          ADD_FAILURE() << \"Shard \" << prev_selected_shard_index << \" and \"\n                        << shard_index << \" are both selected to run test \"\n                        << test_id;\n        }\n      }\n    }\n  }\n\n  // Check balance: This is not required by the sharding protocol, but is a\n  // desirable property for performance.\n  for (int shard_index = 0; shard_index < num_shards; shard_index++) {\n    int num_tests_on_shard = 0;\n    for (int test_id = 0; test_id < num_tests; test_id++) {\n      num_tests_on_shard +=\n          ShouldRunTestOnShard(num_shards, shard_index, test_id);\n    }\n    EXPECT_GE(num_tests_on_shard, num_tests / num_shards);\n  }\n}\n\n// For the same reason we are not explicitly testing everything in the\n// Test class, there are no separate tests for the following classes\n// (except for some trivial cases):\n//\n//   TestSuite, UnitTest, UnitTestResultPrinter.\n//\n// Similarly, there are no separate tests for the following macros:\n//\n//   TEST, TEST_F, RUN_ALL_TESTS\n\nTEST(UnitTestTest, CanGetOriginalWorkingDir) {\n  ASSERT_TRUE(UnitTest::GetInstance()->original_working_dir() != nullptr);\n  EXPECT_STRNE(UnitTest::GetInstance()->original_working_dir(), \"\");\n}\n\nTEST(UnitTestTest, ReturnsPlausibleTimestamp) {\n  EXPECT_LT(0, UnitTest::GetInstance()->start_timestamp());\n  EXPECT_LE(UnitTest::GetInstance()->start_timestamp(), GetTimeInMillis());\n}\n\n// When a property using a reserved key is supplied to this function, it\n// tests that a non-fatal failure is added, a fatal failure is not added,\n// and that the property is not recorded.\nvoid ExpectNonFatalFailureRecordingPropertyWithReservedKey(\n    const TestResult& test_result, const char* key) {\n  EXPECT_NONFATAL_FAILURE(Test::RecordProperty(key, \"1\"), \"Reserved key\");\n  ASSERT_EQ(0, test_result.test_property_count())\n      << \"Property for key '\" << key << \"' recorded unexpectedly.\";\n}\n\nvoid ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(\n    const char* key) {\n  const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();\n  ASSERT_TRUE(test_info != nullptr);\n  ExpectNonFatalFailureRecordingPropertyWithReservedKey(*test_info->result(),\n                                                        key);\n}\n\nvoid ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(\n    const char* key) {\n  const testing::TestSuite* test_suite =\n      UnitTest::GetInstance()->current_test_suite();\n  ASSERT_TRUE(test_suite != nullptr);\n  ExpectNonFatalFailureRecordingPropertyWithReservedKey(\n      test_suite->ad_hoc_test_result(), key);\n}\n\nvoid ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(\n    const char* key) {\n  ExpectNonFatalFailureRecordingPropertyWithReservedKey(\n      UnitTest::GetInstance()->ad_hoc_test_result(), key);\n}\n\n// Tests that property recording functions in UnitTest outside of tests\n// functions correctly.  Creating a separate instance of UnitTest ensures it\n// is in a state similar to the UnitTest's singleton's between tests.\nclass UnitTestRecordPropertyTest\n    : public testing::internal::UnitTestRecordPropertyTestHelper {\n public:\n  static void SetUpTestSuite() {\n    ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(\n        \"disabled\");\n    ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(\n        \"errors\");\n    ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(\n        \"failures\");\n    ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(\n        \"name\");\n    ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(\n        \"tests\");\n    ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTestSuite(\n        \"time\");\n\n    Test::RecordProperty(\"test_case_key_1\", \"1\");\n\n    const testing::TestSuite* test_suite =\n        UnitTest::GetInstance()->current_test_suite();\n\n    ASSERT_TRUE(test_suite != nullptr);\n\n    ASSERT_EQ(1, test_suite->ad_hoc_test_result().test_property_count());\n    EXPECT_STREQ(\"test_case_key_1\",\n                 test_suite->ad_hoc_test_result().GetTestProperty(0).key());\n    EXPECT_STREQ(\"1\",\n                 test_suite->ad_hoc_test_result().GetTestProperty(0).value());\n  }\n};\n\n// Tests TestResult has the expected property when added.\nTEST_F(UnitTestRecordPropertyTest, OnePropertyFoundWhenAdded) {\n  UnitTestRecordProperty(\"key_1\", \"1\");\n\n  ASSERT_EQ(1, unit_test_.ad_hoc_test_result().test_property_count());\n\n  EXPECT_STREQ(\"key_1\",\n               unit_test_.ad_hoc_test_result().GetTestProperty(0).key());\n  EXPECT_STREQ(\"1\", unit_test_.ad_hoc_test_result().GetTestProperty(0).value());\n}\n\n// Tests TestResult has multiple properties when added.\nTEST_F(UnitTestRecordPropertyTest, MultiplePropertiesFoundWhenAdded) {\n  UnitTestRecordProperty(\"key_1\", \"1\");\n  UnitTestRecordProperty(\"key_2\", \"2\");\n\n  ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());\n\n  EXPECT_STREQ(\"key_1\",\n               unit_test_.ad_hoc_test_result().GetTestProperty(0).key());\n  EXPECT_STREQ(\"1\", unit_test_.ad_hoc_test_result().GetTestProperty(0).value());\n\n  EXPECT_STREQ(\"key_2\",\n               unit_test_.ad_hoc_test_result().GetTestProperty(1).key());\n  EXPECT_STREQ(\"2\", unit_test_.ad_hoc_test_result().GetTestProperty(1).value());\n}\n\n// Tests TestResult::RecordProperty() overrides values for duplicate keys.\nTEST_F(UnitTestRecordPropertyTest, OverridesValuesForDuplicateKeys) {\n  UnitTestRecordProperty(\"key_1\", \"1\");\n  UnitTestRecordProperty(\"key_2\", \"2\");\n  UnitTestRecordProperty(\"key_1\", \"12\");\n  UnitTestRecordProperty(\"key_2\", \"22\");\n\n  ASSERT_EQ(2, unit_test_.ad_hoc_test_result().test_property_count());\n\n  EXPECT_STREQ(\"key_1\",\n               unit_test_.ad_hoc_test_result().GetTestProperty(0).key());\n  EXPECT_STREQ(\"12\",\n               unit_test_.ad_hoc_test_result().GetTestProperty(0).value());\n\n  EXPECT_STREQ(\"key_2\",\n               unit_test_.ad_hoc_test_result().GetTestProperty(1).key());\n  EXPECT_STREQ(\"22\",\n               unit_test_.ad_hoc_test_result().GetTestProperty(1).value());\n}\n\nTEST_F(UnitTestRecordPropertyTest,\n       AddFailureInsideTestsWhenUsingTestSuiteReservedKeys) {\n  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(\"name\");\n  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(\n      \"value_param\");\n  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(\n      \"type_param\");\n  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(\"status\");\n  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(\"time\");\n  ExpectNonFatalFailureRecordingPropertyWithReservedKeyForCurrentTest(\n      \"classname\");\n}\n\nTEST_F(UnitTestRecordPropertyTest,\n       AddRecordWithReservedKeysGeneratesCorrectPropertyList) {\n  EXPECT_NONFATAL_FAILURE(\n      Test::RecordProperty(\"name\", \"1\"),\n      \"'classname', 'name', 'status', 'time', 'type_param', 'value_param',\"\n      \" 'file', and 'line' are reserved\");\n}\n\nclass UnitTestRecordPropertyTestEnvironment : public Environment {\n public:\n  void TearDown() override {\n    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(\n        \"tests\");\n    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(\n        \"failures\");\n    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(\n        \"disabled\");\n    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(\n        \"errors\");\n    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(\n        \"name\");\n    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(\n        \"timestamp\");\n    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(\n        \"time\");\n    ExpectNonFatalFailureRecordingPropertyWithReservedKeyOutsideOfTestSuite(\n        \"random_seed\");\n  }\n};\n\n// This will test property recording outside of any test or test case.\nstatic Environment* record_property_env GTEST_ATTRIBUTE_UNUSED_ =\n    AddGlobalTestEnvironment(new UnitTestRecordPropertyTestEnvironment);\n\n// This group of tests is for predicate assertions (ASSERT_PRED*, etc)\n// of various arities.  They do not attempt to be exhaustive.  Rather,\n// view them as smoke tests that can be easily reviewed and verified.\n// A more complete set of tests for predicate assertions can be found\n// in gtest_pred_impl_unittest.cc.\n\n// First, some predicates and predicate-formatters needed by the tests.\n\n// Returns true if and only if the argument is an even number.\nbool IsEven(int n) { return (n % 2) == 0; }\n\n// A functor that returns true if and only if the argument is an even number.\nstruct IsEvenFunctor {\n  bool operator()(int n) { return IsEven(n); }\n};\n\n// A predicate-formatter function that asserts the argument is an even\n// number.\nAssertionResult AssertIsEven(const char* expr, int n) {\n  if (IsEven(n)) {\n    return AssertionSuccess();\n  }\n\n  Message msg;\n  msg << expr << \" evaluates to \" << n << \", which is not even.\";\n  return AssertionFailure(msg);\n}\n\n// A predicate function that returns AssertionResult for use in\n// EXPECT/ASSERT_TRUE/FALSE.\nAssertionResult ResultIsEven(int n) {\n  if (IsEven(n))\n    return AssertionSuccess() << n << \" is even\";\n  else\n    return AssertionFailure() << n << \" is odd\";\n}\n\n// A predicate function that returns AssertionResult but gives no\n// explanation why it succeeds. Needed for testing that\n// EXPECT/ASSERT_FALSE handles such functions correctly.\nAssertionResult ResultIsEvenNoExplanation(int n) {\n  if (IsEven(n))\n    return AssertionSuccess();\n  else\n    return AssertionFailure() << n << \" is odd\";\n}\n\n// A predicate-formatter functor that asserts the argument is an even\n// number.\nstruct AssertIsEvenFunctor {\n  AssertionResult operator()(const char* expr, int n) {\n    return AssertIsEven(expr, n);\n  }\n};\n\n// Returns true if and only if the sum of the arguments is an even number.\nbool SumIsEven2(int n1, int n2) { return IsEven(n1 + n2); }\n\n// A functor that returns true if and only if the sum of the arguments is an\n// even number.\nstruct SumIsEven3Functor {\n  bool operator()(int n1, int n2, int n3) { return IsEven(n1 + n2 + n3); }\n};\n\n// A predicate-formatter function that asserts the sum of the\n// arguments is an even number.\nAssertionResult AssertSumIsEven4(const char* e1, const char* e2, const char* e3,\n                                 const char* e4, int n1, int n2, int n3,\n                                 int n4) {\n  const int sum = n1 + n2 + n3 + n4;\n  if (IsEven(sum)) {\n    return AssertionSuccess();\n  }\n\n  Message msg;\n  msg << e1 << \" + \" << e2 << \" + \" << e3 << \" + \" << e4 << \" (\" << n1 << \" + \"\n      << n2 << \" + \" << n3 << \" + \" << n4 << \") evaluates to \" << sum\n      << \", which is not even.\";\n  return AssertionFailure(msg);\n}\n\n// A predicate-formatter functor that asserts the sum of the arguments\n// is an even number.\nstruct AssertSumIsEven5Functor {\n  AssertionResult operator()(const char* e1, const char* e2, const char* e3,\n                             const char* e4, const char* e5, int n1, int n2,\n                             int n3, int n4, int n5) {\n    const int sum = n1 + n2 + n3 + n4 + n5;\n    if (IsEven(sum)) {\n      return AssertionSuccess();\n    }\n\n    Message msg;\n    msg << e1 << \" + \" << e2 << \" + \" << e3 << \" + \" << e4 << \" + \" << e5\n        << \" (\" << n1 << \" + \" << n2 << \" + \" << n3 << \" + \" << n4 << \" + \"\n        << n5 << \") evaluates to \" << sum << \", which is not even.\";\n    return AssertionFailure(msg);\n  }\n};\n\n// Tests unary predicate assertions.\n\n// Tests unary predicate assertions that don't use a custom formatter.\nTEST(Pred1Test, WithoutFormat) {\n  // Success cases.\n  EXPECT_PRED1(IsEvenFunctor(), 2) << \"This failure is UNEXPECTED!\";\n  ASSERT_PRED1(IsEven, 4);\n\n  // Failure cases.\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED1(IsEven, 5) << \"This failure is expected.\";\n      },\n      \"This failure is expected.\");\n  EXPECT_FATAL_FAILURE(ASSERT_PRED1(IsEvenFunctor(), 5), \"evaluates to false\");\n}\n\n// Tests unary predicate assertions that use a custom formatter.\nTEST(Pred1Test, WithFormat) {\n  // Success cases.\n  EXPECT_PRED_FORMAT1(AssertIsEven, 2);\n  ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), 4)\n      << \"This failure is UNEXPECTED!\";\n\n  // Failure cases.\n  const int n = 5;\n  EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT1(AssertIsEvenFunctor(), n),\n                          \"n evaluates to 5, which is not even.\");\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED_FORMAT1(AssertIsEven, 5) << \"This failure is expected.\";\n      },\n      \"This failure is expected.\");\n}\n\n// Tests that unary predicate assertions evaluates their arguments\n// exactly once.\nTEST(Pred1Test, SingleEvaluationOnFailure) {\n  // A success case.\n  static int n = 0;\n  EXPECT_PRED1(IsEven, n++);\n  EXPECT_EQ(1, n) << \"The argument is not evaluated exactly once.\";\n\n  // A failure case.\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED_FORMAT1(AssertIsEvenFunctor(), n++)\n            << \"This failure is expected.\";\n      },\n      \"This failure is expected.\");\n  EXPECT_EQ(2, n) << \"The argument is not evaluated exactly once.\";\n}\n\n// Tests predicate assertions whose arity is >= 2.\n\n// Tests predicate assertions that don't use a custom formatter.\nTEST(PredTest, WithoutFormat) {\n  // Success cases.\n  ASSERT_PRED2(SumIsEven2, 2, 4) << \"This failure is UNEXPECTED!\";\n  EXPECT_PRED3(SumIsEven3Functor(), 4, 6, 8);\n\n  // Failure cases.\n  const int n1 = 1;\n  const int n2 = 2;\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED2(SumIsEven2, n1, n2) << \"This failure is expected.\";\n      },\n      \"This failure is expected.\");\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED3(SumIsEven3Functor(), 1, 2, 4);\n      },\n      \"evaluates to false\");\n}\n\n// Tests predicate assertions that use a custom formatter.\nTEST(PredTest, WithFormat) {\n  // Success cases.\n  ASSERT_PRED_FORMAT4(AssertSumIsEven4, 4, 6, 8, 10)\n      << \"This failure is UNEXPECTED!\";\n  EXPECT_PRED_FORMAT5(AssertSumIsEven5Functor(), 2, 4, 6, 8, 10);\n\n  // Failure cases.\n  const int n1 = 1;\n  const int n2 = 2;\n  const int n3 = 4;\n  const int n4 = 6;\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT4(AssertSumIsEven4, n1, n2, n3, n4);\n      },\n      \"evaluates to 13, which is not even.\");\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), 1, 2, 4, 6, 8)\n            << \"This failure is expected.\";\n      },\n      \"This failure is expected.\");\n}\n\n// Tests that predicate assertions evaluates their arguments\n// exactly once.\nTEST(PredTest, SingleEvaluationOnFailure) {\n  // A success case.\n  int n1 = 0;\n  int n2 = 0;\n  EXPECT_PRED2(SumIsEven2, n1++, n2++);\n  EXPECT_EQ(1, n1) << \"Argument 1 is not evaluated exactly once.\";\n  EXPECT_EQ(1, n2) << \"Argument 2 is not evaluated exactly once.\";\n\n  // Another success case.\n  n1 = n2 = 0;\n  int n3 = 0;\n  int n4 = 0;\n  int n5 = 0;\n  ASSERT_PRED_FORMAT5(AssertSumIsEven5Functor(), n1++, n2++, n3++, n4++, n5++)\n      << \"This failure is UNEXPECTED!\";\n  EXPECT_EQ(1, n1) << \"Argument 1 is not evaluated exactly once.\";\n  EXPECT_EQ(1, n2) << \"Argument 2 is not evaluated exactly once.\";\n  EXPECT_EQ(1, n3) << \"Argument 3 is not evaluated exactly once.\";\n  EXPECT_EQ(1, n4) << \"Argument 4 is not evaluated exactly once.\";\n  EXPECT_EQ(1, n5) << \"Argument 5 is not evaluated exactly once.\";\n\n  // A failure case.\n  n1 = n2 = n3 = 0;\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED3(SumIsEven3Functor(), ++n1, n2++, n3++)\n            << \"This failure is expected.\";\n      },\n      \"This failure is expected.\");\n  EXPECT_EQ(1, n1) << \"Argument 1 is not evaluated exactly once.\";\n  EXPECT_EQ(1, n2) << \"Argument 2 is not evaluated exactly once.\";\n  EXPECT_EQ(1, n3) << \"Argument 3 is not evaluated exactly once.\";\n\n  // Another failure case.\n  n1 = n2 = n3 = n4 = 0;\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT4(AssertSumIsEven4, ++n1, n2++, n3++, n4++);\n      },\n      \"evaluates to 1, which is not even.\");\n  EXPECT_EQ(1, n1) << \"Argument 1 is not evaluated exactly once.\";\n  EXPECT_EQ(1, n2) << \"Argument 2 is not evaluated exactly once.\";\n  EXPECT_EQ(1, n3) << \"Argument 3 is not evaluated exactly once.\";\n  EXPECT_EQ(1, n4) << \"Argument 4 is not evaluated exactly once.\";\n}\n\n// Test predicate assertions for sets\nTEST(PredTest, ExpectPredEvalFailure) {\n  std::set<int> set_a = {2, 1, 3, 4, 5};\n  std::set<int> set_b = {0, 4, 8};\n  const auto compare_sets = [](std::set<int>, std::set<int>) { return false; };\n  EXPECT_NONFATAL_FAILURE(\n      EXPECT_PRED2(compare_sets, set_a, set_b),\n      \"compare_sets(set_a, set_b) evaluates to false, where\\nset_a evaluates \"\n      \"to { 1, 2, 3, 4, 5 }\\nset_b evaluates to { 0, 4, 8 }\");\n}\n\n// Some helper functions for testing using overloaded/template\n// functions with ASSERT_PREDn and EXPECT_PREDn.\n\nbool IsPositive(double x) { return x > 0; }\n\ntemplate <typename T>\nbool IsNegative(T x) {\n  return x < 0;\n}\n\ntemplate <typename T1, typename T2>\nbool GreaterThan(T1 x1, T2 x2) {\n  return x1 > x2;\n}\n\n// Tests that overloaded functions can be used in *_PRED* as long as\n// their types are explicitly specified.\nTEST(PredicateAssertionTest, AcceptsOverloadedFunction) {\n  // C++Builder requires C-style casts rather than static_cast.\n  EXPECT_PRED1((bool (*)(int))(IsPositive), 5);       // NOLINT\n  ASSERT_PRED1((bool (*)(double))(IsPositive), 6.0);  // NOLINT\n}\n\n// Tests that template functions can be used in *_PRED* as long as\n// their types are explicitly specified.\nTEST(PredicateAssertionTest, AcceptsTemplateFunction) {\n  EXPECT_PRED1(IsNegative<int>, -5);\n  // Makes sure that we can handle templates with more than one\n  // parameter.\n  ASSERT_PRED2((GreaterThan<int, int>), 5, 0);\n}\n\n// Some helper functions for testing using overloaded/template\n// functions with ASSERT_PRED_FORMATn and EXPECT_PRED_FORMATn.\n\nAssertionResult IsPositiveFormat(const char* /* expr */, int n) {\n  return n > 0 ? AssertionSuccess() : AssertionFailure(Message() << \"Failure\");\n}\n\nAssertionResult IsPositiveFormat(const char* /* expr */, double x) {\n  return x > 0 ? AssertionSuccess() : AssertionFailure(Message() << \"Failure\");\n}\n\ntemplate <typename T>\nAssertionResult IsNegativeFormat(const char* /* expr */, T x) {\n  return x < 0 ? AssertionSuccess() : AssertionFailure(Message() << \"Failure\");\n}\n\ntemplate <typename T1, typename T2>\nAssertionResult EqualsFormat(const char* /* expr1 */, const char* /* expr2 */,\n                             const T1& x1, const T2& x2) {\n  return x1 == x2 ? AssertionSuccess()\n                  : AssertionFailure(Message() << \"Failure\");\n}\n\n// Tests that overloaded functions can be used in *_PRED_FORMAT*\n// without explicitly specifying their types.\nTEST(PredicateFormatAssertionTest, AcceptsOverloadedFunction) {\n  EXPECT_PRED_FORMAT1(IsPositiveFormat, 5);\n  ASSERT_PRED_FORMAT1(IsPositiveFormat, 6.0);\n}\n\n// Tests that template functions can be used in *_PRED_FORMAT* without\n// explicitly specifying their types.\nTEST(PredicateFormatAssertionTest, AcceptsTemplateFunction) {\n  EXPECT_PRED_FORMAT1(IsNegativeFormat, -5);\n  ASSERT_PRED_FORMAT2(EqualsFormat, 3, 3);\n}\n\n// Tests string assertions.\n\n// Tests ASSERT_STREQ with non-NULL arguments.\nTEST(StringAssertionTest, ASSERT_STREQ) {\n  const char* const p1 = \"good\";\n  ASSERT_STREQ(p1, p1);\n\n  // Let p2 have the same content as p1, but be at a different address.\n  const char p2[] = \"good\";\n  ASSERT_STREQ(p1, p2);\n\n  EXPECT_FATAL_FAILURE(ASSERT_STREQ(\"bad\", \"good\"), \"  \\\"bad\\\"\\n  \\\"good\\\"\");\n}\n\n// Tests ASSERT_STREQ with NULL arguments.\nTEST(StringAssertionTest, ASSERT_STREQ_Null) {\n  ASSERT_STREQ(static_cast<const char*>(nullptr), nullptr);\n  EXPECT_FATAL_FAILURE(ASSERT_STREQ(nullptr, \"non-null\"), \"non-null\");\n}\n\n// Tests ASSERT_STREQ with NULL arguments.\nTEST(StringAssertionTest, ASSERT_STREQ_Null2) {\n  EXPECT_FATAL_FAILURE(ASSERT_STREQ(\"non-null\", nullptr), \"non-null\");\n}\n\n// Tests ASSERT_STRNE.\nTEST(StringAssertionTest, ASSERT_STRNE) {\n  ASSERT_STRNE(\"hi\", \"Hi\");\n  ASSERT_STRNE(\"Hi\", nullptr);\n  ASSERT_STRNE(nullptr, \"Hi\");\n  ASSERT_STRNE(\"\", nullptr);\n  ASSERT_STRNE(nullptr, \"\");\n  ASSERT_STRNE(\"\", \"Hi\");\n  ASSERT_STRNE(\"Hi\", \"\");\n  EXPECT_FATAL_FAILURE(ASSERT_STRNE(\"Hi\", \"Hi\"), \"\\\"Hi\\\" vs \\\"Hi\\\"\");\n}\n\n// Tests ASSERT_STRCASEEQ.\nTEST(StringAssertionTest, ASSERT_STRCASEEQ) {\n  ASSERT_STRCASEEQ(\"hi\", \"Hi\");\n  ASSERT_STRCASEEQ(static_cast<const char*>(nullptr), nullptr);\n\n  ASSERT_STRCASEEQ(\"\", \"\");\n  EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ(\"Hi\", \"hi2\"), \"Ignoring case\");\n}\n\n// Tests ASSERT_STRCASENE.\nTEST(StringAssertionTest, ASSERT_STRCASENE) {\n  ASSERT_STRCASENE(\"hi1\", \"Hi2\");\n  ASSERT_STRCASENE(\"Hi\", nullptr);\n  ASSERT_STRCASENE(nullptr, \"Hi\");\n  ASSERT_STRCASENE(\"\", nullptr);\n  ASSERT_STRCASENE(nullptr, \"\");\n  ASSERT_STRCASENE(\"\", \"Hi\");\n  ASSERT_STRCASENE(\"Hi\", \"\");\n  EXPECT_FATAL_FAILURE(ASSERT_STRCASENE(\"Hi\", \"hi\"), \"(ignoring case)\");\n}\n\n// Tests *_STREQ on wide strings.\nTEST(StringAssertionTest, STREQ_Wide) {\n  // NULL strings.\n  ASSERT_STREQ(static_cast<const wchar_t*>(nullptr), nullptr);\n\n  // Empty strings.\n  ASSERT_STREQ(L\"\", L\"\");\n\n  // Non-null vs NULL.\n  EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L\"non-null\", nullptr), \"non-null\");\n\n  // Equal strings.\n  EXPECT_STREQ(L\"Hi\", L\"Hi\");\n\n  // Unequal strings.\n  EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L\"abc\", L\"Abc\"), \"Abc\");\n\n  // Strings containing wide characters.\n  EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(L\"abc\\x8119\", L\"abc\\x8120\"), \"abc\");\n\n  // The streaming variation.\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_STREQ(L\"abc\\x8119\", L\"abc\\x8121\") << \"Expected failure\";\n      },\n      \"Expected failure\");\n}\n\n// Tests *_STRNE on wide strings.\nTEST(StringAssertionTest, STRNE_Wide) {\n  // NULL strings.\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_STRNE(static_cast<const wchar_t*>(nullptr), nullptr);\n      },\n      \"\");\n\n  // Empty strings.\n  EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L\"\", L\"\"), \"L\\\"\\\"\");\n\n  // Non-null vs NULL.\n  ASSERT_STRNE(L\"non-null\", nullptr);\n\n  // Equal strings.\n  EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L\"Hi\", L\"Hi\"), \"L\\\"Hi\\\"\");\n\n  // Unequal strings.\n  EXPECT_STRNE(L\"abc\", L\"Abc\");\n\n  // Strings containing wide characters.\n  EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(L\"abc\\x8119\", L\"abc\\x8119\"), \"abc\");\n\n  // The streaming variation.\n  ASSERT_STRNE(L\"abc\\x8119\", L\"abc\\x8120\") << \"This shouldn't happen\";\n}\n\n// Tests for ::testing::IsSubstring().\n\n// Tests that IsSubstring() returns the correct result when the input\n// argument type is const char*.\nTEST(IsSubstringTest, ReturnsCorrectResultForCString) {\n  EXPECT_FALSE(IsSubstring(\"\", \"\", nullptr, \"a\"));\n  EXPECT_FALSE(IsSubstring(\"\", \"\", \"b\", nullptr));\n  EXPECT_FALSE(IsSubstring(\"\", \"\", \"needle\", \"haystack\"));\n\n  EXPECT_TRUE(IsSubstring(\"\", \"\", static_cast<const char*>(nullptr), nullptr));\n  EXPECT_TRUE(IsSubstring(\"\", \"\", \"needle\", \"two needles\"));\n}\n\n// Tests that IsSubstring() returns the correct result when the input\n// argument type is const wchar_t*.\nTEST(IsSubstringTest, ReturnsCorrectResultForWideCString) {\n  EXPECT_FALSE(IsSubstring(\"\", \"\", kNull, L\"a\"));\n  EXPECT_FALSE(IsSubstring(\"\", \"\", L\"b\", kNull));\n  EXPECT_FALSE(IsSubstring(\"\", \"\", L\"needle\", L\"haystack\"));\n\n  EXPECT_TRUE(\n      IsSubstring(\"\", \"\", static_cast<const wchar_t*>(nullptr), nullptr));\n  EXPECT_TRUE(IsSubstring(\"\", \"\", L\"needle\", L\"two needles\"));\n}\n\n// Tests that IsSubstring() generates the correct message when the input\n// argument type is const char*.\nTEST(IsSubstringTest, GeneratesCorrectMessageForCString) {\n  EXPECT_STREQ(\n      \"Value of: needle_expr\\n\"\n      \"  Actual: \\\"needle\\\"\\n\"\n      \"Expected: a substring of haystack_expr\\n\"\n      \"Which is: \\\"haystack\\\"\",\n      IsSubstring(\"needle_expr\", \"haystack_expr\", \"needle\", \"haystack\")\n          .failure_message());\n}\n\n// Tests that IsSubstring returns the correct result when the input\n// argument type is ::std::string.\nTEST(IsSubstringTest, ReturnsCorrectResultsForStdString) {\n  EXPECT_TRUE(IsSubstring(\"\", \"\", std::string(\"hello\"), \"ahellob\"));\n  EXPECT_FALSE(IsSubstring(\"\", \"\", \"hello\", std::string(\"world\")));\n}\n\n#if GTEST_HAS_STD_WSTRING\n// Tests that IsSubstring returns the correct result when the input\n// argument type is ::std::wstring.\nTEST(IsSubstringTest, ReturnsCorrectResultForStdWstring) {\n  EXPECT_TRUE(IsSubstring(\"\", \"\", ::std::wstring(L\"needle\"), L\"two needles\"));\n  EXPECT_FALSE(IsSubstring(\"\", \"\", L\"needle\", ::std::wstring(L\"haystack\")));\n}\n\n// Tests that IsSubstring() generates the correct message when the input\n// argument type is ::std::wstring.\nTEST(IsSubstringTest, GeneratesCorrectMessageForWstring) {\n  EXPECT_STREQ(\n      \"Value of: needle_expr\\n\"\n      \"  Actual: L\\\"needle\\\"\\n\"\n      \"Expected: a substring of haystack_expr\\n\"\n      \"Which is: L\\\"haystack\\\"\",\n      IsSubstring(\"needle_expr\", \"haystack_expr\", ::std::wstring(L\"needle\"),\n                  L\"haystack\")\n          .failure_message());\n}\n\n#endif  // GTEST_HAS_STD_WSTRING\n\n// Tests for ::testing::IsNotSubstring().\n\n// Tests that IsNotSubstring() returns the correct result when the input\n// argument type is const char*.\nTEST(IsNotSubstringTest, ReturnsCorrectResultForCString) {\n  EXPECT_TRUE(IsNotSubstring(\"\", \"\", \"needle\", \"haystack\"));\n  EXPECT_FALSE(IsNotSubstring(\"\", \"\", \"needle\", \"two needles\"));\n}\n\n// Tests that IsNotSubstring() returns the correct result when the input\n// argument type is const wchar_t*.\nTEST(IsNotSubstringTest, ReturnsCorrectResultForWideCString) {\n  EXPECT_TRUE(IsNotSubstring(\"\", \"\", L\"needle\", L\"haystack\"));\n  EXPECT_FALSE(IsNotSubstring(\"\", \"\", L\"needle\", L\"two needles\"));\n}\n\n// Tests that IsNotSubstring() generates the correct message when the input\n// argument type is const wchar_t*.\nTEST(IsNotSubstringTest, GeneratesCorrectMessageForWideCString) {\n  EXPECT_STREQ(\n      \"Value of: needle_expr\\n\"\n      \"  Actual: L\\\"needle\\\"\\n\"\n      \"Expected: not a substring of haystack_expr\\n\"\n      \"Which is: L\\\"two needles\\\"\",\n      IsNotSubstring(\"needle_expr\", \"haystack_expr\", L\"needle\", L\"two needles\")\n          .failure_message());\n}\n\n// Tests that IsNotSubstring returns the correct result when the input\n// argument type is ::std::string.\nTEST(IsNotSubstringTest, ReturnsCorrectResultsForStdString) {\n  EXPECT_FALSE(IsNotSubstring(\"\", \"\", std::string(\"hello\"), \"ahellob\"));\n  EXPECT_TRUE(IsNotSubstring(\"\", \"\", \"hello\", std::string(\"world\")));\n}\n\n// Tests that IsNotSubstring() generates the correct message when the input\n// argument type is ::std::string.\nTEST(IsNotSubstringTest, GeneratesCorrectMessageForStdString) {\n  EXPECT_STREQ(\n      \"Value of: needle_expr\\n\"\n      \"  Actual: \\\"needle\\\"\\n\"\n      \"Expected: not a substring of haystack_expr\\n\"\n      \"Which is: \\\"two needles\\\"\",\n      IsNotSubstring(\"needle_expr\", \"haystack_expr\", ::std::string(\"needle\"),\n                     \"two needles\")\n          .failure_message());\n}\n\n#if GTEST_HAS_STD_WSTRING\n\n// Tests that IsNotSubstring returns the correct result when the input\n// argument type is ::std::wstring.\nTEST(IsNotSubstringTest, ReturnsCorrectResultForStdWstring) {\n  EXPECT_FALSE(\n      IsNotSubstring(\"\", \"\", ::std::wstring(L\"needle\"), L\"two needles\"));\n  EXPECT_TRUE(IsNotSubstring(\"\", \"\", L\"needle\", ::std::wstring(L\"haystack\")));\n}\n\n#endif  // GTEST_HAS_STD_WSTRING\n\n// Tests floating-point assertions.\n\ntemplate <typename RawType>\nclass FloatingPointTest : public Test {\n protected:\n  // Pre-calculated numbers to be used by the tests.\n  struct TestValues {\n    RawType close_to_positive_zero;\n    RawType close_to_negative_zero;\n    RawType further_from_negative_zero;\n\n    RawType close_to_one;\n    RawType further_from_one;\n\n    RawType infinity;\n    RawType close_to_infinity;\n    RawType further_from_infinity;\n\n    RawType nan1;\n    RawType nan2;\n  };\n\n  typedef typename testing::internal::FloatingPoint<RawType> Floating;\n  typedef typename Floating::Bits Bits;\n\n  void SetUp() override {\n    const uint32_t max_ulps = Floating::kMaxUlps;\n\n    // The bits that represent 0.0.\n    const Bits zero_bits = Floating(0).bits();\n\n    // Makes some numbers close to 0.0.\n    values_.close_to_positive_zero =\n        Floating::ReinterpretBits(zero_bits + max_ulps / 2);\n    values_.close_to_negative_zero =\n        -Floating::ReinterpretBits(zero_bits + max_ulps - max_ulps / 2);\n    values_.further_from_negative_zero =\n        -Floating::ReinterpretBits(zero_bits + max_ulps + 1 - max_ulps / 2);\n\n    // The bits that represent 1.0.\n    const Bits one_bits = Floating(1).bits();\n\n    // Makes some numbers close to 1.0.\n    values_.close_to_one = Floating::ReinterpretBits(one_bits + max_ulps);\n    values_.further_from_one =\n        Floating::ReinterpretBits(one_bits + max_ulps + 1);\n\n    // +infinity.\n    values_.infinity = Floating::Infinity();\n\n    // The bits that represent +infinity.\n    const Bits infinity_bits = Floating(values_.infinity).bits();\n\n    // Makes some numbers close to infinity.\n    values_.close_to_infinity =\n        Floating::ReinterpretBits(infinity_bits - max_ulps);\n    values_.further_from_infinity =\n        Floating::ReinterpretBits(infinity_bits - max_ulps - 1);\n\n    // Makes some NAN's.  Sets the most significant bit of the fraction so that\n    // our NaN's are quiet; trying to process a signaling NaN would raise an\n    // exception if our environment enables floating point exceptions.\n    values_.nan1 = Floating::ReinterpretBits(\n        Floating::kExponentBitMask |\n        (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 1);\n    values_.nan2 = Floating::ReinterpretBits(\n        Floating::kExponentBitMask |\n        (static_cast<Bits>(1) << (Floating::kFractionBitCount - 1)) | 200);\n  }\n\n  void TestSize() { EXPECT_EQ(sizeof(RawType), sizeof(Bits)); }\n\n  static TestValues values_;\n};\n\ntemplate <typename RawType>\ntypename FloatingPointTest<RawType>::TestValues\n    FloatingPointTest<RawType>::values_;\n\n// Instantiates FloatingPointTest for testing *_FLOAT_EQ.\ntypedef FloatingPointTest<float> FloatTest;\n\n// Tests that the size of Float::Bits matches the size of float.\nTEST_F(FloatTest, Size) { TestSize(); }\n\n// Tests comparing with +0 and -0.\nTEST_F(FloatTest, Zeros) {\n  EXPECT_FLOAT_EQ(0.0, -0.0);\n  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(-0.0, 1.0), \"1.0\");\n  EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.5), \"1.5\");\n}\n\n// Tests comparing numbers close to 0.\n//\n// This ensures that *_FLOAT_EQ handles the sign correctly and no\n// overflow occurs when comparing numbers whose absolute value is very\n// small.\nTEST_F(FloatTest, AlmostZeros) {\n  // In C++Builder, names within local classes (such as used by\n  // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the\n  // scoping class.  Use a static local alias as a workaround.\n  // We use the assignment syntax since some compilers, like Sun Studio,\n  // don't allow initializing references using construction syntax\n  // (parentheses).\n  static const FloatTest::TestValues& v = this->values_;\n\n  EXPECT_FLOAT_EQ(0.0, v.close_to_positive_zero);\n  EXPECT_FLOAT_EQ(-0.0, v.close_to_negative_zero);\n  EXPECT_FLOAT_EQ(v.close_to_positive_zero, v.close_to_negative_zero);\n\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_FLOAT_EQ(v.close_to_positive_zero, v.further_from_negative_zero);\n      },\n      \"v.further_from_negative_zero\");\n}\n\n// Tests comparing numbers close to each other.\nTEST_F(FloatTest, SmallDiff) {\n  EXPECT_FLOAT_EQ(1.0, values_.close_to_one);\n  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, values_.further_from_one),\n                          \"values_.further_from_one\");\n}\n\n// Tests comparing numbers far apart.\nTEST_F(FloatTest, LargeDiff) {\n  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(2.5, 3.0), \"3.0\");\n}\n\n// Tests comparing with infinity.\n//\n// This ensures that no overflow occurs when comparing numbers whose\n// absolute value is very large.\nTEST_F(FloatTest, Infinity) {\n  EXPECT_FLOAT_EQ(values_.infinity, values_.close_to_infinity);\n  EXPECT_FLOAT_EQ(-values_.infinity, -values_.close_to_infinity);\n  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, -values_.infinity),\n                          \"-values_.infinity\");\n\n  // This is interesting as the representations of infinity and nan1\n  // are only 1 DLP apart.\n  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.infinity, values_.nan1),\n                          \"values_.nan1\");\n}\n\n// Tests that comparing with NAN always returns false.\nTEST_F(FloatTest, NaN) {\n  // In C++Builder, names within local classes (such as used by\n  // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the\n  // scoping class.  Use a static local alias as a workaround.\n  // We use the assignment syntax since some compilers, like Sun Studio,\n  // don't allow initializing references using construction syntax\n  // (parentheses).\n  static const FloatTest::TestValues& v = this->values_;\n\n  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan1), \"v.nan1\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(v.nan1, v.nan2), \"v.nan2\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(1.0, v.nan1), \"v.nan1\");\n\n  EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(v.nan1, v.infinity), \"v.infinity\");\n}\n\n// Tests that *_FLOAT_EQ are reflexive.\nTEST_F(FloatTest, Reflexive) {\n  EXPECT_FLOAT_EQ(0.0, 0.0);\n  EXPECT_FLOAT_EQ(1.0, 1.0);\n  ASSERT_FLOAT_EQ(values_.infinity, values_.infinity);\n}\n\n// Tests that *_FLOAT_EQ are commutative.\nTEST_F(FloatTest, Commutative) {\n  // We already tested EXPECT_FLOAT_EQ(1.0, values_.close_to_one).\n  EXPECT_FLOAT_EQ(values_.close_to_one, 1.0);\n\n  // We already tested EXPECT_FLOAT_EQ(1.0, values_.further_from_one).\n  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(values_.further_from_one, 1.0),\n                          \"1.0\");\n}\n\n// Tests EXPECT_NEAR.\nTEST_F(FloatTest, EXPECT_NEAR) {\n  EXPECT_NEAR(-1.0f, -1.1f, 0.2f);\n  EXPECT_NEAR(2.0f, 3.0f, 1.0f);\n  EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0f, 1.5f, 0.25f),  // NOLINT\n                          \"The difference between 1.0f and 1.5f is 0.5, \"\n                          \"which exceeds 0.25f\");\n}\n\n// Tests ASSERT_NEAR.\nTEST_F(FloatTest, ASSERT_NEAR) {\n  ASSERT_NEAR(-1.0f, -1.1f, 0.2f);\n  ASSERT_NEAR(2.0f, 3.0f, 1.0f);\n  EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0f, 1.5f, 0.25f),  // NOLINT\n                       \"The difference between 1.0f and 1.5f is 0.5, \"\n                       \"which exceeds 0.25f\");\n}\n\n// Tests the cases where FloatLE() should succeed.\nTEST_F(FloatTest, FloatLESucceeds) {\n  EXPECT_PRED_FORMAT2(FloatLE, 1.0f, 2.0f);  // When val1 < val2,\n  ASSERT_PRED_FORMAT2(FloatLE, 1.0f, 1.0f);  // val1 == val2,\n\n  // or when val1 is greater than, but almost equals to, val2.\n  EXPECT_PRED_FORMAT2(FloatLE, values_.close_to_positive_zero, 0.0f);\n}\n\n// Tests the cases where FloatLE() should fail.\nTEST_F(FloatTest, FloatLEFails) {\n  // When val1 is greater than val2 by a large margin,\n  EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(FloatLE, 2.0f, 1.0f),\n                          \"(2.0f) <= (1.0f)\");\n\n  // or by a small yet non-negligible margin,\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT2(FloatLE, values_.further_from_one, 1.0f);\n      },\n      \"(values_.further_from_one) <= (1.0f)\");\n\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT2(FloatLE, values_.nan1, values_.infinity);\n      },\n      \"(values_.nan1) <= (values_.infinity)\");\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT2(FloatLE, -values_.infinity, values_.nan1);\n      },\n      \"(-values_.infinity) <= (values_.nan1)\");\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED_FORMAT2(FloatLE, values_.nan1, values_.nan1);\n      },\n      \"(values_.nan1) <= (values_.nan1)\");\n}\n\n// Instantiates FloatingPointTest for testing *_DOUBLE_EQ.\ntypedef FloatingPointTest<double> DoubleTest;\n\n// Tests that the size of Double::Bits matches the size of double.\nTEST_F(DoubleTest, Size) { TestSize(); }\n\n// Tests comparing with +0 and -0.\nTEST_F(DoubleTest, Zeros) {\n  EXPECT_DOUBLE_EQ(0.0, -0.0);\n  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(-0.0, 1.0), \"1.0\");\n  EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(0.0, 1.0), \"1.0\");\n}\n\n// Tests comparing numbers close to 0.\n//\n// This ensures that *_DOUBLE_EQ handles the sign correctly and no\n// overflow occurs when comparing numbers whose absolute value is very\n// small.\nTEST_F(DoubleTest, AlmostZeros) {\n  // In C++Builder, names within local classes (such as used by\n  // EXPECT_FATAL_FAILURE) cannot be resolved against static members of the\n  // scoping class.  Use a static local alias as a workaround.\n  // We use the assignment syntax since some compilers, like Sun Studio,\n  // don't allow initializing references using construction syntax\n  // (parentheses).\n  static const DoubleTest::TestValues& v = this->values_;\n\n  EXPECT_DOUBLE_EQ(0.0, v.close_to_positive_zero);\n  EXPECT_DOUBLE_EQ(-0.0, v.close_to_negative_zero);\n  EXPECT_DOUBLE_EQ(v.close_to_positive_zero, v.close_to_negative_zero);\n\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_DOUBLE_EQ(v.close_to_positive_zero,\n                         v.further_from_negative_zero);\n      },\n      \"v.further_from_negative_zero\");\n}\n\n// Tests comparing numbers close to each other.\nTEST_F(DoubleTest, SmallDiff) {\n  EXPECT_DOUBLE_EQ(1.0, values_.close_to_one);\n  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, values_.further_from_one),\n                          \"values_.further_from_one\");\n}\n\n// Tests comparing numbers far apart.\nTEST_F(DoubleTest, LargeDiff) {\n  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(2.0, 3.0), \"3.0\");\n}\n\n// Tests comparing with infinity.\n//\n// This ensures that no overflow occurs when comparing numbers whose\n// absolute value is very large.\nTEST_F(DoubleTest, Infinity) {\n  EXPECT_DOUBLE_EQ(values_.infinity, values_.close_to_infinity);\n  EXPECT_DOUBLE_EQ(-values_.infinity, -values_.close_to_infinity);\n  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, -values_.infinity),\n                          \"-values_.infinity\");\n\n  // This is interesting as the representations of infinity_ and nan1_\n  // are only 1 DLP apart.\n  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.infinity, values_.nan1),\n                          \"values_.nan1\");\n}\n\n// Tests that comparing with NAN always returns false.\nTEST_F(DoubleTest, NaN) {\n  static const DoubleTest::TestValues& v = this->values_;\n\n  // Nokia's STLport crashes if we try to output infinity or NaN.\n  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan1), \"v.nan1\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(v.nan1, v.nan2), \"v.nan2\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1.0, v.nan1), \"v.nan1\");\n  EXPECT_FATAL_FAILURE(ASSERT_DOUBLE_EQ(v.nan1, v.infinity), \"v.infinity\");\n}\n\n// Tests that *_DOUBLE_EQ are reflexive.\nTEST_F(DoubleTest, Reflexive) {\n  EXPECT_DOUBLE_EQ(0.0, 0.0);\n  EXPECT_DOUBLE_EQ(1.0, 1.0);\n  ASSERT_DOUBLE_EQ(values_.infinity, values_.infinity);\n}\n\n// Tests that *_DOUBLE_EQ are commutative.\nTEST_F(DoubleTest, Commutative) {\n  // We already tested EXPECT_DOUBLE_EQ(1.0, values_.close_to_one).\n  EXPECT_DOUBLE_EQ(values_.close_to_one, 1.0);\n\n  // We already tested EXPECT_DOUBLE_EQ(1.0, values_.further_from_one).\n  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(values_.further_from_one, 1.0),\n                          \"1.0\");\n}\n\n// Tests EXPECT_NEAR.\nTEST_F(DoubleTest, EXPECT_NEAR) {\n  EXPECT_NEAR(-1.0, -1.1, 0.2);\n  EXPECT_NEAR(2.0, 3.0, 1.0);\n  EXPECT_NONFATAL_FAILURE(EXPECT_NEAR(1.0, 1.5, 0.25),  // NOLINT\n                          \"The difference between 1.0 and 1.5 is 0.5, \"\n                          \"which exceeds 0.25\");\n  // At this magnitude adjacent doubles are 512.0 apart, so this triggers a\n  // slightly different failure reporting path.\n  EXPECT_NONFATAL_FAILURE(\n      EXPECT_NEAR(4.2934311416234112e+18, 4.2934311416234107e+18, 1.0),\n      \"The abs_error parameter 1.0 evaluates to 1 which is smaller than the \"\n      \"minimum distance between doubles for numbers of this magnitude which is \"\n      \"512\");\n}\n\n// Tests ASSERT_NEAR.\nTEST_F(DoubleTest, ASSERT_NEAR) {\n  ASSERT_NEAR(-1.0, -1.1, 0.2);\n  ASSERT_NEAR(2.0, 3.0, 1.0);\n  EXPECT_FATAL_FAILURE(ASSERT_NEAR(1.0, 1.5, 0.25),  // NOLINT\n                       \"The difference between 1.0 and 1.5 is 0.5, \"\n                       \"which exceeds 0.25\");\n}\n\n// Tests the cases where DoubleLE() should succeed.\nTEST_F(DoubleTest, DoubleLESucceeds) {\n  EXPECT_PRED_FORMAT2(DoubleLE, 1.0, 2.0);  // When val1 < val2,\n  ASSERT_PRED_FORMAT2(DoubleLE, 1.0, 1.0);  // val1 == val2,\n\n  // or when val1 is greater than, but almost equals to, val2.\n  EXPECT_PRED_FORMAT2(DoubleLE, values_.close_to_positive_zero, 0.0);\n}\n\n// Tests the cases where DoubleLE() should fail.\nTEST_F(DoubleTest, DoubleLEFails) {\n  // When val1 is greater than val2 by a large margin,\n  EXPECT_NONFATAL_FAILURE(EXPECT_PRED_FORMAT2(DoubleLE, 2.0, 1.0),\n                          \"(2.0) <= (1.0)\");\n\n  // or by a small yet non-negligible margin,\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT2(DoubleLE, values_.further_from_one, 1.0);\n      },\n      \"(values_.further_from_one) <= (1.0)\");\n\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.infinity);\n      },\n      \"(values_.nan1) <= (values_.infinity)\");\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_PRED_FORMAT2(DoubleLE, -values_.infinity, values_.nan1);\n      },\n      \" (-values_.infinity) <= (values_.nan1)\");\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_PRED_FORMAT2(DoubleLE, values_.nan1, values_.nan1);\n      },\n      \"(values_.nan1) <= (values_.nan1)\");\n}\n\n// Verifies that a test or test case whose name starts with DISABLED_ is\n// not run.\n\n// A test whose name starts with DISABLED_.\n// Should not run.\nTEST(DisabledTest, DISABLED_TestShouldNotRun) {\n  FAIL() << \"Unexpected failure: Disabled test should not be run.\";\n}\n\n// A test whose name does not start with DISABLED_.\n// Should run.\nTEST(DisabledTest, NotDISABLED_TestShouldRun) { EXPECT_EQ(1, 1); }\n\n// A test case whose name starts with DISABLED_.\n// Should not run.\nTEST(DISABLED_TestSuite, TestShouldNotRun) {\n  FAIL() << \"Unexpected failure: Test in disabled test case should not be run.\";\n}\n\n// A test case and test whose names start with DISABLED_.\n// Should not run.\nTEST(DISABLED_TestSuite, DISABLED_TestShouldNotRun) {\n  FAIL() << \"Unexpected failure: Test in disabled test case should not be run.\";\n}\n\n// Check that when all tests in a test case are disabled, SetUpTestSuite() and\n// TearDownTestSuite() are not called.\nclass DisabledTestsTest : public Test {\n protected:\n  static void SetUpTestSuite() {\n    FAIL() << \"Unexpected failure: All tests disabled in test case. \"\n              \"SetUpTestSuite() should not be called.\";\n  }\n\n  static void TearDownTestSuite() {\n    FAIL() << \"Unexpected failure: All tests disabled in test case. \"\n              \"TearDownTestSuite() should not be called.\";\n  }\n};\n\nTEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_1) {\n  FAIL() << \"Unexpected failure: Disabled test should not be run.\";\n}\n\nTEST_F(DisabledTestsTest, DISABLED_TestShouldNotRun_2) {\n  FAIL() << \"Unexpected failure: Disabled test should not be run.\";\n}\n\n// Tests that disabled typed tests aren't run.\n\ntemplate <typename T>\nclass TypedTest : public Test {};\n\ntypedef testing::Types<int, double> NumericTypes;\nTYPED_TEST_SUITE(TypedTest, NumericTypes);\n\nTYPED_TEST(TypedTest, DISABLED_ShouldNotRun) {\n  FAIL() << \"Unexpected failure: Disabled typed test should not run.\";\n}\n\ntemplate <typename T>\nclass DISABLED_TypedTest : public Test {};\n\nTYPED_TEST_SUITE(DISABLED_TypedTest, NumericTypes);\n\nTYPED_TEST(DISABLED_TypedTest, ShouldNotRun) {\n  FAIL() << \"Unexpected failure: Disabled typed test should not run.\";\n}\n\n// Tests that disabled type-parameterized tests aren't run.\n\ntemplate <typename T>\nclass TypedTestP : public Test {};\n\nTYPED_TEST_SUITE_P(TypedTestP);\n\nTYPED_TEST_P(TypedTestP, DISABLED_ShouldNotRun) {\n  FAIL() << \"Unexpected failure: \"\n         << \"Disabled type-parameterized test should not run.\";\n}\n\nREGISTER_TYPED_TEST_SUITE_P(TypedTestP, DISABLED_ShouldNotRun);\n\nINSTANTIATE_TYPED_TEST_SUITE_P(My, TypedTestP, NumericTypes);\n\ntemplate <typename T>\nclass DISABLED_TypedTestP : public Test {};\n\nTYPED_TEST_SUITE_P(DISABLED_TypedTestP);\n\nTYPED_TEST_P(DISABLED_TypedTestP, ShouldNotRun) {\n  FAIL() << \"Unexpected failure: \"\n         << \"Disabled type-parameterized test should not run.\";\n}\n\nREGISTER_TYPED_TEST_SUITE_P(DISABLED_TypedTestP, ShouldNotRun);\n\nINSTANTIATE_TYPED_TEST_SUITE_P(My, DISABLED_TypedTestP, NumericTypes);\n\n// Tests that assertion macros evaluate their arguments exactly once.\n\nclass SingleEvaluationTest : public Test {\n public:  // Must be public and not protected due to a bug in g++ 3.4.2.\n  // This helper function is needed by the FailedASSERT_STREQ test\n  // below.  It's public to work around C++Builder's bug with scoping local\n  // classes.\n  static void CompareAndIncrementCharPtrs() { ASSERT_STREQ(p1_++, p2_++); }\n\n  // This helper function is needed by the FailedASSERT_NE test below.  It's\n  // public to work around C++Builder's bug with scoping local classes.\n  static void CompareAndIncrementInts() { ASSERT_NE(a_++, b_++); }\n\n protected:\n  SingleEvaluationTest() {\n    p1_ = s1_;\n    p2_ = s2_;\n    a_ = 0;\n    b_ = 0;\n  }\n\n  static const char* const s1_;\n  static const char* const s2_;\n  static const char* p1_;\n  static const char* p2_;\n\n  static int a_;\n  static int b_;\n};\n\nconst char* const SingleEvaluationTest::s1_ = \"01234\";\nconst char* const SingleEvaluationTest::s2_ = \"abcde\";\nconst char* SingleEvaluationTest::p1_;\nconst char* SingleEvaluationTest::p2_;\nint SingleEvaluationTest::a_;\nint SingleEvaluationTest::b_;\n\n// Tests that when ASSERT_STREQ fails, it evaluates its arguments\n// exactly once.\nTEST_F(SingleEvaluationTest, FailedASSERT_STREQ) {\n  EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementCharPtrs(),\n                       \"p2_++\");\n  EXPECT_EQ(s1_ + 1, p1_);\n  EXPECT_EQ(s2_ + 1, p2_);\n}\n\n// Tests that string assertion arguments are evaluated exactly once.\nTEST_F(SingleEvaluationTest, ASSERT_STR) {\n  // successful EXPECT_STRNE\n  EXPECT_STRNE(p1_++, p2_++);\n  EXPECT_EQ(s1_ + 1, p1_);\n  EXPECT_EQ(s2_ + 1, p2_);\n\n  // failed EXPECT_STRCASEEQ\n  EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(p1_++, p2_++), \"Ignoring case\");\n  EXPECT_EQ(s1_ + 2, p1_);\n  EXPECT_EQ(s2_ + 2, p2_);\n}\n\n// Tests that when ASSERT_NE fails, it evaluates its arguments exactly\n// once.\nTEST_F(SingleEvaluationTest, FailedASSERT_NE) {\n  EXPECT_FATAL_FAILURE(SingleEvaluationTest::CompareAndIncrementInts(),\n                       \"(a_++) != (b_++)\");\n  EXPECT_EQ(1, a_);\n  EXPECT_EQ(1, b_);\n}\n\n// Tests that assertion arguments are evaluated exactly once.\nTEST_F(SingleEvaluationTest, OtherCases) {\n  // successful EXPECT_TRUE\n  EXPECT_TRUE(0 == a_++);  // NOLINT\n  EXPECT_EQ(1, a_);\n\n  // failed EXPECT_TRUE\n  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(-1 == a_++), \"-1 == a_++\");\n  EXPECT_EQ(2, a_);\n\n  // successful EXPECT_GT\n  EXPECT_GT(a_++, b_++);\n  EXPECT_EQ(3, a_);\n  EXPECT_EQ(1, b_);\n\n  // failed EXPECT_LT\n  EXPECT_NONFATAL_FAILURE(EXPECT_LT(a_++, b_++), \"(a_++) < (b_++)\");\n  EXPECT_EQ(4, a_);\n  EXPECT_EQ(2, b_);\n\n  // successful ASSERT_TRUE\n  ASSERT_TRUE(0 < a_++);  // NOLINT\n  EXPECT_EQ(5, a_);\n\n  // successful ASSERT_GT\n  ASSERT_GT(a_++, b_++);\n  EXPECT_EQ(6, a_);\n  EXPECT_EQ(3, b_);\n}\n\n#if GTEST_HAS_EXCEPTIONS\n\n#if GTEST_HAS_RTTI\n\n#ifdef _MSC_VER\n#define ERROR_DESC \"class std::runtime_error\"\n#else\n#define ERROR_DESC \"std::runtime_error\"\n#endif\n\n#else  // GTEST_HAS_RTTI\n\n#define ERROR_DESC \"an std::exception-derived error\"\n\n#endif  // GTEST_HAS_RTTI\n\nvoid ThrowAnInteger() { throw 1; }\nvoid ThrowRuntimeError(const char* what) { throw std::runtime_error(what); }\n\n// Tests that assertion arguments are evaluated exactly once.\nTEST_F(SingleEvaluationTest, ExceptionTests) {\n  // successful EXPECT_THROW\n  EXPECT_THROW(\n      {  // NOLINT\n        a_++;\n        ThrowAnInteger();\n      },\n      int);\n  EXPECT_EQ(1, a_);\n\n  // failed EXPECT_THROW, throws different\n  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(\n                              {  // NOLINT\n                                a_++;\n                                ThrowAnInteger();\n                              },\n                              bool),\n                          \"throws a different type\");\n  EXPECT_EQ(2, a_);\n\n  // failed EXPECT_THROW, throws runtime error\n  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(\n                              {  // NOLINT\n                                a_++;\n                                ThrowRuntimeError(\"A description\");\n                              },\n                              bool),\n                          \"throws \" ERROR_DESC\n                          \" with description \\\"A description\\\"\");\n  EXPECT_EQ(3, a_);\n\n  // failed EXPECT_THROW, throws nothing\n  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(a_++, bool), \"throws nothing\");\n  EXPECT_EQ(4, a_);\n\n  // successful EXPECT_NO_THROW\n  EXPECT_NO_THROW(a_++);\n  EXPECT_EQ(5, a_);\n\n  // failed EXPECT_NO_THROW\n  EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW({  // NOLINT\n                            a_++;\n                            ThrowAnInteger();\n                          }),\n                          \"it throws\");\n  EXPECT_EQ(6, a_);\n\n  // successful EXPECT_ANY_THROW\n  EXPECT_ANY_THROW({  // NOLINT\n    a_++;\n    ThrowAnInteger();\n  });\n  EXPECT_EQ(7, a_);\n\n  // failed EXPECT_ANY_THROW\n  EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(a_++), \"it doesn't\");\n  EXPECT_EQ(8, a_);\n}\n\n#endif  // GTEST_HAS_EXCEPTIONS\n\n// Tests {ASSERT|EXPECT}_NO_FATAL_FAILURE.\nclass NoFatalFailureTest : public Test {\n protected:\n  void Succeeds() {}\n  void FailsNonFatal() { ADD_FAILURE() << \"some non-fatal failure\"; }\n  void Fails() { FAIL() << \"some fatal failure\"; }\n\n  void DoAssertNoFatalFailureOnFails() {\n    ASSERT_NO_FATAL_FAILURE(Fails());\n    ADD_FAILURE() << \"should not reach here.\";\n  }\n\n  void DoExpectNoFatalFailureOnFails() {\n    EXPECT_NO_FATAL_FAILURE(Fails());\n    ADD_FAILURE() << \"other failure\";\n  }\n};\n\nTEST_F(NoFatalFailureTest, NoFailure) {\n  EXPECT_NO_FATAL_FAILURE(Succeeds());\n  ASSERT_NO_FATAL_FAILURE(Succeeds());\n}\n\nTEST_F(NoFatalFailureTest, NonFatalIsNoFailure) {\n  EXPECT_NONFATAL_FAILURE(EXPECT_NO_FATAL_FAILURE(FailsNonFatal()),\n                          \"some non-fatal failure\");\n  EXPECT_NONFATAL_FAILURE(ASSERT_NO_FATAL_FAILURE(FailsNonFatal()),\n                          \"some non-fatal failure\");\n}\n\nTEST_F(NoFatalFailureTest, AssertNoFatalFailureOnFatalFailure) {\n  TestPartResultArray gtest_failures;\n  {\n    ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);\n    DoAssertNoFatalFailureOnFails();\n  }\n  ASSERT_EQ(2, gtest_failures.size());\n  EXPECT_EQ(TestPartResult::kFatalFailure,\n            gtest_failures.GetTestPartResult(0).type());\n  EXPECT_EQ(TestPartResult::kFatalFailure,\n            gtest_failures.GetTestPartResult(1).type());\n  EXPECT_PRED_FORMAT2(testing::IsSubstring, \"some fatal failure\",\n                      gtest_failures.GetTestPartResult(0).message());\n  EXPECT_PRED_FORMAT2(testing::IsSubstring, \"it does\",\n                      gtest_failures.GetTestPartResult(1).message());\n}\n\nTEST_F(NoFatalFailureTest, ExpectNoFatalFailureOnFatalFailure) {\n  TestPartResultArray gtest_failures;\n  {\n    ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);\n    DoExpectNoFatalFailureOnFails();\n  }\n  ASSERT_EQ(3, gtest_failures.size());\n  EXPECT_EQ(TestPartResult::kFatalFailure,\n            gtest_failures.GetTestPartResult(0).type());\n  EXPECT_EQ(TestPartResult::kNonFatalFailure,\n            gtest_failures.GetTestPartResult(1).type());\n  EXPECT_EQ(TestPartResult::kNonFatalFailure,\n            gtest_failures.GetTestPartResult(2).type());\n  EXPECT_PRED_FORMAT2(testing::IsSubstring, \"some fatal failure\",\n                      gtest_failures.GetTestPartResult(0).message());\n  EXPECT_PRED_FORMAT2(testing::IsSubstring, \"it does\",\n                      gtest_failures.GetTestPartResult(1).message());\n  EXPECT_PRED_FORMAT2(testing::IsSubstring, \"other failure\",\n                      gtest_failures.GetTestPartResult(2).message());\n}\n\nTEST_F(NoFatalFailureTest, MessageIsStreamable) {\n  TestPartResultArray gtest_failures;\n  {\n    ScopedFakeTestPartResultReporter gtest_reporter(&gtest_failures);\n    EXPECT_NO_FATAL_FAILURE(FAIL() << \"foo\") << \"my message\";\n  }\n  ASSERT_EQ(2, gtest_failures.size());\n  EXPECT_EQ(TestPartResult::kNonFatalFailure,\n            gtest_failures.GetTestPartResult(0).type());\n  EXPECT_EQ(TestPartResult::kNonFatalFailure,\n            gtest_failures.GetTestPartResult(1).type());\n  EXPECT_PRED_FORMAT2(testing::IsSubstring, \"foo\",\n                      gtest_failures.GetTestPartResult(0).message());\n  EXPECT_PRED_FORMAT2(testing::IsSubstring, \"my message\",\n                      gtest_failures.GetTestPartResult(1).message());\n}\n\n// Tests non-string assertions.\n\nstd::string EditsToString(const std::vector<EditType>& edits) {\n  std::string out;\n  for (size_t i = 0; i < edits.size(); ++i) {\n    static const char kEdits[] = \" +-/\";\n    out.append(1, kEdits[edits[i]]);\n  }\n  return out;\n}\n\nstd::vector<size_t> CharsToIndices(const std::string& str) {\n  std::vector<size_t> out;\n  for (size_t i = 0; i < str.size(); ++i) {\n    out.push_back(static_cast<size_t>(str[i]));\n  }\n  return out;\n}\n\nstd::vector<std::string> CharsToLines(const std::string& str) {\n  std::vector<std::string> out;\n  for (size_t i = 0; i < str.size(); ++i) {\n    out.push_back(str.substr(i, 1));\n  }\n  return out;\n}\n\nTEST(EditDistance, TestSuites) {\n  struct Case {\n    int line;\n    const char* left;\n    const char* right;\n    const char* expected_edits;\n    const char* expected_diff;\n  };\n  static const Case kCases[] = {\n      // No change.\n      {__LINE__, \"A\", \"A\", \" \", \"\"},\n      {__LINE__, \"ABCDE\", \"ABCDE\", \"     \", \"\"},\n      // Simple adds.\n      {__LINE__, \"X\", \"XA\", \" +\", \"@@ +1,2 @@\\n X\\n+A\\n\"},\n      {__LINE__, \"X\", \"XABCD\", \" ++++\", \"@@ +1,5 @@\\n X\\n+A\\n+B\\n+C\\n+D\\n\"},\n      // Simple removes.\n      {__LINE__, \"XA\", \"X\", \" -\", \"@@ -1,2 @@\\n X\\n-A\\n\"},\n      {__LINE__, \"XABCD\", \"X\", \" ----\", \"@@ -1,5 @@\\n X\\n-A\\n-B\\n-C\\n-D\\n\"},\n      // Simple replaces.\n      {__LINE__, \"A\", \"a\", \"/\", \"@@ -1,1 +1,1 @@\\n-A\\n+a\\n\"},\n      {__LINE__, \"ABCD\", \"abcd\", \"////\",\n       \"@@ -1,4 +1,4 @@\\n-A\\n-B\\n-C\\n-D\\n+a\\n+b\\n+c\\n+d\\n\"},\n      // Path finding.\n      {__LINE__, \"ABCDEFGH\", \"ABXEGH1\", \"  -/ -  +\",\n       \"@@ -1,8 +1,7 @@\\n A\\n B\\n-C\\n-D\\n+X\\n E\\n-F\\n G\\n H\\n+1\\n\"},\n      {__LINE__, \"AAAABCCCC\", \"ABABCDCDC\", \"- /   + / \",\n       \"@@ -1,9 +1,9 @@\\n-A\\n A\\n-A\\n+B\\n A\\n B\\n C\\n+D\\n C\\n-C\\n+D\\n C\\n\"},\n      {__LINE__, \"ABCDE\", \"BCDCD\", \"-   +/\",\n       \"@@ -1,5 +1,5 @@\\n-A\\n B\\n C\\n D\\n-E\\n+C\\n+D\\n\"},\n      {__LINE__, \"ABCDEFGHIJKL\", \"BCDCDEFGJKLJK\", \"- ++     --   ++\",\n       \"@@ -1,4 +1,5 @@\\n-A\\n B\\n+C\\n+D\\n C\\n D\\n\"\n       \"@@ -6,7 +7,7 @@\\n F\\n G\\n-H\\n-I\\n J\\n K\\n L\\n+J\\n+K\\n\"},\n      {}};\n  for (const Case* c = kCases; c->left; ++c) {\n    EXPECT_TRUE(c->expected_edits ==\n                EditsToString(CalculateOptimalEdits(CharsToIndices(c->left),\n                                                    CharsToIndices(c->right))))\n        << \"Left <\" << c->left << \"> Right <\" << c->right << \"> Edits <\"\n        << EditsToString(CalculateOptimalEdits(CharsToIndices(c->left),\n                                               CharsToIndices(c->right)))\n        << \">\";\n    EXPECT_TRUE(c->expected_diff == CreateUnifiedDiff(CharsToLines(c->left),\n                                                      CharsToLines(c->right)))\n        << \"Left <\" << c->left << \"> Right <\" << c->right << \"> Diff <\"\n        << CreateUnifiedDiff(CharsToLines(c->left), CharsToLines(c->right))\n        << \">\";\n  }\n}\n\n// Tests EqFailure(), used for implementing *EQ* assertions.\nTEST(AssertionTest, EqFailure) {\n  const std::string foo_val(\"5\"), bar_val(\"6\");\n  const std::string msg1(\n      EqFailure(\"foo\", \"bar\", foo_val, bar_val, false).failure_message());\n  EXPECT_STREQ(\n      \"Expected equality of these values:\\n\"\n      \"  foo\\n\"\n      \"    Which is: 5\\n\"\n      \"  bar\\n\"\n      \"    Which is: 6\",\n      msg1.c_str());\n\n  const std::string msg2(\n      EqFailure(\"foo\", \"6\", foo_val, bar_val, false).failure_message());\n  EXPECT_STREQ(\n      \"Expected equality of these values:\\n\"\n      \"  foo\\n\"\n      \"    Which is: 5\\n\"\n      \"  6\",\n      msg2.c_str());\n\n  const std::string msg3(\n      EqFailure(\"5\", \"bar\", foo_val, bar_val, false).failure_message());\n  EXPECT_STREQ(\n      \"Expected equality of these values:\\n\"\n      \"  5\\n\"\n      \"  bar\\n\"\n      \"    Which is: 6\",\n      msg3.c_str());\n\n  const std::string msg4(\n      EqFailure(\"5\", \"6\", foo_val, bar_val, false).failure_message());\n  EXPECT_STREQ(\n      \"Expected equality of these values:\\n\"\n      \"  5\\n\"\n      \"  6\",\n      msg4.c_str());\n\n  const std::string msg5(\n      EqFailure(\"foo\", \"bar\", std::string(\"\\\"x\\\"\"), std::string(\"\\\"y\\\"\"), true)\n          .failure_message());\n  EXPECT_STREQ(\n      \"Expected equality of these values:\\n\"\n      \"  foo\\n\"\n      \"    Which is: \\\"x\\\"\\n\"\n      \"  bar\\n\"\n      \"    Which is: \\\"y\\\"\\n\"\n      \"Ignoring case\",\n      msg5.c_str());\n}\n\nTEST(AssertionTest, EqFailureWithDiff) {\n  const std::string left(\n      \"1\\\\n2XXX\\\\n3\\\\n5\\\\n6\\\\n7\\\\n8\\\\n9\\\\n10\\\\n11\\\\n12XXX\\\\n13\\\\n14\\\\n15\");\n  const std::string right(\n      \"1\\\\n2\\\\n3\\\\n4\\\\n5\\\\n6\\\\n7\\\\n8\\\\n9\\\\n11\\\\n12\\\\n13\\\\n14\");\n  const std::string msg1(\n      EqFailure(\"left\", \"right\", left, right, false).failure_message());\n  EXPECT_STREQ(\n      \"Expected equality of these values:\\n\"\n      \"  left\\n\"\n      \"    Which is: \"\n      \"1\\\\n2XXX\\\\n3\\\\n5\\\\n6\\\\n7\\\\n8\\\\n9\\\\n10\\\\n11\\\\n12XXX\\\\n13\\\\n14\\\\n15\\n\"\n      \"  right\\n\"\n      \"    Which is: 1\\\\n2\\\\n3\\\\n4\\\\n5\\\\n6\\\\n7\\\\n8\\\\n9\\\\n11\\\\n12\\\\n13\\\\n14\\n\"\n      \"With diff:\\n@@ -1,5 +1,6 @@\\n 1\\n-2XXX\\n+2\\n 3\\n+4\\n 5\\n 6\\n\"\n      \"@@ -7,8 +8,6 @@\\n 8\\n 9\\n-10\\n 11\\n-12XXX\\n+12\\n 13\\n 14\\n-15\\n\",\n      msg1.c_str());\n}\n\n// Tests AppendUserMessage(), used for implementing the *EQ* macros.\nTEST(AssertionTest, AppendUserMessage) {\n  const std::string foo(\"foo\");\n\n  Message msg;\n  EXPECT_STREQ(\"foo\", AppendUserMessage(foo, msg).c_str());\n\n  msg << \"bar\";\n  EXPECT_STREQ(\"foo\\nbar\", AppendUserMessage(foo, msg).c_str());\n}\n\n#ifdef __BORLANDC__\n// Silences warnings: \"Condition is always true\", \"Unreachable code\"\n#pragma option push -w-ccc -w-rch\n#endif\n\n// Tests ASSERT_TRUE.\nTEST(AssertionTest, ASSERT_TRUE) {\n  ASSERT_TRUE(2 > 1);  // NOLINT\n  EXPECT_FATAL_FAILURE(ASSERT_TRUE(2 < 1), \"2 < 1\");\n}\n\n// Tests ASSERT_TRUE(predicate) for predicates returning AssertionResult.\nTEST(AssertionTest, AssertTrueWithAssertionResult) {\n  ASSERT_TRUE(ResultIsEven(2));\n#ifndef __BORLANDC__\n  // ICE's in C++Builder.\n  EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEven(3)),\n                       \"Value of: ResultIsEven(3)\\n\"\n                       \"  Actual: false (3 is odd)\\n\"\n                       \"Expected: true\");\n#endif\n  ASSERT_TRUE(ResultIsEvenNoExplanation(2));\n  EXPECT_FATAL_FAILURE(ASSERT_TRUE(ResultIsEvenNoExplanation(3)),\n                       \"Value of: ResultIsEvenNoExplanation(3)\\n\"\n                       \"  Actual: false (3 is odd)\\n\"\n                       \"Expected: true\");\n}\n\n// Tests ASSERT_FALSE.\nTEST(AssertionTest, ASSERT_FALSE) {\n  ASSERT_FALSE(2 < 1);  // NOLINT\n  EXPECT_FATAL_FAILURE(ASSERT_FALSE(2 > 1),\n                       \"Value of: 2 > 1\\n\"\n                       \"  Actual: true\\n\"\n                       \"Expected: false\");\n}\n\n// Tests ASSERT_FALSE(predicate) for predicates returning AssertionResult.\nTEST(AssertionTest, AssertFalseWithAssertionResult) {\n  ASSERT_FALSE(ResultIsEven(3));\n#ifndef __BORLANDC__\n  // ICE's in C++Builder.\n  EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEven(2)),\n                       \"Value of: ResultIsEven(2)\\n\"\n                       \"  Actual: true (2 is even)\\n\"\n                       \"Expected: false\");\n#endif\n  ASSERT_FALSE(ResultIsEvenNoExplanation(3));\n  EXPECT_FATAL_FAILURE(ASSERT_FALSE(ResultIsEvenNoExplanation(2)),\n                       \"Value of: ResultIsEvenNoExplanation(2)\\n\"\n                       \"  Actual: true\\n\"\n                       \"Expected: false\");\n}\n\n#ifdef __BORLANDC__\n// Restores warnings after previous \"#pragma option push\" suppressed them\n#pragma option pop\n#endif\n\n// Tests using ASSERT_EQ on double values.  The purpose is to make\n// sure that the specialization we did for integer and anonymous enums\n// isn't used for double arguments.\nTEST(ExpectTest, ASSERT_EQ_Double) {\n  // A success.\n  ASSERT_EQ(5.6, 5.6);\n\n  // A failure.\n  EXPECT_FATAL_FAILURE(ASSERT_EQ(5.1, 5.2), \"5.1\");\n}\n\n// Tests ASSERT_EQ.\nTEST(AssertionTest, ASSERT_EQ) {\n  ASSERT_EQ(5, 2 + 3);\n  // clang-format off\n  EXPECT_FATAL_FAILURE(ASSERT_EQ(5, 2*3),\n                       \"Expected equality of these values:\\n\"\n                       \"  5\\n\"\n                       \"  2*3\\n\"\n                       \"    Which is: 6\");\n  // clang-format on\n}\n\n// Tests ASSERT_EQ(NULL, pointer).\nTEST(AssertionTest, ASSERT_EQ_NULL) {\n  // A success.\n  const char* p = nullptr;\n  ASSERT_EQ(nullptr, p);\n\n  // A failure.\n  static int n = 0;\n  EXPECT_FATAL_FAILURE(ASSERT_EQ(nullptr, &n), \"  &n\\n    Which is:\");\n}\n\n// Tests ASSERT_EQ(0, non_pointer).  Since the literal 0 can be\n// treated as a null pointer by the compiler, we need to make sure\n// that ASSERT_EQ(0, non_pointer) isn't interpreted by Google Test as\n// ASSERT_EQ(static_cast<void*>(NULL), non_pointer).\nTEST(ExpectTest, ASSERT_EQ_0) {\n  int n = 0;\n\n  // A success.\n  ASSERT_EQ(0, n);\n\n  // A failure.\n  EXPECT_FATAL_FAILURE(ASSERT_EQ(0, 5.6), \"  0\\n  5.6\");\n}\n\n// Tests ASSERT_NE.\nTEST(AssertionTest, ASSERT_NE) {\n  ASSERT_NE(6, 7);\n  EXPECT_FATAL_FAILURE(ASSERT_NE('a', 'a'),\n                       \"Expected: ('a') != ('a'), \"\n                       \"actual: 'a' (97, 0x61) vs 'a' (97, 0x61)\");\n}\n\n// Tests ASSERT_LE.\nTEST(AssertionTest, ASSERT_LE) {\n  ASSERT_LE(2, 3);\n  ASSERT_LE(2, 2);\n  EXPECT_FATAL_FAILURE(ASSERT_LE(2, 0), \"Expected: (2) <= (0), actual: 2 vs 0\");\n}\n\n// Tests ASSERT_LT.\nTEST(AssertionTest, ASSERT_LT) {\n  ASSERT_LT(2, 3);\n  EXPECT_FATAL_FAILURE(ASSERT_LT(2, 2), \"Expected: (2) < (2), actual: 2 vs 2\");\n}\n\n// Tests ASSERT_GE.\nTEST(AssertionTest, ASSERT_GE) {\n  ASSERT_GE(2, 1);\n  ASSERT_GE(2, 2);\n  EXPECT_FATAL_FAILURE(ASSERT_GE(2, 3), \"Expected: (2) >= (3), actual: 2 vs 3\");\n}\n\n// Tests ASSERT_GT.\nTEST(AssertionTest, ASSERT_GT) {\n  ASSERT_GT(2, 1);\n  EXPECT_FATAL_FAILURE(ASSERT_GT(2, 2), \"Expected: (2) > (2), actual: 2 vs 2\");\n}\n\n#if GTEST_HAS_EXCEPTIONS\n\nvoid ThrowNothing() {}\n\n// Tests ASSERT_THROW.\nTEST(AssertionTest, ASSERT_THROW) {\n  ASSERT_THROW(ThrowAnInteger(), int);\n\n#ifndef __BORLANDC__\n\n  // ICE's in C++Builder 2007 and 2009.\n  EXPECT_FATAL_FAILURE(\n      ASSERT_THROW(ThrowAnInteger(), bool),\n      \"Expected: ThrowAnInteger() throws an exception of type bool.\\n\"\n      \"  Actual: it throws a different type.\");\n  EXPECT_FATAL_FAILURE(\n      ASSERT_THROW(ThrowRuntimeError(\"A description\"), std::logic_error),\n      \"Expected: ThrowRuntimeError(\\\"A description\\\") \"\n      \"throws an exception of type std::logic_error.\\n  \"\n      \"Actual: it throws \" ERROR_DESC\n      \" \"\n      \"with description \\\"A description\\\".\");\n#endif\n\n  EXPECT_FATAL_FAILURE(\n      ASSERT_THROW(ThrowNothing(), bool),\n      \"Expected: ThrowNothing() throws an exception of type bool.\\n\"\n      \"  Actual: it throws nothing.\");\n}\n\n// Tests ASSERT_NO_THROW.\nTEST(AssertionTest, ASSERT_NO_THROW) {\n  ASSERT_NO_THROW(ThrowNothing());\n  EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()),\n                       \"Expected: ThrowAnInteger() doesn't throw an exception.\"\n                       \"\\n  Actual: it throws.\");\n  EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowRuntimeError(\"A description\")),\n                       \"Expected: ThrowRuntimeError(\\\"A description\\\") \"\n                       \"doesn't throw an exception.\\n  \"\n                       \"Actual: it throws \" ERROR_DESC\n                       \" \"\n                       \"with description \\\"A description\\\".\");\n}\n\n// Tests ASSERT_ANY_THROW.\nTEST(AssertionTest, ASSERT_ANY_THROW) {\n  ASSERT_ANY_THROW(ThrowAnInteger());\n  EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()),\n                       \"Expected: ThrowNothing() throws an exception.\\n\"\n                       \"  Actual: it doesn't.\");\n}\n\n#endif  // GTEST_HAS_EXCEPTIONS\n\n// Makes sure we deal with the precedence of <<.  This test should\n// compile.\nTEST(AssertionTest, AssertPrecedence) {\n  ASSERT_EQ(1 < 2, true);\n  bool false_value = false;\n  ASSERT_EQ(true && false_value, false);\n}\n\n// A subroutine used by the following test.\nvoid TestEq1(int x) { ASSERT_EQ(1, x); }\n\n// Tests calling a test subroutine that's not part of a fixture.\nTEST(AssertionTest, NonFixtureSubroutine) {\n  EXPECT_FATAL_FAILURE(TestEq1(2), \"  x\\n    Which is: 2\");\n}\n\n// An uncopyable class.\nclass Uncopyable {\n public:\n  explicit Uncopyable(int a_value) : value_(a_value) {}\n\n  int value() const { return value_; }\n  bool operator==(const Uncopyable& rhs) const {\n    return value() == rhs.value();\n  }\n\n private:\n  // This constructor deliberately has no implementation, as we don't\n  // want this class to be copyable.\n  Uncopyable(const Uncopyable&);  // NOLINT\n\n  int value_;\n};\n\n::std::ostream& operator<<(::std::ostream& os, const Uncopyable& value) {\n  return os << value.value();\n}\n\nbool IsPositiveUncopyable(const Uncopyable& x) { return x.value() > 0; }\n\n// A subroutine used by the following test.\nvoid TestAssertNonPositive() {\n  Uncopyable y(-1);\n  ASSERT_PRED1(IsPositiveUncopyable, y);\n}\n// A subroutine used by the following test.\nvoid TestAssertEqualsUncopyable() {\n  Uncopyable x(5);\n  Uncopyable y(-1);\n  ASSERT_EQ(x, y);\n}\n\n// Tests that uncopyable objects can be used in assertions.\nTEST(AssertionTest, AssertWorksWithUncopyableObject) {\n  Uncopyable x(5);\n  ASSERT_PRED1(IsPositiveUncopyable, x);\n  ASSERT_EQ(x, x);\n  EXPECT_FATAL_FAILURE(\n      TestAssertNonPositive(),\n      \"IsPositiveUncopyable(y) evaluates to false, where\\ny evaluates to -1\");\n  EXPECT_FATAL_FAILURE(TestAssertEqualsUncopyable(),\n                       \"Expected equality of these values:\\n\"\n                       \"  x\\n    Which is: 5\\n  y\\n    Which is: -1\");\n}\n\n// Tests that uncopyable objects can be used in expects.\nTEST(AssertionTest, ExpectWorksWithUncopyableObject) {\n  Uncopyable x(5);\n  EXPECT_PRED1(IsPositiveUncopyable, x);\n  Uncopyable y(-1);\n  EXPECT_NONFATAL_FAILURE(\n      EXPECT_PRED1(IsPositiveUncopyable, y),\n      \"IsPositiveUncopyable(y) evaluates to false, where\\ny evaluates to -1\");\n  EXPECT_EQ(x, x);\n  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y),\n                          \"Expected equality of these values:\\n\"\n                          \"  x\\n    Which is: 5\\n  y\\n    Which is: -1\");\n}\n\nenum NamedEnum { kE1 = 0, kE2 = 1 };\n\nTEST(AssertionTest, NamedEnum) {\n  EXPECT_EQ(kE1, kE1);\n  EXPECT_LT(kE1, kE2);\n  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), \"Which is: 0\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(kE1, kE2), \"Which is: 1\");\n}\n\n// Sun Studio and HP aCC2reject this code.\n#if !defined(__SUNPRO_CC) && !defined(__HP_aCC)\n\n// Tests using assertions with anonymous enums.\nenum {\n  kCaseA = -1,\n\n#if GTEST_OS_LINUX\n\n  // We want to test the case where the size of the anonymous enum is\n  // larger than sizeof(int), to make sure our implementation of the\n  // assertions doesn't truncate the enums.  However, MSVC\n  // (incorrectly) doesn't allow an enum value to exceed the range of\n  // an int, so this has to be conditionally compiled.\n  //\n  // On Linux, kCaseB and kCaseA have the same value when truncated to\n  // int size.  We want to test whether this will confuse the\n  // assertions.\n  kCaseB = testing::internal::kMaxBiggestInt,\n\n#else\n\n  kCaseB = INT_MAX,\n\n#endif  // GTEST_OS_LINUX\n\n  kCaseC = 42\n};\n\nTEST(AssertionTest, AnonymousEnum) {\n#if GTEST_OS_LINUX\n\n  EXPECT_EQ(static_cast<int>(kCaseA), static_cast<int>(kCaseB));\n\n#endif  // GTEST_OS_LINUX\n\n  EXPECT_EQ(kCaseA, kCaseA);\n  EXPECT_NE(kCaseA, kCaseB);\n  EXPECT_LT(kCaseA, kCaseB);\n  EXPECT_LE(kCaseA, kCaseB);\n  EXPECT_GT(kCaseB, kCaseA);\n  EXPECT_GE(kCaseA, kCaseA);\n  EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseB), \"(kCaseA) >= (kCaseB)\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_GE(kCaseA, kCaseC), \"-1 vs 42\");\n\n  ASSERT_EQ(kCaseA, kCaseA);\n  ASSERT_NE(kCaseA, kCaseB);\n  ASSERT_LT(kCaseA, kCaseB);\n  ASSERT_LE(kCaseA, kCaseB);\n  ASSERT_GT(kCaseB, kCaseA);\n  ASSERT_GE(kCaseA, kCaseA);\n\n#ifndef __BORLANDC__\n\n  // ICE's in C++Builder.\n  EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseB), \"  kCaseB\\n    Which is: \");\n  EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), \"\\n    Which is: 42\");\n#endif\n\n  EXPECT_FATAL_FAILURE(ASSERT_EQ(kCaseA, kCaseC), \"\\n    Which is: -1\");\n}\n\n#endif  // !GTEST_OS_MAC && !defined(__SUNPRO_CC)\n\n#if GTEST_OS_WINDOWS\n\nstatic HRESULT UnexpectedHRESULTFailure() { return E_UNEXPECTED; }\n\nstatic HRESULT OkHRESULTSuccess() { return S_OK; }\n\nstatic HRESULT FalseHRESULTSuccess() { return S_FALSE; }\n\n// HRESULT assertion tests test both zero and non-zero\n// success codes as well as failure message for each.\n//\n// Windows CE doesn't support message texts.\nTEST(HRESULTAssertionTest, EXPECT_HRESULT_SUCCEEDED) {\n  EXPECT_HRESULT_SUCCEEDED(S_OK);\n  EXPECT_HRESULT_SUCCEEDED(S_FALSE);\n\n  EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),\n                          \"Expected: (UnexpectedHRESULTFailure()) succeeds.\\n\"\n                          \"  Actual: 0x8000FFFF\");\n}\n\nTEST(HRESULTAssertionTest, ASSERT_HRESULT_SUCCEEDED) {\n  ASSERT_HRESULT_SUCCEEDED(S_OK);\n  ASSERT_HRESULT_SUCCEEDED(S_FALSE);\n\n  EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(UnexpectedHRESULTFailure()),\n                       \"Expected: (UnexpectedHRESULTFailure()) succeeds.\\n\"\n                       \"  Actual: 0x8000FFFF\");\n}\n\nTEST(HRESULTAssertionTest, EXPECT_HRESULT_FAILED) {\n  EXPECT_HRESULT_FAILED(E_UNEXPECTED);\n\n  EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(OkHRESULTSuccess()),\n                          \"Expected: (OkHRESULTSuccess()) fails.\\n\"\n                          \"  Actual: 0x0\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(FalseHRESULTSuccess()),\n                          \"Expected: (FalseHRESULTSuccess()) fails.\\n\"\n                          \"  Actual: 0x1\");\n}\n\nTEST(HRESULTAssertionTest, ASSERT_HRESULT_FAILED) {\n  ASSERT_HRESULT_FAILED(E_UNEXPECTED);\n\n#ifndef __BORLANDC__\n\n  // ICE's in C++Builder 2007 and 2009.\n  EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(OkHRESULTSuccess()),\n                       \"Expected: (OkHRESULTSuccess()) fails.\\n\"\n                       \"  Actual: 0x0\");\n#endif\n\n  EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(FalseHRESULTSuccess()),\n                       \"Expected: (FalseHRESULTSuccess()) fails.\\n\"\n                       \"  Actual: 0x1\");\n}\n\n// Tests that streaming to the HRESULT macros works.\nTEST(HRESULTAssertionTest, Streaming) {\n  EXPECT_HRESULT_SUCCEEDED(S_OK) << \"unexpected failure\";\n  ASSERT_HRESULT_SUCCEEDED(S_OK) << \"unexpected failure\";\n  EXPECT_HRESULT_FAILED(E_UNEXPECTED) << \"unexpected failure\";\n  ASSERT_HRESULT_FAILED(E_UNEXPECTED) << \"unexpected failure\";\n\n  EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_SUCCEEDED(E_UNEXPECTED)\n                              << \"expected failure\",\n                          \"expected failure\");\n\n#ifndef __BORLANDC__\n\n  // ICE's in C++Builder 2007 and 2009.\n  EXPECT_FATAL_FAILURE(ASSERT_HRESULT_SUCCEEDED(E_UNEXPECTED)\n                           << \"expected failure\",\n                       \"expected failure\");\n#endif\n\n  EXPECT_NONFATAL_FAILURE(EXPECT_HRESULT_FAILED(S_OK) << \"expected failure\",\n                          \"expected failure\");\n\n  EXPECT_FATAL_FAILURE(ASSERT_HRESULT_FAILED(S_OK) << \"expected failure\",\n                       \"expected failure\");\n}\n\n#endif  // GTEST_OS_WINDOWS\n\n// The following code intentionally tests a suboptimal syntax.\n#ifdef __GNUC__\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wdangling-else\"\n#pragma GCC diagnostic ignored \"-Wempty-body\"\n#pragma GCC diagnostic ignored \"-Wpragmas\"\n#endif\n// Tests that the assertion macros behave like single statements.\nTEST(AssertionSyntaxTest, BasicAssertionsBehavesLikeSingleStatement) {\n  if (AlwaysFalse())\n    ASSERT_TRUE(false) << \"This should never be executed; \"\n                          \"It's a compilation test only.\";\n\n  if (AlwaysTrue())\n    EXPECT_FALSE(false);\n  else\n    ;  // NOLINT\n\n  if (AlwaysFalse()) ASSERT_LT(1, 3);\n\n  if (AlwaysFalse())\n    ;  // NOLINT\n  else\n    EXPECT_GT(3, 2) << \"\";\n}\n#ifdef __GNUC__\n#pragma GCC diagnostic pop\n#endif\n\n#if GTEST_HAS_EXCEPTIONS\n// Tests that the compiler will not complain about unreachable code in the\n// EXPECT_THROW/EXPECT_ANY_THROW/EXPECT_NO_THROW macros.\nTEST(ExpectThrowTest, DoesNotGenerateUnreachableCodeWarning) {\n  int n = 0;\n\n  EXPECT_THROW(throw 1, int);\n  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(n++, int), \"\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(throw 1, const char*), \"\");\n  EXPECT_NO_THROW(n++);\n  EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(throw 1), \"\");\n  EXPECT_ANY_THROW(throw 1);\n  EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(n++), \"\");\n}\n\nTEST(ExpectThrowTest, DoesNotGenerateDuplicateCatchClauseWarning) {\n  EXPECT_THROW(throw std::exception(), std::exception);\n}\n\n// The following code intentionally tests a suboptimal syntax.\n#ifdef __GNUC__\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wdangling-else\"\n#pragma GCC diagnostic ignored \"-Wempty-body\"\n#pragma GCC diagnostic ignored \"-Wpragmas\"\n#endif\nTEST(AssertionSyntaxTest, ExceptionAssertionsBehavesLikeSingleStatement) {\n  if (AlwaysFalse()) EXPECT_THROW(ThrowNothing(), bool);\n\n  if (AlwaysTrue())\n    EXPECT_THROW(ThrowAnInteger(), int);\n  else\n    ;  // NOLINT\n\n  if (AlwaysFalse()) EXPECT_NO_THROW(ThrowAnInteger());\n\n  if (AlwaysTrue())\n    EXPECT_NO_THROW(ThrowNothing());\n  else\n    ;  // NOLINT\n\n  if (AlwaysFalse()) EXPECT_ANY_THROW(ThrowNothing());\n\n  if (AlwaysTrue())\n    EXPECT_ANY_THROW(ThrowAnInteger());\n  else\n    ;  // NOLINT\n}\n#ifdef __GNUC__\n#pragma GCC diagnostic pop\n#endif\n\n#endif  // GTEST_HAS_EXCEPTIONS\n\n// The following code intentionally tests a suboptimal syntax.\n#ifdef __GNUC__\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wdangling-else\"\n#pragma GCC diagnostic ignored \"-Wempty-body\"\n#pragma GCC diagnostic ignored \"-Wpragmas\"\n#endif\nTEST(AssertionSyntaxTest, NoFatalFailureAssertionsBehavesLikeSingleStatement) {\n  if (AlwaysFalse())\n    EXPECT_NO_FATAL_FAILURE(FAIL()) << \"This should never be executed. \"\n                                    << \"It's a compilation test only.\";\n  else\n    ;  // NOLINT\n\n  if (AlwaysFalse())\n    ASSERT_NO_FATAL_FAILURE(FAIL()) << \"\";\n  else\n    ;  // NOLINT\n\n  if (AlwaysTrue())\n    EXPECT_NO_FATAL_FAILURE(SUCCEED());\n  else\n    ;  // NOLINT\n\n  if (AlwaysFalse())\n    ;  // NOLINT\n  else\n    ASSERT_NO_FATAL_FAILURE(SUCCEED());\n}\n#ifdef __GNUC__\n#pragma GCC diagnostic pop\n#endif\n\n// Tests that the assertion macros work well with switch statements.\nTEST(AssertionSyntaxTest, WorksWithSwitch) {\n  switch (0) {\n    case 1:\n      break;\n    default:\n      ASSERT_TRUE(true);\n  }\n\n  switch (0)\n  case 0:\n    EXPECT_FALSE(false) << \"EXPECT_FALSE failed in switch case\";\n\n  // Binary assertions are implemented using a different code path\n  // than the Boolean assertions.  Hence we test them separately.\n  switch (0) {\n    case 1:\n    default:\n      ASSERT_EQ(1, 1) << \"ASSERT_EQ failed in default switch handler\";\n  }\n\n  switch (0)\n  case 0:\n    EXPECT_NE(1, 2);\n}\n\n#if GTEST_HAS_EXCEPTIONS\n\nvoid ThrowAString() { throw \"std::string\"; }\n\n// Test that the exception assertion macros compile and work with const\n// type qualifier.\nTEST(AssertionSyntaxTest, WorksWithConst) {\n  ASSERT_THROW(ThrowAString(), const char*);\n\n  EXPECT_THROW(ThrowAString(), const char*);\n}\n\n#endif  // GTEST_HAS_EXCEPTIONS\n\n}  // namespace\n\nnamespace testing {\n\n// Tests that Google Test tracks SUCCEED*.\nTEST(SuccessfulAssertionTest, SUCCEED) {\n  SUCCEED();\n  SUCCEED() << \"OK\";\n  EXPECT_EQ(2, GetUnitTestImpl()->current_test_result()->total_part_count());\n}\n\n// Tests that Google Test doesn't track successful EXPECT_*.\nTEST(SuccessfulAssertionTest, EXPECT) {\n  EXPECT_TRUE(true);\n  EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());\n}\n\n// Tests that Google Test doesn't track successful EXPECT_STR*.\nTEST(SuccessfulAssertionTest, EXPECT_STR) {\n  EXPECT_STREQ(\"\", \"\");\n  EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());\n}\n\n// Tests that Google Test doesn't track successful ASSERT_*.\nTEST(SuccessfulAssertionTest, ASSERT) {\n  ASSERT_TRUE(true);\n  EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());\n}\n\n// Tests that Google Test doesn't track successful ASSERT_STR*.\nTEST(SuccessfulAssertionTest, ASSERT_STR) {\n  ASSERT_STREQ(\"\", \"\");\n  EXPECT_EQ(0, GetUnitTestImpl()->current_test_result()->total_part_count());\n}\n\n}  // namespace testing\n\nnamespace {\n\n// Tests the message streaming variation of assertions.\n\nTEST(AssertionWithMessageTest, EXPECT) {\n  EXPECT_EQ(1, 1) << \"This should succeed.\";\n  EXPECT_NONFATAL_FAILURE(EXPECT_NE(1, 1) << \"Expected failure #1.\",\n                          \"Expected failure #1\");\n  EXPECT_LE(1, 2) << \"This should succeed.\";\n  EXPECT_NONFATAL_FAILURE(EXPECT_LT(1, 0) << \"Expected failure #2.\",\n                          \"Expected failure #2.\");\n  EXPECT_GE(1, 0) << \"This should succeed.\";\n  EXPECT_NONFATAL_FAILURE(EXPECT_GT(1, 2) << \"Expected failure #3.\",\n                          \"Expected failure #3.\");\n\n  EXPECT_STREQ(\"1\", \"1\") << \"This should succeed.\";\n  EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(\"1\", \"1\") << \"Expected failure #4.\",\n                          \"Expected failure #4.\");\n  EXPECT_STRCASEEQ(\"a\", \"A\") << \"This should succeed.\";\n  EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE(\"a\", \"A\") << \"Expected failure #5.\",\n                          \"Expected failure #5.\");\n\n  EXPECT_FLOAT_EQ(1, 1) << \"This should succeed.\";\n  EXPECT_NONFATAL_FAILURE(EXPECT_DOUBLE_EQ(1, 1.2) << \"Expected failure #6.\",\n                          \"Expected failure #6.\");\n  EXPECT_NEAR(1, 1.1, 0.2) << \"This should succeed.\";\n}\n\nTEST(AssertionWithMessageTest, ASSERT) {\n  ASSERT_EQ(1, 1) << \"This should succeed.\";\n  ASSERT_NE(1, 2) << \"This should succeed.\";\n  ASSERT_LE(1, 2) << \"This should succeed.\";\n  ASSERT_LT(1, 2) << \"This should succeed.\";\n  ASSERT_GE(1, 0) << \"This should succeed.\";\n  EXPECT_FATAL_FAILURE(ASSERT_GT(1, 2) << \"Expected failure.\",\n                       \"Expected failure.\");\n}\n\nTEST(AssertionWithMessageTest, ASSERT_STR) {\n  ASSERT_STREQ(\"1\", \"1\") << \"This should succeed.\";\n  ASSERT_STRNE(\"1\", \"2\") << \"This should succeed.\";\n  ASSERT_STRCASEEQ(\"a\", \"A\") << \"This should succeed.\";\n  EXPECT_FATAL_FAILURE(ASSERT_STRCASENE(\"a\", \"A\") << \"Expected failure.\",\n                       \"Expected failure.\");\n}\n\nTEST(AssertionWithMessageTest, ASSERT_FLOATING) {\n  ASSERT_FLOAT_EQ(1, 1) << \"This should succeed.\";\n  ASSERT_DOUBLE_EQ(1, 1) << \"This should succeed.\";\n  EXPECT_FATAL_FAILURE(ASSERT_NEAR(1, 1.2, 0.1) << \"Expect failure.\",  // NOLINT\n                       \"Expect failure.\");\n}\n\n// Tests using ASSERT_FALSE with a streamed message.\nTEST(AssertionWithMessageTest, ASSERT_FALSE) {\n  ASSERT_FALSE(false) << \"This shouldn't fail.\";\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_FALSE(true) << \"Expected failure: \" << 2 << \" > \" << 1\n                           << \" evaluates to \" << true;\n      },\n      \"Expected failure\");\n}\n\n// Tests using FAIL with a streamed message.\nTEST(AssertionWithMessageTest, FAIL) { EXPECT_FATAL_FAILURE(FAIL() << 0, \"0\"); }\n\n// Tests using SUCCEED with a streamed message.\nTEST(AssertionWithMessageTest, SUCCEED) { SUCCEED() << \"Success == \" << 1; }\n\n// Tests using ASSERT_TRUE with a streamed message.\nTEST(AssertionWithMessageTest, ASSERT_TRUE) {\n  ASSERT_TRUE(true) << \"This should succeed.\";\n  ASSERT_TRUE(true) << true;\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_TRUE(false) << static_cast<const char*>(nullptr)\n                           << static_cast<char*>(nullptr);\n      },\n      \"(null)(null)\");\n}\n\n#if GTEST_OS_WINDOWS\n// Tests using wide strings in assertion messages.\nTEST(AssertionWithMessageTest, WideStringMessage) {\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_TRUE(false) << L\"This failure is expected.\\x8119\";\n      },\n      \"This failure is expected.\");\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_EQ(1, 2) << \"This failure is \" << L\"expected too.\\x8120\";\n      },\n      \"This failure is expected too.\");\n}\n#endif  // GTEST_OS_WINDOWS\n\n// Tests EXPECT_TRUE.\nTEST(ExpectTest, EXPECT_TRUE) {\n  EXPECT_TRUE(true) << \"Intentional success\";\n  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << \"Intentional failure #1.\",\n                          \"Intentional failure #1.\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << \"Intentional failure #2.\",\n                          \"Intentional failure #2.\");\n  EXPECT_TRUE(2 > 1);  // NOLINT\n  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 < 1),\n                          \"Value of: 2 < 1\\n\"\n                          \"  Actual: false\\n\"\n                          \"Expected: true\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(2 > 3), \"2 > 3\");\n}\n\n// Tests EXPECT_TRUE(predicate) for predicates returning AssertionResult.\nTEST(ExpectTest, ExpectTrueWithAssertionResult) {\n  EXPECT_TRUE(ResultIsEven(2));\n  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEven(3)),\n                          \"Value of: ResultIsEven(3)\\n\"\n                          \"  Actual: false (3 is odd)\\n\"\n                          \"Expected: true\");\n  EXPECT_TRUE(ResultIsEvenNoExplanation(2));\n  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(ResultIsEvenNoExplanation(3)),\n                          \"Value of: ResultIsEvenNoExplanation(3)\\n\"\n                          \"  Actual: false (3 is odd)\\n\"\n                          \"Expected: true\");\n}\n\n// Tests EXPECT_FALSE with a streamed message.\nTEST(ExpectTest, EXPECT_FALSE) {\n  EXPECT_FALSE(2 < 1);  // NOLINT\n  EXPECT_FALSE(false) << \"Intentional success\";\n  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << \"Intentional failure #1.\",\n                          \"Intentional failure #1.\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << \"Intentional failure #2.\",\n                          \"Intentional failure #2.\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 > 1),\n                          \"Value of: 2 > 1\\n\"\n                          \"  Actual: true\\n\"\n                          \"Expected: false\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(2 < 3), \"2 < 3\");\n}\n\n// Tests EXPECT_FALSE(predicate) for predicates returning AssertionResult.\nTEST(ExpectTest, ExpectFalseWithAssertionResult) {\n  EXPECT_FALSE(ResultIsEven(3));\n  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEven(2)),\n                          \"Value of: ResultIsEven(2)\\n\"\n                          \"  Actual: true (2 is even)\\n\"\n                          \"Expected: false\");\n  EXPECT_FALSE(ResultIsEvenNoExplanation(3));\n  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(ResultIsEvenNoExplanation(2)),\n                          \"Value of: ResultIsEvenNoExplanation(2)\\n\"\n                          \"  Actual: true\\n\"\n                          \"Expected: false\");\n}\n\n#ifdef __BORLANDC__\n// Restores warnings after previous \"#pragma option push\" suppressed them\n#pragma option pop\n#endif\n\n// Tests EXPECT_EQ.\nTEST(ExpectTest, EXPECT_EQ) {\n  EXPECT_EQ(5, 2 + 3);\n  // clang-format off\n  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2*3),\n                          \"Expected equality of these values:\\n\"\n                          \"  5\\n\"\n                          \"  2*3\\n\"\n                          \"    Which is: 6\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5, 2 - 3), \"2 - 3\");\n  // clang-format on\n}\n\n// Tests using EXPECT_EQ on double values.  The purpose is to make\n// sure that the specialization we did for integer and anonymous enums\n// isn't used for double arguments.\nTEST(ExpectTest, EXPECT_EQ_Double) {\n  // A success.\n  EXPECT_EQ(5.6, 5.6);\n\n  // A failure.\n  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(5.1, 5.2), \"5.1\");\n}\n\n// Tests EXPECT_EQ(NULL, pointer).\nTEST(ExpectTest, EXPECT_EQ_NULL) {\n  // A success.\n  const char* p = nullptr;\n  EXPECT_EQ(nullptr, p);\n\n  // A failure.\n  int n = 0;\n  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(nullptr, &n), \"  &n\\n    Which is:\");\n}\n\n// Tests EXPECT_EQ(0, non_pointer).  Since the literal 0 can be\n// treated as a null pointer by the compiler, we need to make sure\n// that EXPECT_EQ(0, non_pointer) isn't interpreted by Google Test as\n// EXPECT_EQ(static_cast<void*>(NULL), non_pointer).\nTEST(ExpectTest, EXPECT_EQ_0) {\n  int n = 0;\n\n  // A success.\n  EXPECT_EQ(0, n);\n\n  // A failure.\n  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(0, 5.6), \"  0\\n  5.6\");\n}\n\n// Tests EXPECT_NE.\nTEST(ExpectTest, EXPECT_NE) {\n  EXPECT_NE(6, 7);\n\n  EXPECT_NONFATAL_FAILURE(EXPECT_NE('a', 'a'),\n                          \"Expected: ('a') != ('a'), \"\n                          \"actual: 'a' (97, 0x61) vs 'a' (97, 0x61)\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_NE(2, 2), \"2\");\n  char* const p0 = nullptr;\n  EXPECT_NONFATAL_FAILURE(EXPECT_NE(p0, p0), \"p0\");\n  // Only way to get the Nokia compiler to compile the cast\n  // is to have a separate void* variable first. Putting\n  // the two casts on the same line doesn't work, neither does\n  // a direct C-style to char*.\n  void* pv1 = (void*)0x1234;  // NOLINT\n  char* const p1 = reinterpret_cast<char*>(pv1);\n  EXPECT_NONFATAL_FAILURE(EXPECT_NE(p1, p1), \"p1\");\n}\n\n// Tests EXPECT_LE.\nTEST(ExpectTest, EXPECT_LE) {\n  EXPECT_LE(2, 3);\n  EXPECT_LE(2, 2);\n  EXPECT_NONFATAL_FAILURE(EXPECT_LE(2, 0),\n                          \"Expected: (2) <= (0), actual: 2 vs 0\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_LE(1.1, 0.9), \"(1.1) <= (0.9)\");\n}\n\n// Tests EXPECT_LT.\nTEST(ExpectTest, EXPECT_LT) {\n  EXPECT_LT(2, 3);\n  EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 2),\n                          \"Expected: (2) < (2), actual: 2 vs 2\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1), \"(2) < (1)\");\n}\n\n// Tests EXPECT_GE.\nTEST(ExpectTest, EXPECT_GE) {\n  EXPECT_GE(2, 1);\n  EXPECT_GE(2, 2);\n  EXPECT_NONFATAL_FAILURE(EXPECT_GE(2, 3),\n                          \"Expected: (2) >= (3), actual: 2 vs 3\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_GE(0.9, 1.1), \"(0.9) >= (1.1)\");\n}\n\n// Tests EXPECT_GT.\nTEST(ExpectTest, EXPECT_GT) {\n  EXPECT_GT(2, 1);\n  EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 2),\n                          \"Expected: (2) > (2), actual: 2 vs 2\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_GT(2, 3), \"(2) > (3)\");\n}\n\n#if GTEST_HAS_EXCEPTIONS\n\n// Tests EXPECT_THROW.\nTEST(ExpectTest, EXPECT_THROW) {\n  EXPECT_THROW(ThrowAnInteger(), int);\n  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool),\n                          \"Expected: ThrowAnInteger() throws an exception of \"\n                          \"type bool.\\n  Actual: it throws a different type.\");\n  EXPECT_NONFATAL_FAILURE(\n      EXPECT_THROW(ThrowRuntimeError(\"A description\"), std::logic_error),\n      \"Expected: ThrowRuntimeError(\\\"A description\\\") \"\n      \"throws an exception of type std::logic_error.\\n  \"\n      \"Actual: it throws \" ERROR_DESC\n      \" \"\n      \"with description \\\"A description\\\".\");\n  EXPECT_NONFATAL_FAILURE(\n      EXPECT_THROW(ThrowNothing(), bool),\n      \"Expected: ThrowNothing() throws an exception of type bool.\\n\"\n      \"  Actual: it throws nothing.\");\n}\n\n// Tests EXPECT_NO_THROW.\nTEST(ExpectTest, EXPECT_NO_THROW) {\n  EXPECT_NO_THROW(ThrowNothing());\n  EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger()),\n                          \"Expected: ThrowAnInteger() doesn't throw an \"\n                          \"exception.\\n  Actual: it throws.\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowRuntimeError(\"A description\")),\n                          \"Expected: ThrowRuntimeError(\\\"A description\\\") \"\n                          \"doesn't throw an exception.\\n  \"\n                          \"Actual: it throws \" ERROR_DESC\n                          \" \"\n                          \"with description \\\"A description\\\".\");\n}\n\n// Tests EXPECT_ANY_THROW.\nTEST(ExpectTest, EXPECT_ANY_THROW) {\n  EXPECT_ANY_THROW(ThrowAnInteger());\n  EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing()),\n                          \"Expected: ThrowNothing() throws an exception.\\n\"\n                          \"  Actual: it doesn't.\");\n}\n\n#endif  // GTEST_HAS_EXCEPTIONS\n\n// Make sure we deal with the precedence of <<.\nTEST(ExpectTest, ExpectPrecedence) {\n  EXPECT_EQ(1 < 2, true);\n  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(true, true && false),\n                          \"  true && false\\n    Which is: false\");\n}\n\n// Tests the StreamableToString() function.\n\n// Tests using StreamableToString() on a scalar.\nTEST(StreamableToStringTest, Scalar) {\n  EXPECT_STREQ(\"5\", StreamableToString(5).c_str());\n}\n\n// Tests using StreamableToString() on a non-char pointer.\nTEST(StreamableToStringTest, Pointer) {\n  int n = 0;\n  int* p = &n;\n  EXPECT_STRNE(\"(null)\", StreamableToString(p).c_str());\n}\n\n// Tests using StreamableToString() on a NULL non-char pointer.\nTEST(StreamableToStringTest, NullPointer) {\n  int* p = nullptr;\n  EXPECT_STREQ(\"(null)\", StreamableToString(p).c_str());\n}\n\n// Tests using StreamableToString() on a C string.\nTEST(StreamableToStringTest, CString) {\n  EXPECT_STREQ(\"Foo\", StreamableToString(\"Foo\").c_str());\n}\n\n// Tests using StreamableToString() on a NULL C string.\nTEST(StreamableToStringTest, NullCString) {\n  char* p = nullptr;\n  EXPECT_STREQ(\"(null)\", StreamableToString(p).c_str());\n}\n\n// Tests using streamable values as assertion messages.\n\n// Tests using std::string as an assertion message.\nTEST(StreamableTest, string) {\n  static const std::string str(\n      \"This failure message is a std::string, and is expected.\");\n  EXPECT_FATAL_FAILURE(FAIL() << str, str.c_str());\n}\n\n// Tests that we can output strings containing embedded NULs.\n// Limited to Linux because we can only do this with std::string's.\nTEST(StreamableTest, stringWithEmbeddedNUL) {\n  static const char char_array_with_nul[] =\n      \"Here's a NUL\\0 and some more string\";\n  static const std::string string_with_nul(\n      char_array_with_nul,\n      sizeof(char_array_with_nul) - 1);  // drops the trailing NUL\n  EXPECT_FATAL_FAILURE(FAIL() << string_with_nul,\n                       \"Here's a NUL\\\\0 and some more string\");\n}\n\n// Tests that we can output a NUL char.\nTEST(StreamableTest, NULChar) {\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        FAIL() << \"A NUL\" << '\\0' << \" and some more string\";\n      },\n      \"A NUL\\\\0 and some more string\");\n}\n\n// Tests using int as an assertion message.\nTEST(StreamableTest, int) { EXPECT_FATAL_FAILURE(FAIL() << 900913, \"900913\"); }\n\n// Tests using NULL char pointer as an assertion message.\n//\n// In MSVC, streaming a NULL char * causes access violation.  Google Test\n// implemented a workaround (substituting \"(null)\" for NULL).  This\n// tests whether the workaround works.\nTEST(StreamableTest, NullCharPtr) {\n  EXPECT_FATAL_FAILURE(FAIL() << static_cast<const char*>(nullptr), \"(null)\");\n}\n\n// Tests that basic IO manipulators (endl, ends, and flush) can be\n// streamed to testing::Message.\nTEST(StreamableTest, BasicIoManip) {\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        FAIL() << \"Line 1.\" << std::endl\n               << \"A NUL char \" << std::ends << std::flush << \" in line 2.\";\n      },\n      \"Line 1.\\nA NUL char \\\\0 in line 2.\");\n}\n\n// Tests the macros that haven't been covered so far.\n\nvoid AddFailureHelper(bool* aborted) {\n  *aborted = true;\n  ADD_FAILURE() << \"Intentional failure.\";\n  *aborted = false;\n}\n\n// Tests ADD_FAILURE.\nTEST(MacroTest, ADD_FAILURE) {\n  bool aborted = true;\n  EXPECT_NONFATAL_FAILURE(AddFailureHelper(&aborted), \"Intentional failure.\");\n  EXPECT_FALSE(aborted);\n}\n\n// Tests ADD_FAILURE_AT.\nTEST(MacroTest, ADD_FAILURE_AT) {\n  // Verifies that ADD_FAILURE_AT does generate a nonfatal failure and\n  // the failure message contains the user-streamed part.\n  EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT(\"foo.cc\", 42) << \"Wrong!\", \"Wrong!\");\n\n  // Verifies that the user-streamed part is optional.\n  EXPECT_NONFATAL_FAILURE(ADD_FAILURE_AT(\"foo.cc\", 42), \"Failed\");\n\n  // Unfortunately, we cannot verify that the failure message contains\n  // the right file path and line number the same way, as\n  // EXPECT_NONFATAL_FAILURE() doesn't get to see the file path and\n  // line number.  Instead, we do that in googletest-output-test_.cc.\n}\n\n// Tests FAIL.\nTEST(MacroTest, FAIL) {\n  EXPECT_FATAL_FAILURE(FAIL(), \"Failed\");\n  EXPECT_FATAL_FAILURE(FAIL() << \"Intentional failure.\",\n                       \"Intentional failure.\");\n}\n\n// Tests GTEST_FAIL_AT.\nTEST(MacroTest, GTEST_FAIL_AT) {\n  // Verifies that GTEST_FAIL_AT does generate a fatal failure and\n  // the failure message contains the user-streamed part.\n  EXPECT_FATAL_FAILURE(GTEST_FAIL_AT(\"foo.cc\", 42) << \"Wrong!\", \"Wrong!\");\n\n  // Verifies that the user-streamed part is optional.\n  EXPECT_FATAL_FAILURE(GTEST_FAIL_AT(\"foo.cc\", 42), \"Failed\");\n\n  // See the ADD_FAIL_AT test above to see how we test that the failure message\n  // contains the right filename and line number -- the same applies here.\n}\n\n// Tests SUCCEED\nTEST(MacroTest, SUCCEED) {\n  SUCCEED();\n  SUCCEED() << \"Explicit success.\";\n}\n\n// Tests for EXPECT_EQ() and ASSERT_EQ().\n//\n// These tests fail *intentionally*, s.t. the failure messages can be\n// generated and tested.\n//\n// We have different tests for different argument types.\n\n// Tests using bool values in {EXPECT|ASSERT}_EQ.\nTEST(EqAssertionTest, Bool) {\n  EXPECT_EQ(true, true);\n  EXPECT_FATAL_FAILURE(\n      {\n        bool false_value = false;\n        ASSERT_EQ(false_value, true);\n      },\n      \"  false_value\\n    Which is: false\\n  true\");\n}\n\n// Tests using int values in {EXPECT|ASSERT}_EQ.\nTEST(EqAssertionTest, Int) {\n  ASSERT_EQ(32, 32);\n  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(32, 33), \"  32\\n  33\");\n}\n\n// Tests using time_t values in {EXPECT|ASSERT}_EQ.\nTEST(EqAssertionTest, Time_T) {\n  EXPECT_EQ(static_cast<time_t>(0), static_cast<time_t>(0));\n  EXPECT_FATAL_FAILURE(\n      ASSERT_EQ(static_cast<time_t>(0), static_cast<time_t>(1234)), \"1234\");\n}\n\n// Tests using char values in {EXPECT|ASSERT}_EQ.\nTEST(EqAssertionTest, Char) {\n  ASSERT_EQ('z', 'z');\n  const char ch = 'b';\n  EXPECT_NONFATAL_FAILURE(EXPECT_EQ('\\0', ch), \"  ch\\n    Which is: 'b'\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_EQ('a', ch), \"  ch\\n    Which is: 'b'\");\n}\n\n// Tests using wchar_t values in {EXPECT|ASSERT}_EQ.\nTEST(EqAssertionTest, WideChar) {\n  EXPECT_EQ(L'b', L'b');\n\n  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'\\0', L'x'),\n                          \"Expected equality of these values:\\n\"\n                          \"  L'\\0'\\n\"\n                          \"    Which is: L'\\0' (0, 0x0)\\n\"\n                          \"  L'x'\\n\"\n                          \"    Which is: L'x' (120, 0x78)\");\n\n  static wchar_t wchar;\n  wchar = L'b';\n  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(L'a', wchar), \"wchar\");\n  wchar = 0x8119;\n  EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<wchar_t>(0x8120), wchar),\n                       \"  wchar\\n    Which is: L'\");\n}\n\n// Tests using ::std::string values in {EXPECT|ASSERT}_EQ.\nTEST(EqAssertionTest, StdString) {\n  // Compares a const char* to an std::string that has identical\n  // content.\n  ASSERT_EQ(\"Test\", ::std::string(\"Test\"));\n\n  // Compares two identical std::strings.\n  static const ::std::string str1(\"A * in the middle\");\n  static const ::std::string str2(str1);\n  EXPECT_EQ(str1, str2);\n\n  // Compares a const char* to an std::string that has different\n  // content\n  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(\"Test\", ::std::string(\"test\")), \"\\\"test\\\"\");\n\n  // Compares an std::string to a char* that has different content.\n  char* const p1 = const_cast<char*>(\"foo\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(::std::string(\"bar\"), p1), \"p1\");\n\n  // Compares two std::strings that have different contents, one of\n  // which having a NUL character in the middle.  This should fail.\n  static ::std::string str3(str1);\n  str3.at(2) = '\\0';\n  EXPECT_FATAL_FAILURE(ASSERT_EQ(str1, str3),\n                       \"  str3\\n    Which is: \\\"A \\\\0 in the middle\\\"\");\n}\n\n#if GTEST_HAS_STD_WSTRING\n\n// Tests using ::std::wstring values in {EXPECT|ASSERT}_EQ.\nTEST(EqAssertionTest, StdWideString) {\n  // Compares two identical std::wstrings.\n  const ::std::wstring wstr1(L\"A * in the middle\");\n  const ::std::wstring wstr2(wstr1);\n  ASSERT_EQ(wstr1, wstr2);\n\n  // Compares an std::wstring to a const wchar_t* that has identical\n  // content.\n  const wchar_t kTestX8119[] = {'T', 'e', 's', 't', 0x8119, '\\0'};\n  EXPECT_EQ(::std::wstring(kTestX8119), kTestX8119);\n\n  // Compares an std::wstring to a const wchar_t* that has different\n  // content.\n  const wchar_t kTestX8120[] = {'T', 'e', 's', 't', 0x8120, '\\0'};\n  EXPECT_NONFATAL_FAILURE(\n      {  // NOLINT\n        EXPECT_EQ(::std::wstring(kTestX8119), kTestX8120);\n      },\n      \"kTestX8120\");\n\n  // Compares two std::wstrings that have different contents, one of\n  // which having a NUL character in the middle.\n  ::std::wstring wstr3(wstr1);\n  wstr3.at(2) = L'\\0';\n  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(wstr1, wstr3), \"wstr3\");\n\n  // Compares a wchar_t* to an std::wstring that has different\n  // content.\n  EXPECT_FATAL_FAILURE(\n      {  // NOLINT\n        ASSERT_EQ(const_cast<wchar_t*>(L\"foo\"), ::std::wstring(L\"bar\"));\n      },\n      \"\");\n}\n\n#endif  // GTEST_HAS_STD_WSTRING\n\n// Tests using char pointers in {EXPECT|ASSERT}_EQ.\nTEST(EqAssertionTest, CharPointer) {\n  char* const p0 = nullptr;\n  // Only way to get the Nokia compiler to compile the cast\n  // is to have a separate void* variable first. Putting\n  // the two casts on the same line doesn't work, neither does\n  // a direct C-style to char*.\n  void* pv1 = (void*)0x1234;  // NOLINT\n  void* pv2 = (void*)0xABC0;  // NOLINT\n  char* const p1 = reinterpret_cast<char*>(pv1);\n  char* const p2 = reinterpret_cast<char*>(pv2);\n  ASSERT_EQ(p1, p1);\n\n  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), \"  p2\\n    Which is:\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), \"  p2\\n    Which is:\");\n  EXPECT_FATAL_FAILURE(ASSERT_EQ(reinterpret_cast<char*>(0x1234),\n                                 reinterpret_cast<char*>(0xABC0)),\n                       \"ABC0\");\n}\n\n// Tests using wchar_t pointers in {EXPECT|ASSERT}_EQ.\nTEST(EqAssertionTest, WideCharPointer) {\n  wchar_t* const p0 = nullptr;\n  // Only way to get the Nokia compiler to compile the cast\n  // is to have a separate void* variable first. Putting\n  // the two casts on the same line doesn't work, neither does\n  // a direct C-style to char*.\n  void* pv1 = (void*)0x1234;  // NOLINT\n  void* pv2 = (void*)0xABC0;  // NOLINT\n  wchar_t* const p1 = reinterpret_cast<wchar_t*>(pv1);\n  wchar_t* const p2 = reinterpret_cast<wchar_t*>(pv2);\n  EXPECT_EQ(p0, p0);\n\n  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p0, p2), \"  p2\\n    Which is:\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p1, p2), \"  p2\\n    Which is:\");\n  void* pv3 = (void*)0x1234;  // NOLINT\n  void* pv4 = (void*)0xABC0;  // NOLINT\n  const wchar_t* p3 = reinterpret_cast<const wchar_t*>(pv3);\n  const wchar_t* p4 = reinterpret_cast<const wchar_t*>(pv4);\n  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(p3, p4), \"p4\");\n}\n\n// Tests using other types of pointers in {EXPECT|ASSERT}_EQ.\nTEST(EqAssertionTest, OtherPointer) {\n  ASSERT_EQ(static_cast<const int*>(nullptr), static_cast<const int*>(nullptr));\n  EXPECT_FATAL_FAILURE(ASSERT_EQ(static_cast<const int*>(nullptr),\n                                 reinterpret_cast<const int*>(0x1234)),\n                       \"0x1234\");\n}\n\n// A class that supports binary comparison operators but not streaming.\nclass UnprintableChar {\n public:\n  explicit UnprintableChar(char ch) : char_(ch) {}\n\n  bool operator==(const UnprintableChar& rhs) const {\n    return char_ == rhs.char_;\n  }\n  bool operator!=(const UnprintableChar& rhs) const {\n    return char_ != rhs.char_;\n  }\n  bool operator<(const UnprintableChar& rhs) const { return char_ < rhs.char_; }\n  bool operator<=(const UnprintableChar& rhs) const {\n    return char_ <= rhs.char_;\n  }\n  bool operator>(const UnprintableChar& rhs) const { return char_ > rhs.char_; }\n  bool operator>=(const UnprintableChar& rhs) const {\n    return char_ >= rhs.char_;\n  }\n\n private:\n  char char_;\n};\n\n// Tests that ASSERT_EQ() and friends don't require the arguments to\n// be printable.\nTEST(ComparisonAssertionTest, AcceptsUnprintableArgs) {\n  const UnprintableChar x('x'), y('y');\n  ASSERT_EQ(x, x);\n  EXPECT_NE(x, y);\n  ASSERT_LT(x, y);\n  EXPECT_LE(x, y);\n  ASSERT_GT(y, x);\n  EXPECT_GE(x, x);\n\n  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), \"1-byte object <78>\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(x, y), \"1-byte object <79>\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_LT(y, y), \"1-byte object <79>\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), \"1-byte object <78>\");\n  EXPECT_NONFATAL_FAILURE(EXPECT_GT(x, y), \"1-byte object <79>\");\n\n  // Code tested by EXPECT_FATAL_FAILURE cannot reference local\n  // variables, so we have to write UnprintableChar('x') instead of x.\n#ifndef __BORLANDC__\n  // ICE's in C++Builder.\n  EXPECT_FATAL_FAILURE(ASSERT_NE(UnprintableChar('x'), UnprintableChar('x')),\n                       \"1-byte object <78>\");\n  EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),\n                       \"1-byte object <78>\");\n#endif\n  EXPECT_FATAL_FAILURE(ASSERT_LE(UnprintableChar('y'), UnprintableChar('x')),\n                       \"1-byte object <79>\");\n  EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),\n                       \"1-byte object <78>\");\n  EXPECT_FATAL_FAILURE(ASSERT_GE(UnprintableChar('x'), UnprintableChar('y')),\n                       \"1-byte object <79>\");\n}\n\n// Tests the FRIEND_TEST macro.\n\n// This class has a private member we want to test.  We will test it\n// both in a TEST and in a TEST_F.\nclass Foo {\n public:\n  Foo() {}\n\n private:\n  int Bar() const { return 1; }\n\n  // Declares the friend tests that can access the private member\n  // Bar().\n  FRIEND_TEST(FRIEND_TEST_Test, TEST);\n  FRIEND_TEST(FRIEND_TEST_Test2, TEST_F);\n};\n\n// Tests that the FRIEND_TEST declaration allows a TEST to access a\n// class's private members.  This should compile.\nTEST(FRIEND_TEST_Test, TEST) { ASSERT_EQ(1, Foo().Bar()); }\n\n// The fixture needed to test using FRIEND_TEST with TEST_F.\nclass FRIEND_TEST_Test2 : public Test {\n protected:\n  Foo foo;\n};\n\n// Tests that the FRIEND_TEST declaration allows a TEST_F to access a\n// class's private members.  This should compile.\nTEST_F(FRIEND_TEST_Test2, TEST_F) { ASSERT_EQ(1, foo.Bar()); }\n\n// Tests the life cycle of Test objects.\n\n// The test fixture for testing the life cycle of Test objects.\n//\n// This class counts the number of live test objects that uses this\n// fixture.\nclass TestLifeCycleTest : public Test {\n protected:\n  // Constructor.  Increments the number of test objects that uses\n  // this fixture.\n  TestLifeCycleTest() { count_++; }\n\n  // Destructor.  Decrements the number of test objects that uses this\n  // fixture.\n  ~TestLifeCycleTest() override { count_--; }\n\n  // Returns the number of live test objects that uses this fixture.\n  int count() const { return count_; }\n\n private:\n  static int count_;\n};\n\nint TestLifeCycleTest::count_ = 0;\n\n// Tests the life cycle of test objects.\nTEST_F(TestLifeCycleTest, Test1) {\n  // There should be only one test object in this test case that's\n  // currently alive.\n  ASSERT_EQ(1, count());\n}\n\n// Tests the life cycle of test objects.\nTEST_F(TestLifeCycleTest, Test2) {\n  // After Test1 is done and Test2 is started, there should still be\n  // only one live test object, as the object for Test1 should've been\n  // deleted.\n  ASSERT_EQ(1, count());\n}\n\n}  // namespace\n\n// Tests that the copy constructor works when it is NOT optimized away by\n// the compiler.\nTEST(AssertionResultTest, CopyConstructorWorksWhenNotOptimied) {\n  // Checks that the copy constructor doesn't try to dereference NULL pointers\n  // in the source object.\n  AssertionResult r1 = AssertionSuccess();\n  AssertionResult r2 = r1;\n  // The following line is added to prevent the compiler from optimizing\n  // away the constructor call.\n  r1 << \"abc\";\n\n  AssertionResult r3 = r1;\n  EXPECT_EQ(static_cast<bool>(r3), static_cast<bool>(r1));\n  EXPECT_STREQ(\"abc\", r1.message());\n}\n\n// Tests that AssertionSuccess and AssertionFailure construct\n// AssertionResult objects as expected.\nTEST(AssertionResultTest, ConstructionWorks) {\n  AssertionResult r1 = AssertionSuccess();\n  EXPECT_TRUE(r1);\n  EXPECT_STREQ(\"\", r1.message());\n\n  AssertionResult r2 = AssertionSuccess() << \"abc\";\n  EXPECT_TRUE(r2);\n  EXPECT_STREQ(\"abc\", r2.message());\n\n  AssertionResult r3 = AssertionFailure();\n  EXPECT_FALSE(r3);\n  EXPECT_STREQ(\"\", r3.message());\n\n  AssertionResult r4 = AssertionFailure() << \"def\";\n  EXPECT_FALSE(r4);\n  EXPECT_STREQ(\"def\", r4.message());\n\n  AssertionResult r5 = AssertionFailure(Message() << \"ghi\");\n  EXPECT_FALSE(r5);\n  EXPECT_STREQ(\"ghi\", r5.message());\n}\n\n// Tests that the negation flips the predicate result but keeps the message.\nTEST(AssertionResultTest, NegationWorks) {\n  AssertionResult r1 = AssertionSuccess() << \"abc\";\n  EXPECT_FALSE(!r1);\n  EXPECT_STREQ(\"abc\", (!r1).message());\n\n  AssertionResult r2 = AssertionFailure() << \"def\";\n  EXPECT_TRUE(!r2);\n  EXPECT_STREQ(\"def\", (!r2).message());\n}\n\nTEST(AssertionResultTest, StreamingWorks) {\n  AssertionResult r = AssertionSuccess();\n  r << \"abc\" << 'd' << 0 << true;\n  EXPECT_STREQ(\"abcd0true\", r.message());\n}\n\nTEST(AssertionResultTest, CanStreamOstreamManipulators) {\n  AssertionResult r = AssertionSuccess();\n  r << \"Data\" << std::endl << std::flush << std::ends << \"Will be visible\";\n  EXPECT_STREQ(\"Data\\n\\\\0Will be visible\", r.message());\n}\n\n// The next test uses explicit conversion operators\n\nTEST(AssertionResultTest, ConstructibleFromContextuallyConvertibleToBool) {\n  struct ExplicitlyConvertibleToBool {\n    explicit operator bool() const { return value; }\n    bool value;\n  };\n  ExplicitlyConvertibleToBool v1 = {false};\n  ExplicitlyConvertibleToBool v2 = {true};\n  EXPECT_FALSE(v1);\n  EXPECT_TRUE(v2);\n}\n\nstruct ConvertibleToAssertionResult {\n  operator AssertionResult() const { return AssertionResult(true); }\n};\n\nTEST(AssertionResultTest, ConstructibleFromImplicitlyConvertible) {\n  ConvertibleToAssertionResult obj;\n  EXPECT_TRUE(obj);\n}\n\n// Tests streaming a user type whose definition and operator << are\n// both in the global namespace.\nclass Base {\n public:\n  explicit Base(int an_x) : x_(an_x) {}\n  int x() const { return x_; }\n\n private:\n  int x_;\n};\nstd::ostream& operator<<(std::ostream& os, const Base& val) {\n  return os << val.x();\n}\nstd::ostream& operator<<(std::ostream& os, const Base* pointer) {\n  return os << \"(\" << pointer->x() << \")\";\n}\n\nTEST(MessageTest, CanStreamUserTypeInGlobalNameSpace) {\n  Message msg;\n  Base a(1);\n\n  msg << a << &a;  // Uses ::operator<<.\n  EXPECT_STREQ(\"1(1)\", msg.GetString().c_str());\n}\n\n// Tests streaming a user type whose definition and operator<< are\n// both in an unnamed namespace.\nnamespace {\nclass MyTypeInUnnamedNameSpace : public Base {\n public:\n  explicit MyTypeInUnnamedNameSpace(int an_x) : Base(an_x) {}\n};\nstd::ostream& operator<<(std::ostream& os,\n                         const MyTypeInUnnamedNameSpace& val) {\n  return os << val.x();\n}\nstd::ostream& operator<<(std::ostream& os,\n                         const MyTypeInUnnamedNameSpace* pointer) {\n  return os << \"(\" << pointer->x() << \")\";\n}\n}  // namespace\n\nTEST(MessageTest, CanStreamUserTypeInUnnamedNameSpace) {\n  Message msg;\n  MyTypeInUnnamedNameSpace a(1);\n\n  msg << a << &a;  // Uses <unnamed_namespace>::operator<<.\n  EXPECT_STREQ(\"1(1)\", msg.GetString().c_str());\n}\n\n// Tests streaming a user type whose definition and operator<< are\n// both in a user namespace.\nnamespace namespace1 {\nclass MyTypeInNameSpace1 : public Base {\n public:\n  explicit MyTypeInNameSpace1(int an_x) : Base(an_x) {}\n};\nstd::ostream& operator<<(std::ostream& os, const MyTypeInNameSpace1& val) {\n  return os << val.x();\n}\nstd::ostream& operator<<(std::ostream& os, const MyTypeInNameSpace1* pointer) {\n  return os << \"(\" << pointer->x() << \")\";\n}\n}  // namespace namespace1\n\nTEST(MessageTest, CanStreamUserTypeInUserNameSpace) {\n  Message msg;\n  namespace1::MyTypeInNameSpace1 a(1);\n\n  msg << a << &a;  // Uses namespace1::operator<<.\n  EXPECT_STREQ(\"1(1)\", msg.GetString().c_str());\n}\n\n// Tests streaming a user type whose definition is in a user namespace\n// but whose operator<< is in the global namespace.\nnamespace namespace2 {\nclass MyTypeInNameSpace2 : public ::Base {\n public:\n  explicit MyTypeInNameSpace2(int an_x) : Base(an_x) {}\n};\n}  // namespace namespace2\nstd::ostream& operator<<(std::ostream& os,\n                         const namespace2::MyTypeInNameSpace2& val) {\n  return os << val.x();\n}\nstd::ostream& operator<<(std::ostream& os,\n                         const namespace2::MyTypeInNameSpace2* pointer) {\n  return os << \"(\" << pointer->x() << \")\";\n}\n\nTEST(MessageTest, CanStreamUserTypeInUserNameSpaceWithStreamOperatorInGlobal) {\n  Message msg;\n  namespace2::MyTypeInNameSpace2 a(1);\n\n  msg << a << &a;  // Uses ::operator<<.\n  EXPECT_STREQ(\"1(1)\", msg.GetString().c_str());\n}\n\n// Tests streaming NULL pointers to testing::Message.\nTEST(MessageTest, NullPointers) {\n  Message msg;\n  char* const p1 = nullptr;\n  unsigned char* const p2 = nullptr;\n  int* p3 = nullptr;\n  double* p4 = nullptr;\n  bool* p5 = nullptr;\n  Message* p6 = nullptr;\n\n  msg << p1 << p2 << p3 << p4 << p5 << p6;\n  ASSERT_STREQ(\"(null)(null)(null)(null)(null)(null)\", msg.GetString().c_str());\n}\n\n// Tests streaming wide strings to testing::Message.\nTEST(MessageTest, WideStrings) {\n  // Streams a NULL of type const wchar_t*.\n  const wchar_t* const_wstr = nullptr;\n  EXPECT_STREQ(\"(null)\", (Message() << const_wstr).GetString().c_str());\n\n  // Streams a NULL of type wchar_t*.\n  wchar_t* wstr = nullptr;\n  EXPECT_STREQ(\"(null)\", (Message() << wstr).GetString().c_str());\n\n  // Streams a non-NULL of type const wchar_t*.\n  const_wstr = L\"abc\\x8119\";\n  EXPECT_STREQ(\"abc\\xe8\\x84\\x99\",\n               (Message() << const_wstr).GetString().c_str());\n\n  // Streams a non-NULL of type wchar_t*.\n  wstr = const_cast<wchar_t*>(const_wstr);\n  EXPECT_STREQ(\"abc\\xe8\\x84\\x99\", (Message() << wstr).GetString().c_str());\n}\n\n// This line tests that we can define tests in the testing namespace.\nnamespace testing {\n\n// Tests the TestInfo class.\n\nclass TestInfoTest : public Test {\n protected:\n  static const TestInfo* GetTestInfo(const char* test_name) {\n    const TestSuite* const test_suite =\n        GetUnitTestImpl()->GetTestSuite(\"TestInfoTest\", \"\", nullptr, nullptr);\n\n    for (int i = 0; i < test_suite->total_test_count(); ++i) {\n      const TestInfo* const test_info = test_suite->GetTestInfo(i);\n      if (strcmp(test_name, test_info->name()) == 0) return test_info;\n    }\n    return nullptr;\n  }\n\n  static const TestResult* GetTestResult(const TestInfo* test_info) {\n    return test_info->result();\n  }\n};\n\n// Tests TestInfo::test_case_name() and TestInfo::name().\nTEST_F(TestInfoTest, Names) {\n  const TestInfo* const test_info = GetTestInfo(\"Names\");\n\n  ASSERT_STREQ(\"TestInfoTest\", test_info->test_suite_name());\n  ASSERT_STREQ(\"Names\", test_info->name());\n}\n\n// Tests TestInfo::result().\nTEST_F(TestInfoTest, result) {\n  const TestInfo* const test_info = GetTestInfo(\"result\");\n\n  // Initially, there is no TestPartResult for this test.\n  ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());\n\n  // After the previous assertion, there is still none.\n  ASSERT_EQ(0, GetTestResult(test_info)->total_part_count());\n}\n\n#define VERIFY_CODE_LOCATION                                                \\\n  const int expected_line = __LINE__ - 1;                                   \\\n  const TestInfo* const test_info = GetUnitTestImpl()->current_test_info(); \\\n  ASSERT_TRUE(test_info);                                                   \\\n  EXPECT_STREQ(__FILE__, test_info->file());                                \\\n  EXPECT_EQ(expected_line, test_info->line())\n\n// clang-format off\nTEST(CodeLocationForTEST, Verify) {\n  VERIFY_CODE_LOCATION;\n}\n\nclass CodeLocationForTESTF : public Test {};\n\nTEST_F(CodeLocationForTESTF, Verify) {\n  VERIFY_CODE_LOCATION;\n}\n\nclass CodeLocationForTESTP : public TestWithParam<int> {};\n\nTEST_P(CodeLocationForTESTP, Verify) {\n  VERIFY_CODE_LOCATION;\n}\n\nINSTANTIATE_TEST_SUITE_P(, CodeLocationForTESTP, Values(0));\n\ntemplate <typename T>\nclass CodeLocationForTYPEDTEST : public Test {};\n\nTYPED_TEST_SUITE(CodeLocationForTYPEDTEST, int);\n\nTYPED_TEST(CodeLocationForTYPEDTEST, Verify) {\n  VERIFY_CODE_LOCATION;\n}\n\ntemplate <typename T>\nclass CodeLocationForTYPEDTESTP : public Test {};\n\nTYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP);\n\nTYPED_TEST_P(CodeLocationForTYPEDTESTP, Verify) {\n  VERIFY_CODE_LOCATION;\n}\n\nREGISTER_TYPED_TEST_SUITE_P(CodeLocationForTYPEDTESTP, Verify);\n\nINSTANTIATE_TYPED_TEST_SUITE_P(My, CodeLocationForTYPEDTESTP, int);\n\n#undef VERIFY_CODE_LOCATION\n// clang-format on\n\n// Tests setting up and tearing down a test case.\n// Legacy API is deprecated but still available\n#ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_\nclass SetUpTestCaseTest : public Test {\n protected:\n  // This will be called once before the first test in this test case\n  // is run.\n  static void SetUpTestCase() {\n    printf(\"Setting up the test case . . .\\n\");\n\n    // Initializes some shared resource.  In this simple example, we\n    // just create a C string.  More complex stuff can be done if\n    // desired.\n    shared_resource_ = \"123\";\n\n    // Increments the number of test cases that have been set up.\n    counter_++;\n\n    // SetUpTestCase() should be called only once.\n    EXPECT_EQ(1, counter_);\n  }\n\n  // This will be called once after the last test in this test case is\n  // run.\n  static void TearDownTestCase() {\n    printf(\"Tearing down the test case . . .\\n\");\n\n    // Decrements the number of test cases that have been set up.\n    counter_--;\n\n    // TearDownTestCase() should be called only once.\n    EXPECT_EQ(0, counter_);\n\n    // Cleans up the shared resource.\n    shared_resource_ = nullptr;\n  }\n\n  // This will be called before each test in this test case.\n  void SetUp() override {\n    // SetUpTestCase() should be called only once, so counter_ should\n    // always be 1.\n    EXPECT_EQ(1, counter_);\n  }\n\n  // Number of test cases that have been set up.\n  static int counter_;\n\n  // Some resource to be shared by all tests in this test case.\n  static const char* shared_resource_;\n};\n\nint SetUpTestCaseTest::counter_ = 0;\nconst char* SetUpTestCaseTest::shared_resource_ = nullptr;\n\n// A test that uses the shared resource.\nTEST_F(SetUpTestCaseTest, Test1) { EXPECT_STRNE(nullptr, shared_resource_); }\n\n// Another test that uses the shared resource.\nTEST_F(SetUpTestCaseTest, Test2) { EXPECT_STREQ(\"123\", shared_resource_); }\n#endif  //  GTEST_REMOVE_LEGACY_TEST_CASEAPI_\n\n// Tests SetupTestSuite/TearDown TestSuite\nclass SetUpTestSuiteTest : public Test {\n protected:\n  // This will be called once before the first test in this test case\n  // is run.\n  static void SetUpTestSuite() {\n    printf(\"Setting up the test suite . . .\\n\");\n\n    // Initializes some shared resource.  In this simple example, we\n    // just create a C string.  More complex stuff can be done if\n    // desired.\n    shared_resource_ = \"123\";\n\n    // Increments the number of test cases that have been set up.\n    counter_++;\n\n    // SetUpTestSuite() should be called only once.\n    EXPECT_EQ(1, counter_);\n  }\n\n  // This will be called once after the last test in this test case is\n  // run.\n  static void TearDownTestSuite() {\n    printf(\"Tearing down the test suite . . .\\n\");\n\n    // Decrements the number of test suites that have been set up.\n    counter_--;\n\n    // TearDownTestSuite() should be called only once.\n    EXPECT_EQ(0, counter_);\n\n    // Cleans up the shared resource.\n    shared_resource_ = nullptr;\n  }\n\n  // This will be called before each test in this test case.\n  void SetUp() override {\n    // SetUpTestSuite() should be called only once, so counter_ should\n    // always be 1.\n    EXPECT_EQ(1, counter_);\n  }\n\n  // Number of test suites that have been set up.\n  static int counter_;\n\n  // Some resource to be shared by all tests in this test case.\n  static const char* shared_resource_;\n};\n\nint SetUpTestSuiteTest::counter_ = 0;\nconst char* SetUpTestSuiteTest::shared_resource_ = nullptr;\n\n// A test that uses the shared resource.\nTEST_F(SetUpTestSuiteTest, TestSetupTestSuite1) {\n  EXPECT_STRNE(nullptr, shared_resource_);\n}\n\n// Another test that uses the shared resource.\nTEST_F(SetUpTestSuiteTest, TestSetupTestSuite2) {\n  EXPECT_STREQ(\"123\", shared_resource_);\n}\n\n// The ParseFlagsTest test case tests ParseGoogleTestFlagsOnly.\n\n// The Flags struct stores a copy of all Google Test flags.\nstruct Flags {\n  // Constructs a Flags struct where each flag has its default value.\n  Flags()\n      : also_run_disabled_tests(false),\n        break_on_failure(false),\n        catch_exceptions(false),\n        death_test_use_fork(false),\n        fail_fast(false),\n        filter(\"\"),\n        list_tests(false),\n        output(\"\"),\n        brief(false),\n        print_time(true),\n        random_seed(0),\n        repeat(1),\n        recreate_environments_when_repeating(true),\n        shuffle(false),\n        stack_trace_depth(kMaxStackTraceDepth),\n        stream_result_to(\"\"),\n        throw_on_failure(false) {}\n\n  // Factory methods.\n\n  // Creates a Flags struct where the gtest_also_run_disabled_tests flag has\n  // the given value.\n  static Flags AlsoRunDisabledTests(bool also_run_disabled_tests) {\n    Flags flags;\n    flags.also_run_disabled_tests = also_run_disabled_tests;\n    return flags;\n  }\n\n  // Creates a Flags struct where the gtest_break_on_failure flag has\n  // the given value.\n  static Flags BreakOnFailure(bool break_on_failure) {\n    Flags flags;\n    flags.break_on_failure = break_on_failure;\n    return flags;\n  }\n\n  // Creates a Flags struct where the gtest_catch_exceptions flag has\n  // the given value.\n  static Flags CatchExceptions(bool catch_exceptions) {\n    Flags flags;\n    flags.catch_exceptions = catch_exceptions;\n    return flags;\n  }\n\n  // Creates a Flags struct where the gtest_death_test_use_fork flag has\n  // the given value.\n  static Flags DeathTestUseFork(bool death_test_use_fork) {\n    Flags flags;\n    flags.death_test_use_fork = death_test_use_fork;\n    return flags;\n  }\n\n  // Creates a Flags struct where the gtest_fail_fast flag has\n  // the given value.\n  static Flags FailFast(bool fail_fast) {\n    Flags flags;\n    flags.fail_fast = fail_fast;\n    return flags;\n  }\n\n  // Creates a Flags struct where the gtest_filter flag has the given\n  // value.\n  static Flags Filter(const char* filter) {\n    Flags flags;\n    flags.filter = filter;\n    return flags;\n  }\n\n  // Creates a Flags struct where the gtest_list_tests flag has the\n  // given value.\n  static Flags ListTests(bool list_tests) {\n    Flags flags;\n    flags.list_tests = list_tests;\n    return flags;\n  }\n\n  // Creates a Flags struct where the gtest_output flag has the given\n  // value.\n  static Flags Output(const char* output) {\n    Flags flags;\n    flags.output = output;\n    return flags;\n  }\n\n  // Creates a Flags struct where the gtest_brief flag has the given\n  // value.\n  static Flags Brief(bool brief) {\n    Flags flags;\n    flags.brief = brief;\n    return flags;\n  }\n\n  // Creates a Flags struct where the gtest_print_time flag has the given\n  // value.\n  static Flags PrintTime(bool print_time) {\n    Flags flags;\n    flags.print_time = print_time;\n    return flags;\n  }\n\n  // Creates a Flags struct where the gtest_random_seed flag has the given\n  // value.\n  static Flags RandomSeed(int32_t random_seed) {\n    Flags flags;\n    flags.random_seed = random_seed;\n    return flags;\n  }\n\n  // Creates a Flags struct where the gtest_repeat flag has the given\n  // value.\n  static Flags Repeat(int32_t repeat) {\n    Flags flags;\n    flags.repeat = repeat;\n    return flags;\n  }\n\n  // Creates a Flags struct where the gtest_recreate_environments_when_repeating\n  // flag has the given value.\n  static Flags RecreateEnvironmentsWhenRepeating(\n      bool recreate_environments_when_repeating) {\n    Flags flags;\n    flags.recreate_environments_when_repeating =\n        recreate_environments_when_repeating;\n    return flags;\n  }\n\n  // Creates a Flags struct where the gtest_shuffle flag has the given\n  // value.\n  static Flags Shuffle(bool shuffle) {\n    Flags flags;\n    flags.shuffle = shuffle;\n    return flags;\n  }\n\n  // Creates a Flags struct where the GTEST_FLAG(stack_trace_depth) flag has\n  // the given value.\n  static Flags StackTraceDepth(int32_t stack_trace_depth) {\n    Flags flags;\n    flags.stack_trace_depth = stack_trace_depth;\n    return flags;\n  }\n\n  // Creates a Flags struct where the GTEST_FLAG(stream_result_to) flag has\n  // the given value.\n  static Flags StreamResultTo(const char* stream_result_to) {\n    Flags flags;\n    flags.stream_result_to = stream_result_to;\n    return flags;\n  }\n\n  // Creates a Flags struct where the gtest_throw_on_failure flag has\n  // the given value.\n  static Flags ThrowOnFailure(bool throw_on_failure) {\n    Flags flags;\n    flags.throw_on_failure = throw_on_failure;\n    return flags;\n  }\n\n  // These fields store the flag values.\n  bool also_run_disabled_tests;\n  bool break_on_failure;\n  bool catch_exceptions;\n  bool death_test_use_fork;\n  bool fail_fast;\n  const char* filter;\n  bool list_tests;\n  const char* output;\n  bool brief;\n  bool print_time;\n  int32_t random_seed;\n  int32_t repeat;\n  bool recreate_environments_when_repeating;\n  bool shuffle;\n  int32_t stack_trace_depth;\n  const char* stream_result_to;\n  bool throw_on_failure;\n};\n\n// Fixture for testing ParseGoogleTestFlagsOnly().\nclass ParseFlagsTest : public Test {\n protected:\n  // Clears the flags before each test.\n  void SetUp() override {\n    GTEST_FLAG_SET(also_run_disabled_tests, false);\n    GTEST_FLAG_SET(break_on_failure, false);\n    GTEST_FLAG_SET(catch_exceptions, false);\n    GTEST_FLAG_SET(death_test_use_fork, false);\n    GTEST_FLAG_SET(fail_fast, false);\n    GTEST_FLAG_SET(filter, \"\");\n    GTEST_FLAG_SET(list_tests, false);\n    GTEST_FLAG_SET(output, \"\");\n    GTEST_FLAG_SET(brief, false);\n    GTEST_FLAG_SET(print_time, true);\n    GTEST_FLAG_SET(random_seed, 0);\n    GTEST_FLAG_SET(repeat, 1);\n    GTEST_FLAG_SET(recreate_environments_when_repeating, true);\n    GTEST_FLAG_SET(shuffle, false);\n    GTEST_FLAG_SET(stack_trace_depth, kMaxStackTraceDepth);\n    GTEST_FLAG_SET(stream_result_to, \"\");\n    GTEST_FLAG_SET(throw_on_failure, false);\n  }\n\n  // Asserts that two narrow or wide string arrays are equal.\n  template <typename CharType>\n  static void AssertStringArrayEq(int size1, CharType** array1, int size2,\n                                  CharType** array2) {\n    ASSERT_EQ(size1, size2) << \" Array sizes different.\";\n\n    for (int i = 0; i != size1; i++) {\n      ASSERT_STREQ(array1[i], array2[i]) << \" where i == \" << i;\n    }\n  }\n\n  // Verifies that the flag values match the expected values.\n  static void CheckFlags(const Flags& expected) {\n    EXPECT_EQ(expected.also_run_disabled_tests,\n              GTEST_FLAG_GET(also_run_disabled_tests));\n    EXPECT_EQ(expected.break_on_failure, GTEST_FLAG_GET(break_on_failure));\n    EXPECT_EQ(expected.catch_exceptions, GTEST_FLAG_GET(catch_exceptions));\n    EXPECT_EQ(expected.death_test_use_fork,\n              GTEST_FLAG_GET(death_test_use_fork));\n    EXPECT_EQ(expected.fail_fast, GTEST_FLAG_GET(fail_fast));\n    EXPECT_STREQ(expected.filter, GTEST_FLAG_GET(filter).c_str());\n    EXPECT_EQ(expected.list_tests, GTEST_FLAG_GET(list_tests));\n    EXPECT_STREQ(expected.output, GTEST_FLAG_GET(output).c_str());\n    EXPECT_EQ(expected.brief, GTEST_FLAG_GET(brief));\n    EXPECT_EQ(expected.print_time, GTEST_FLAG_GET(print_time));\n    EXPECT_EQ(expected.random_seed, GTEST_FLAG_GET(random_seed));\n    EXPECT_EQ(expected.repeat, GTEST_FLAG_GET(repeat));\n    EXPECT_EQ(expected.recreate_environments_when_repeating,\n              GTEST_FLAG_GET(recreate_environments_when_repeating));\n    EXPECT_EQ(expected.shuffle, GTEST_FLAG_GET(shuffle));\n    EXPECT_EQ(expected.stack_trace_depth, GTEST_FLAG_GET(stack_trace_depth));\n    EXPECT_STREQ(expected.stream_result_to,\n                 GTEST_FLAG_GET(stream_result_to).c_str());\n    EXPECT_EQ(expected.throw_on_failure, GTEST_FLAG_GET(throw_on_failure));\n  }\n\n  // Parses a command line (specified by argc1 and argv1), then\n  // verifies that the flag values are expected and that the\n  // recognized flags are removed from the command line.\n  template <typename CharType>\n  static void TestParsingFlags(int argc1, const CharType** argv1, int argc2,\n                               const CharType** argv2, const Flags& expected,\n                               bool should_print_help) {\n    const bool saved_help_flag = ::testing::internal::g_help_flag;\n    ::testing::internal::g_help_flag = false;\n\n#if GTEST_HAS_STREAM_REDIRECTION\n    CaptureStdout();\n#endif\n\n    // Parses the command line.\n    internal::ParseGoogleTestFlagsOnly(&argc1, const_cast<CharType**>(argv1));\n\n#if GTEST_HAS_STREAM_REDIRECTION\n    const std::string captured_stdout = GetCapturedStdout();\n#endif\n\n    // Verifies the flag values.\n    CheckFlags(expected);\n\n    // Verifies that the recognized flags are removed from the command\n    // line.\n    AssertStringArrayEq(argc1 + 1, argv1, argc2 + 1, argv2);\n\n    // ParseGoogleTestFlagsOnly should neither set g_help_flag nor print the\n    // help message for the flags it recognizes.\n    EXPECT_EQ(should_print_help, ::testing::internal::g_help_flag);\n\n#if GTEST_HAS_STREAM_REDIRECTION\n    const char* const expected_help_fragment =\n        \"This program contains tests written using\";\n    if (should_print_help) {\n      EXPECT_PRED_FORMAT2(IsSubstring, expected_help_fragment, captured_stdout);\n    } else {\n      EXPECT_PRED_FORMAT2(IsNotSubstring, expected_help_fragment,\n                          captured_stdout);\n    }\n#endif  // GTEST_HAS_STREAM_REDIRECTION\n\n    ::testing::internal::g_help_flag = saved_help_flag;\n  }\n\n  // This macro wraps TestParsingFlags s.t. the user doesn't need\n  // to specify the array sizes.\n\n#define GTEST_TEST_PARSING_FLAGS_(argv1, argv2, expected, should_print_help) \\\n  TestParsingFlags(sizeof(argv1) / sizeof(*argv1) - 1, argv1,                \\\n                   sizeof(argv2) / sizeof(*argv2) - 1, argv2, expected,      \\\n                   should_print_help)\n};\n\n// Tests parsing an empty command line.\nTEST_F(ParseFlagsTest, Empty) {\n  const char* argv[] = {nullptr};\n\n  const char* argv2[] = {nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);\n}\n\n// Tests parsing a command line that has no flag.\nTEST_F(ParseFlagsTest, NoFlag) {\n  const char* argv[] = {\"foo.exe\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);\n}\n\n// Tests parsing --gtest_fail_fast.\nTEST_F(ParseFlagsTest, FailFast) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_fail_fast\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::FailFast(true), false);\n}\n\n// Tests parsing an empty --gtest_filter flag.\nTEST_F(ParseFlagsTest, FilterEmpty) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_filter=\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(\"\"), false);\n}\n\n// Tests parsing a non-empty --gtest_filter flag.\nTEST_F(ParseFlagsTest, FilterNonEmpty) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_filter=abc\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(\"abc\"), false);\n}\n\n// Tests parsing --gtest_break_on_failure.\nTEST_F(ParseFlagsTest, BreakOnFailureWithoutValue) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_break_on_failure\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);\n}\n\n// Tests parsing --gtest_break_on_failure=0.\nTEST_F(ParseFlagsTest, BreakOnFailureFalse_0) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_break_on_failure=0\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);\n}\n\n// Tests parsing --gtest_break_on_failure=f.\nTEST_F(ParseFlagsTest, BreakOnFailureFalse_f) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_break_on_failure=f\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);\n}\n\n// Tests parsing --gtest_break_on_failure=F.\nTEST_F(ParseFlagsTest, BreakOnFailureFalse_F) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_break_on_failure=F\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(false), false);\n}\n\n// Tests parsing a --gtest_break_on_failure flag that has a \"true\"\n// definition.\nTEST_F(ParseFlagsTest, BreakOnFailureTrue) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_break_on_failure=1\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::BreakOnFailure(true), false);\n}\n\n// Tests parsing --gtest_catch_exceptions.\nTEST_F(ParseFlagsTest, CatchExceptions) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_catch_exceptions\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::CatchExceptions(true), false);\n}\n\n// Tests parsing --gtest_death_test_use_fork.\nTEST_F(ParseFlagsTest, DeathTestUseFork) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_death_test_use_fork\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::DeathTestUseFork(true), false);\n}\n\n// Tests having the same flag twice with different values.  The\n// expected behavior is that the one coming last takes precedence.\nTEST_F(ParseFlagsTest, DuplicatedFlags) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_filter=a\", \"--gtest_filter=b\",\n                        nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(\"b\"), false);\n}\n\n// Tests having an unrecognized flag on the command line.\nTEST_F(ParseFlagsTest, UnrecognizedFlag) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_break_on_failure\",\n                        \"bar\",  // Unrecognized by Google Test.\n                        \"--gtest_filter=b\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", \"bar\", nullptr};\n\n  Flags flags;\n  flags.break_on_failure = true;\n  flags.filter = \"b\";\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, flags, false);\n}\n\n// Tests having a --gtest_list_tests flag\nTEST_F(ParseFlagsTest, ListTestsFlag) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_list_tests\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);\n}\n\n// Tests having a --gtest_list_tests flag with a \"true\" value\nTEST_F(ParseFlagsTest, ListTestsTrue) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_list_tests=1\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(true), false);\n}\n\n// Tests having a --gtest_list_tests flag with a \"false\" value\nTEST_F(ParseFlagsTest, ListTestsFalse) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_list_tests=0\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);\n}\n\n// Tests parsing --gtest_list_tests=f.\nTEST_F(ParseFlagsTest, ListTestsFalse_f) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_list_tests=f\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);\n}\n\n// Tests parsing --gtest_list_tests=F.\nTEST_F(ParseFlagsTest, ListTestsFalse_F) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_list_tests=F\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ListTests(false), false);\n}\n\n// Tests parsing --gtest_output=xml\nTEST_F(ParseFlagsTest, OutputXml) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_output=xml\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output(\"xml\"), false);\n}\n\n// Tests parsing --gtest_output=xml:file\nTEST_F(ParseFlagsTest, OutputXmlFile) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_output=xml:file\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output(\"xml:file\"), false);\n}\n\n// Tests parsing --gtest_output=xml:directory/path/\nTEST_F(ParseFlagsTest, OutputXmlDirectory) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_output=xml:directory/path/\",\n                        nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Output(\"xml:directory/path/\"),\n                            false);\n}\n\n// Tests having a --gtest_brief flag\nTEST_F(ParseFlagsTest, BriefFlag) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_brief\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);\n}\n\n// Tests having a --gtest_brief flag with a \"true\" value\nTEST_F(ParseFlagsTest, BriefFlagTrue) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_brief=1\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(true), false);\n}\n\n// Tests having a --gtest_brief flag with a \"false\" value\nTEST_F(ParseFlagsTest, BriefFlagFalse) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_brief=0\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Brief(false), false);\n}\n\n// Tests having a --gtest_print_time flag\nTEST_F(ParseFlagsTest, PrintTimeFlag) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_print_time\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);\n}\n\n// Tests having a --gtest_print_time flag with a \"true\" value\nTEST_F(ParseFlagsTest, PrintTimeTrue) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_print_time=1\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(true), false);\n}\n\n// Tests having a --gtest_print_time flag with a \"false\" value\nTEST_F(ParseFlagsTest, PrintTimeFalse) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_print_time=0\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);\n}\n\n// Tests parsing --gtest_print_time=f.\nTEST_F(ParseFlagsTest, PrintTimeFalse_f) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_print_time=f\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);\n}\n\n// Tests parsing --gtest_print_time=F.\nTEST_F(ParseFlagsTest, PrintTimeFalse_F) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_print_time=F\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::PrintTime(false), false);\n}\n\n// Tests parsing --gtest_random_seed=number\nTEST_F(ParseFlagsTest, RandomSeed) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_random_seed=1000\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::RandomSeed(1000), false);\n}\n\n// Tests parsing --gtest_repeat=number\nTEST_F(ParseFlagsTest, Repeat) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_repeat=1000\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Repeat(1000), false);\n}\n\n// Tests parsing --gtest_recreate_environments_when_repeating\nTEST_F(ParseFlagsTest, RecreateEnvironmentsWhenRepeating) {\n  const char* argv[] = {\n      \"foo.exe\",\n      \"--gtest_recreate_environments_when_repeating=0\",\n      nullptr,\n  };\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(\n      argv, argv2, Flags::RecreateEnvironmentsWhenRepeating(false), false);\n}\n\n// Tests having a --gtest_also_run_disabled_tests flag\nTEST_F(ParseFlagsTest, AlsoRunDisabledTestsFlag) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_also_run_disabled_tests\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true),\n                            false);\n}\n\n// Tests having a --gtest_also_run_disabled_tests flag with a \"true\" value\nTEST_F(ParseFlagsTest, AlsoRunDisabledTestsTrue) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_also_run_disabled_tests=1\",\n                        nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(true),\n                            false);\n}\n\n// Tests having a --gtest_also_run_disabled_tests flag with a \"false\" value\nTEST_F(ParseFlagsTest, AlsoRunDisabledTestsFalse) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_also_run_disabled_tests=0\",\n                        nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::AlsoRunDisabledTests(false),\n                            false);\n}\n\n// Tests parsing --gtest_shuffle.\nTEST_F(ParseFlagsTest, ShuffleWithoutValue) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_shuffle\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);\n}\n\n// Tests parsing --gtest_shuffle=0.\nTEST_F(ParseFlagsTest, ShuffleFalse_0) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_shuffle=0\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(false), false);\n}\n\n// Tests parsing a --gtest_shuffle flag that has a \"true\" definition.\nTEST_F(ParseFlagsTest, ShuffleTrue) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_shuffle=1\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Shuffle(true), false);\n}\n\n// Tests parsing --gtest_stack_trace_depth=number.\nTEST_F(ParseFlagsTest, StackTraceDepth) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_stack_trace_depth=5\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::StackTraceDepth(5), false);\n}\n\nTEST_F(ParseFlagsTest, StreamResultTo) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_stream_result_to=localhost:1234\",\n                        nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2,\n                            Flags::StreamResultTo(\"localhost:1234\"), false);\n}\n\n// Tests parsing --gtest_throw_on_failure.\nTEST_F(ParseFlagsTest, ThrowOnFailureWithoutValue) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_throw_on_failure\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);\n}\n\n// Tests parsing --gtest_throw_on_failure=0.\nTEST_F(ParseFlagsTest, ThrowOnFailureFalse_0) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_throw_on_failure=0\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(false), false);\n}\n\n// Tests parsing a --gtest_throw_on_failure flag that has a \"true\"\n// definition.\nTEST_F(ParseFlagsTest, ThrowOnFailureTrue) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_throw_on_failure=1\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);\n}\n\n// Tests parsing a bad --gtest_filter flag.\nTEST_F(ParseFlagsTest, FilterBad) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_filter\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", \"--gtest_filter\", nullptr};\n\n#if GTEST_HAS_ABSL && GTEST_HAS_DEATH_TEST\n  // Invalid flag arguments are a fatal error when using the Abseil Flags.\n  EXPECT_EXIT(GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(\"\"), true),\n              testing::ExitedWithCode(1),\n              \"ERROR: Missing the value for the flag 'gtest_filter'\");\n#elif !GTEST_HAS_ABSL\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(\"\"), true);\n#else\n  static_cast<void>(argv);\n  static_cast<void>(argv2);\n#endif\n}\n\n// Tests parsing --gtest_output (invalid).\nTEST_F(ParseFlagsTest, OutputEmpty) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_output\", nullptr};\n\n  const char* argv2[] = {\"foo.exe\", \"--gtest_output\", nullptr};\n\n#if GTEST_HAS_ABSL && GTEST_HAS_DEATH_TEST\n  // Invalid flag arguments are a fatal error when using the Abseil Flags.\n  EXPECT_EXIT(GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true),\n              testing::ExitedWithCode(1),\n              \"ERROR: Missing the value for the flag 'gtest_output'\");\n#elif !GTEST_HAS_ABSL\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), true);\n#else\n  static_cast<void>(argv);\n  static_cast<void>(argv2);\n#endif\n}\n\n#if GTEST_HAS_ABSL\nTEST_F(ParseFlagsTest, AbseilPositionalFlags) {\n  const char* argv[] = {\"foo.exe\", \"--gtest_throw_on_failure=1\", \"--\",\n                        \"--other_flag\", nullptr};\n\n  // When using Abseil flags, it should be possible to pass flags not recognized\n  // using \"--\" to delimit positional arguments. These flags should be returned\n  // though argv.\n  const char* argv2[] = {\"foo.exe\", \"--other_flag\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::ThrowOnFailure(true), false);\n}\n#endif\n\n#if GTEST_OS_WINDOWS\n// Tests parsing wide strings.\nTEST_F(ParseFlagsTest, WideStrings) {\n  const wchar_t* argv[] = {L\"foo.exe\",\n                           L\"--gtest_filter=Foo*\",\n                           L\"--gtest_list_tests=1\",\n                           L\"--gtest_break_on_failure\",\n                           L\"--non_gtest_flag\",\n                           NULL};\n\n  const wchar_t* argv2[] = {L\"foo.exe\", L\"--non_gtest_flag\", NULL};\n\n  Flags expected_flags;\n  expected_flags.break_on_failure = true;\n  expected_flags.filter = \"Foo*\";\n  expected_flags.list_tests = true;\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);\n}\n#endif  // GTEST_OS_WINDOWS\n\n#if GTEST_USE_OWN_FLAGFILE_FLAG_\nclass FlagfileTest : public ParseFlagsTest {\n public:\n  void SetUp() override {\n    ParseFlagsTest::SetUp();\n\n    testdata_path_.Set(internal::FilePath(\n        testing::TempDir() + internal::GetCurrentExecutableName().string() +\n        \"_flagfile_test\"));\n    testing::internal::posix::RmDir(testdata_path_.c_str());\n    EXPECT_TRUE(testdata_path_.CreateFolder());\n  }\n\n  void TearDown() override {\n    testing::internal::posix::RmDir(testdata_path_.c_str());\n    ParseFlagsTest::TearDown();\n  }\n\n  internal::FilePath CreateFlagfile(const char* contents) {\n    internal::FilePath file_path(internal::FilePath::GenerateUniqueFileName(\n        testdata_path_, internal::FilePath(\"unique\"), \"txt\"));\n    FILE* f = testing::internal::posix::FOpen(file_path.c_str(), \"w\");\n    fprintf(f, \"%s\", contents);\n    fclose(f);\n    return file_path;\n  }\n\n private:\n  internal::FilePath testdata_path_;\n};\n\n// Tests an empty flagfile.\nTEST_F(FlagfileTest, Empty) {\n  internal::FilePath flagfile_path(CreateFlagfile(\"\"));\n  std::string flagfile_flag =\n      std::string(\"--\" GTEST_FLAG_PREFIX_ \"flagfile=\") + flagfile_path.c_str();\n\n  const char* argv[] = {\"foo.exe\", flagfile_flag.c_str(), nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags(), false);\n}\n\n// Tests passing a non-empty --gtest_filter flag via --gtest_flagfile.\nTEST_F(FlagfileTest, FilterNonEmpty) {\n  internal::FilePath flagfile_path(\n      CreateFlagfile(\"--\" GTEST_FLAG_PREFIX_ \"filter=abc\"));\n  std::string flagfile_flag =\n      std::string(\"--\" GTEST_FLAG_PREFIX_ \"flagfile=\") + flagfile_path.c_str();\n\n  const char* argv[] = {\"foo.exe\", flagfile_flag.c_str(), nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, Flags::Filter(\"abc\"), false);\n}\n\n// Tests passing several flags via --gtest_flagfile.\nTEST_F(FlagfileTest, SeveralFlags) {\n  internal::FilePath flagfile_path(\n      CreateFlagfile(\"--\" GTEST_FLAG_PREFIX_ \"filter=abc\\n\"\n                     \"--\" GTEST_FLAG_PREFIX_ \"break_on_failure\\n\"\n                     \"--\" GTEST_FLAG_PREFIX_ \"list_tests\"));\n  std::string flagfile_flag =\n      std::string(\"--\" GTEST_FLAG_PREFIX_ \"flagfile=\") + flagfile_path.c_str();\n\n  const char* argv[] = {\"foo.exe\", flagfile_flag.c_str(), nullptr};\n\n  const char* argv2[] = {\"foo.exe\", nullptr};\n\n  Flags expected_flags;\n  expected_flags.break_on_failure = true;\n  expected_flags.filter = \"abc\";\n  expected_flags.list_tests = true;\n\n  GTEST_TEST_PARSING_FLAGS_(argv, argv2, expected_flags, false);\n}\n#endif  // GTEST_USE_OWN_FLAGFILE_FLAG_\n\n// Tests current_test_info() in UnitTest.\nclass CurrentTestInfoTest : public Test {\n protected:\n  // Tests that current_test_info() returns NULL before the first test in\n  // the test case is run.\n  static void SetUpTestSuite() {\n    // There should be no tests running at this point.\n    const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();\n    EXPECT_TRUE(test_info == nullptr)\n        << \"There should be no tests running at this point.\";\n  }\n\n  // Tests that current_test_info() returns NULL after the last test in\n  // the test case has run.\n  static void TearDownTestSuite() {\n    const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();\n    EXPECT_TRUE(test_info == nullptr)\n        << \"There should be no tests running at this point.\";\n  }\n};\n\n// Tests that current_test_info() returns TestInfo for currently running\n// test by checking the expected test name against the actual one.\nTEST_F(CurrentTestInfoTest, WorksForFirstTestInATestSuite) {\n  const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();\n  ASSERT_TRUE(nullptr != test_info)\n      << \"There is a test running so we should have a valid TestInfo.\";\n  EXPECT_STREQ(\"CurrentTestInfoTest\", test_info->test_suite_name())\n      << \"Expected the name of the currently running test suite.\";\n  EXPECT_STREQ(\"WorksForFirstTestInATestSuite\", test_info->name())\n      << \"Expected the name of the currently running test.\";\n}\n\n// Tests that current_test_info() returns TestInfo for currently running\n// test by checking the expected test name against the actual one.  We\n// use this test to see that the TestInfo object actually changed from\n// the previous invocation.\nTEST_F(CurrentTestInfoTest, WorksForSecondTestInATestSuite) {\n  const TestInfo* test_info = UnitTest::GetInstance()->current_test_info();\n  ASSERT_TRUE(nullptr != test_info)\n      << \"There is a test running so we should have a valid TestInfo.\";\n  EXPECT_STREQ(\"CurrentTestInfoTest\", test_info->test_suite_name())\n      << \"Expected the name of the currently running test suite.\";\n  EXPECT_STREQ(\"WorksForSecondTestInATestSuite\", test_info->name())\n      << \"Expected the name of the currently running test.\";\n}\n\n}  // namespace testing\n\n// These two lines test that we can define tests in a namespace that\n// has the name \"testing\" and is nested in another namespace.\nnamespace my_namespace {\nnamespace testing {\n\n// Makes sure that TEST knows to use ::testing::Test instead of\n// ::my_namespace::testing::Test.\nclass Test {};\n\n// Makes sure that an assertion knows to use ::testing::Message instead of\n// ::my_namespace::testing::Message.\nclass Message {};\n\n// Makes sure that an assertion knows to use\n// ::testing::AssertionResult instead of\n// ::my_namespace::testing::AssertionResult.\nclass AssertionResult {};\n\n// Tests that an assertion that should succeed works as expected.\nTEST(NestedTestingNamespaceTest, Success) {\n  EXPECT_EQ(1, 1) << \"This shouldn't fail.\";\n}\n\n// Tests that an assertion that should fail works as expected.\nTEST(NestedTestingNamespaceTest, Failure) {\n  EXPECT_FATAL_FAILURE(FAIL() << \"This failure is expected.\",\n                       \"This failure is expected.\");\n}\n\n}  // namespace testing\n}  // namespace my_namespace\n\n// Tests that one can call superclass SetUp and TearDown methods--\n// that is, that they are not private.\n// No tests are based on this fixture; the test \"passes\" if it compiles\n// successfully.\nclass ProtectedFixtureMethodsTest : public Test {\n protected:\n  void SetUp() override { Test::SetUp(); }\n  void TearDown() override { Test::TearDown(); }\n};\n\n// StreamingAssertionsTest tests the streaming versions of a representative\n// sample of assertions.\nTEST(StreamingAssertionsTest, Unconditional) {\n  SUCCEED() << \"expected success\";\n  EXPECT_NONFATAL_FAILURE(ADD_FAILURE() << \"expected failure\",\n                          \"expected failure\");\n  EXPECT_FATAL_FAILURE(FAIL() << \"expected failure\", \"expected failure\");\n}\n\n#ifdef __BORLANDC__\n// Silences warnings: \"Condition is always true\", \"Unreachable code\"\n#pragma option push -w-ccc -w-rch\n#endif\n\nTEST(StreamingAssertionsTest, Truth) {\n  EXPECT_TRUE(true) << \"unexpected failure\";\n  ASSERT_TRUE(true) << \"unexpected failure\";\n  EXPECT_NONFATAL_FAILURE(EXPECT_TRUE(false) << \"expected failure\",\n                          \"expected failure\");\n  EXPECT_FATAL_FAILURE(ASSERT_TRUE(false) << \"expected failure\",\n                       \"expected failure\");\n}\n\nTEST(StreamingAssertionsTest, Truth2) {\n  EXPECT_FALSE(false) << \"unexpected failure\";\n  ASSERT_FALSE(false) << \"unexpected failure\";\n  EXPECT_NONFATAL_FAILURE(EXPECT_FALSE(true) << \"expected failure\",\n                          \"expected failure\");\n  EXPECT_FATAL_FAILURE(ASSERT_FALSE(true) << \"expected failure\",\n                       \"expected failure\");\n}\n\n#ifdef __BORLANDC__\n// Restores warnings after previous \"#pragma option push\" suppressed them\n#pragma option pop\n#endif\n\nTEST(StreamingAssertionsTest, IntegerEquals) {\n  EXPECT_EQ(1, 1) << \"unexpected failure\";\n  ASSERT_EQ(1, 1) << \"unexpected failure\";\n  EXPECT_NONFATAL_FAILURE(EXPECT_EQ(1, 2) << \"expected failure\",\n                          \"expected failure\");\n  EXPECT_FATAL_FAILURE(ASSERT_EQ(1, 2) << \"expected failure\",\n                       \"expected failure\");\n}\n\nTEST(StreamingAssertionsTest, IntegerLessThan) {\n  EXPECT_LT(1, 2) << \"unexpected failure\";\n  ASSERT_LT(1, 2) << \"unexpected failure\";\n  EXPECT_NONFATAL_FAILURE(EXPECT_LT(2, 1) << \"expected failure\",\n                          \"expected failure\");\n  EXPECT_FATAL_FAILURE(ASSERT_LT(2, 1) << \"expected failure\",\n                       \"expected failure\");\n}\n\nTEST(StreamingAssertionsTest, StringsEqual) {\n  EXPECT_STREQ(\"foo\", \"foo\") << \"unexpected failure\";\n  ASSERT_STREQ(\"foo\", \"foo\") << \"unexpected failure\";\n  EXPECT_NONFATAL_FAILURE(EXPECT_STREQ(\"foo\", \"bar\") << \"expected failure\",\n                          \"expected failure\");\n  EXPECT_FATAL_FAILURE(ASSERT_STREQ(\"foo\", \"bar\") << \"expected failure\",\n                       \"expected failure\");\n}\n\nTEST(StreamingAssertionsTest, StringsNotEqual) {\n  EXPECT_STRNE(\"foo\", \"bar\") << \"unexpected failure\";\n  ASSERT_STRNE(\"foo\", \"bar\") << \"unexpected failure\";\n  EXPECT_NONFATAL_FAILURE(EXPECT_STRNE(\"foo\", \"foo\") << \"expected failure\",\n                          \"expected failure\");\n  EXPECT_FATAL_FAILURE(ASSERT_STRNE(\"foo\", \"foo\") << \"expected failure\",\n                       \"expected failure\");\n}\n\nTEST(StreamingAssertionsTest, StringsEqualIgnoringCase) {\n  EXPECT_STRCASEEQ(\"foo\", \"FOO\") << \"unexpected failure\";\n  ASSERT_STRCASEEQ(\"foo\", \"FOO\") << \"unexpected failure\";\n  EXPECT_NONFATAL_FAILURE(EXPECT_STRCASEEQ(\"foo\", \"bar\") << \"expected failure\",\n                          \"expected failure\");\n  EXPECT_FATAL_FAILURE(ASSERT_STRCASEEQ(\"foo\", \"bar\") << \"expected failure\",\n                       \"expected failure\");\n}\n\nTEST(StreamingAssertionsTest, StringNotEqualIgnoringCase) {\n  EXPECT_STRCASENE(\"foo\", \"bar\") << \"unexpected failure\";\n  ASSERT_STRCASENE(\"foo\", \"bar\") << \"unexpected failure\";\n  EXPECT_NONFATAL_FAILURE(EXPECT_STRCASENE(\"foo\", \"FOO\") << \"expected failure\",\n                          \"expected failure\");\n  EXPECT_FATAL_FAILURE(ASSERT_STRCASENE(\"bar\", \"BAR\") << \"expected failure\",\n                       \"expected failure\");\n}\n\nTEST(StreamingAssertionsTest, FloatingPointEquals) {\n  EXPECT_FLOAT_EQ(1.0, 1.0) << \"unexpected failure\";\n  ASSERT_FLOAT_EQ(1.0, 1.0) << \"unexpected failure\";\n  EXPECT_NONFATAL_FAILURE(EXPECT_FLOAT_EQ(0.0, 1.0) << \"expected failure\",\n                          \"expected failure\");\n  EXPECT_FATAL_FAILURE(ASSERT_FLOAT_EQ(0.0, 1.0) << \"expected failure\",\n                       \"expected failure\");\n}\n\n#if GTEST_HAS_EXCEPTIONS\n\nTEST(StreamingAssertionsTest, Throw) {\n  EXPECT_THROW(ThrowAnInteger(), int) << \"unexpected failure\";\n  ASSERT_THROW(ThrowAnInteger(), int) << \"unexpected failure\";\n  EXPECT_NONFATAL_FAILURE(EXPECT_THROW(ThrowAnInteger(), bool)\n                              << \"expected failure\",\n                          \"expected failure\");\n  EXPECT_FATAL_FAILURE(ASSERT_THROW(ThrowAnInteger(), bool)\n                           << \"expected failure\",\n                       \"expected failure\");\n}\n\nTEST(StreamingAssertionsTest, NoThrow) {\n  EXPECT_NO_THROW(ThrowNothing()) << \"unexpected failure\";\n  ASSERT_NO_THROW(ThrowNothing()) << \"unexpected failure\";\n  EXPECT_NONFATAL_FAILURE(EXPECT_NO_THROW(ThrowAnInteger())\n                              << \"expected failure\",\n                          \"expected failure\");\n  EXPECT_FATAL_FAILURE(ASSERT_NO_THROW(ThrowAnInteger()) << \"expected failure\",\n                       \"expected failure\");\n}\n\nTEST(StreamingAssertionsTest, AnyThrow) {\n  EXPECT_ANY_THROW(ThrowAnInteger()) << \"unexpected failure\";\n  ASSERT_ANY_THROW(ThrowAnInteger()) << \"unexpected failure\";\n  EXPECT_NONFATAL_FAILURE(EXPECT_ANY_THROW(ThrowNothing())\n                              << \"expected failure\",\n                          \"expected failure\");\n  EXPECT_FATAL_FAILURE(ASSERT_ANY_THROW(ThrowNothing()) << \"expected failure\",\n                       \"expected failure\");\n}\n\n#endif  // GTEST_HAS_EXCEPTIONS\n\n// Tests that Google Test correctly decides whether to use colors in the output.\n\nTEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsYes) {\n  GTEST_FLAG_SET(color, \"yes\");\n\n  SetEnv(\"TERM\", \"xterm\");             // TERM supports colors.\n  EXPECT_TRUE(ShouldUseColor(true));   // Stdout is a TTY.\n  EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.\n\n  SetEnv(\"TERM\", \"dumb\");              // TERM doesn't support colors.\n  EXPECT_TRUE(ShouldUseColor(true));   // Stdout is a TTY.\n  EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.\n}\n\nTEST(ColoredOutputTest, UsesColorsWhenGTestColorFlagIsAliasOfYes) {\n  SetEnv(\"TERM\", \"dumb\");  // TERM doesn't support colors.\n\n  GTEST_FLAG_SET(color, \"True\");\n  EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.\n\n  GTEST_FLAG_SET(color, \"t\");\n  EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.\n\n  GTEST_FLAG_SET(color, \"1\");\n  EXPECT_TRUE(ShouldUseColor(false));  // Stdout is not a TTY.\n}\n\nTEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsNo) {\n  GTEST_FLAG_SET(color, \"no\");\n\n  SetEnv(\"TERM\", \"xterm\");              // TERM supports colors.\n  EXPECT_FALSE(ShouldUseColor(true));   // Stdout is a TTY.\n  EXPECT_FALSE(ShouldUseColor(false));  // Stdout is not a TTY.\n\n  SetEnv(\"TERM\", \"dumb\");               // TERM doesn't support colors.\n  EXPECT_FALSE(ShouldUseColor(true));   // Stdout is a TTY.\n  EXPECT_FALSE(ShouldUseColor(false));  // Stdout is not a TTY.\n}\n\nTEST(ColoredOutputTest, UsesNoColorWhenGTestColorFlagIsInvalid) {\n  SetEnv(\"TERM\", \"xterm\");  // TERM supports colors.\n\n  GTEST_FLAG_SET(color, \"F\");\n  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.\n\n  GTEST_FLAG_SET(color, \"0\");\n  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.\n\n  GTEST_FLAG_SET(color, \"unknown\");\n  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.\n}\n\nTEST(ColoredOutputTest, UsesColorsWhenStdoutIsTty) {\n  GTEST_FLAG_SET(color, \"auto\");\n\n  SetEnv(\"TERM\", \"xterm\");              // TERM supports colors.\n  EXPECT_FALSE(ShouldUseColor(false));  // Stdout is not a TTY.\n  EXPECT_TRUE(ShouldUseColor(true));    // Stdout is a TTY.\n}\n\nTEST(ColoredOutputTest, UsesColorsWhenTermSupportsColors) {\n  GTEST_FLAG_SET(color, \"auto\");\n\n#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MINGW\n  // On Windows, we ignore the TERM variable as it's usually not set.\n\n  SetEnv(\"TERM\", \"dumb\");\n  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.\n\n  SetEnv(\"TERM\", \"\");\n  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.\n\n  SetEnv(\"TERM\", \"xterm\");\n  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.\n#else\n  // On non-Windows platforms, we rely on TERM to determine if the\n  // terminal supports colors.\n\n  SetEnv(\"TERM\", \"dumb\");              // TERM doesn't support colors.\n  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.\n\n  SetEnv(\"TERM\", \"emacs\");             // TERM doesn't support colors.\n  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.\n\n  SetEnv(\"TERM\", \"vt100\");             // TERM doesn't support colors.\n  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.\n\n  SetEnv(\"TERM\", \"xterm-mono\");        // TERM doesn't support colors.\n  EXPECT_FALSE(ShouldUseColor(true));  // Stdout is a TTY.\n\n  SetEnv(\"TERM\", \"xterm\");            // TERM supports colors.\n  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.\n\n  SetEnv(\"TERM\", \"xterm-color\");      // TERM supports colors.\n  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.\n\n  SetEnv(\"TERM\", \"xterm-256color\");   // TERM supports colors.\n  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.\n\n  SetEnv(\"TERM\", \"screen\");           // TERM supports colors.\n  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.\n\n  SetEnv(\"TERM\", \"screen-256color\");  // TERM supports colors.\n  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.\n\n  SetEnv(\"TERM\", \"tmux\");             // TERM supports colors.\n  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.\n\n  SetEnv(\"TERM\", \"tmux-256color\");    // TERM supports colors.\n  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.\n\n  SetEnv(\"TERM\", \"rxvt-unicode\");     // TERM supports colors.\n  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.\n\n  SetEnv(\"TERM\", \"rxvt-unicode-256color\");  // TERM supports colors.\n  EXPECT_TRUE(ShouldUseColor(true));        // Stdout is a TTY.\n\n  SetEnv(\"TERM\", \"linux\");            // TERM supports colors.\n  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.\n\n  SetEnv(\"TERM\", \"cygwin\");           // TERM supports colors.\n  EXPECT_TRUE(ShouldUseColor(true));  // Stdout is a TTY.\n#endif  // GTEST_OS_WINDOWS\n}\n\n// Verifies that StaticAssertTypeEq works in a namespace scope.\n\nstatic bool dummy1 GTEST_ATTRIBUTE_UNUSED_ = StaticAssertTypeEq<bool, bool>();\nstatic bool dummy2 GTEST_ATTRIBUTE_UNUSED_ =\n    StaticAssertTypeEq<const int, const int>();\n\n// Verifies that StaticAssertTypeEq works in a class.\n\ntemplate <typename T>\nclass StaticAssertTypeEqTestHelper {\n public:\n  StaticAssertTypeEqTestHelper() { StaticAssertTypeEq<bool, T>(); }\n};\n\nTEST(StaticAssertTypeEqTest, WorksInClass) {\n  StaticAssertTypeEqTestHelper<bool>();\n}\n\n// Verifies that StaticAssertTypeEq works inside a function.\n\ntypedef int IntAlias;\n\nTEST(StaticAssertTypeEqTest, CompilesForEqualTypes) {\n  StaticAssertTypeEq<int, IntAlias>();\n  StaticAssertTypeEq<int*, IntAlias*>();\n}\n\nTEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsNoFailure) {\n  EXPECT_FALSE(HasNonfatalFailure());\n}\n\nstatic void FailFatally() { FAIL(); }\n\nTEST(HasNonfatalFailureTest, ReturnsFalseWhenThereIsOnlyFatalFailure) {\n  FailFatally();\n  const bool has_nonfatal_failure = HasNonfatalFailure();\n  ClearCurrentTestPartResults();\n  EXPECT_FALSE(has_nonfatal_failure);\n}\n\nTEST(HasNonfatalFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {\n  ADD_FAILURE();\n  const bool has_nonfatal_failure = HasNonfatalFailure();\n  ClearCurrentTestPartResults();\n  EXPECT_TRUE(has_nonfatal_failure);\n}\n\nTEST(HasNonfatalFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {\n  FailFatally();\n  ADD_FAILURE();\n  const bool has_nonfatal_failure = HasNonfatalFailure();\n  ClearCurrentTestPartResults();\n  EXPECT_TRUE(has_nonfatal_failure);\n}\n\n// A wrapper for calling HasNonfatalFailure outside of a test body.\nstatic bool HasNonfatalFailureHelper() {\n  return testing::Test::HasNonfatalFailure();\n}\n\nTEST(HasNonfatalFailureTest, WorksOutsideOfTestBody) {\n  EXPECT_FALSE(HasNonfatalFailureHelper());\n}\n\nTEST(HasNonfatalFailureTest, WorksOutsideOfTestBody2) {\n  ADD_FAILURE();\n  const bool has_nonfatal_failure = HasNonfatalFailureHelper();\n  ClearCurrentTestPartResults();\n  EXPECT_TRUE(has_nonfatal_failure);\n}\n\nTEST(HasFailureTest, ReturnsFalseWhenThereIsNoFailure) {\n  EXPECT_FALSE(HasFailure());\n}\n\nTEST(HasFailureTest, ReturnsTrueWhenThereIsFatalFailure) {\n  FailFatally();\n  const bool has_failure = HasFailure();\n  ClearCurrentTestPartResults();\n  EXPECT_TRUE(has_failure);\n}\n\nTEST(HasFailureTest, ReturnsTrueWhenThereIsNonfatalFailure) {\n  ADD_FAILURE();\n  const bool has_failure = HasFailure();\n  ClearCurrentTestPartResults();\n  EXPECT_TRUE(has_failure);\n}\n\nTEST(HasFailureTest, ReturnsTrueWhenThereAreFatalAndNonfatalFailures) {\n  FailFatally();\n  ADD_FAILURE();\n  const bool has_failure = HasFailure();\n  ClearCurrentTestPartResults();\n  EXPECT_TRUE(has_failure);\n}\n\n// A wrapper for calling HasFailure outside of a test body.\nstatic bool HasFailureHelper() { return testing::Test::HasFailure(); }\n\nTEST(HasFailureTest, WorksOutsideOfTestBody) {\n  EXPECT_FALSE(HasFailureHelper());\n}\n\nTEST(HasFailureTest, WorksOutsideOfTestBody2) {\n  ADD_FAILURE();\n  const bool has_failure = HasFailureHelper();\n  ClearCurrentTestPartResults();\n  EXPECT_TRUE(has_failure);\n}\n\nclass TestListener : public EmptyTestEventListener {\n public:\n  TestListener() : on_start_counter_(nullptr), is_destroyed_(nullptr) {}\n  TestListener(int* on_start_counter, bool* is_destroyed)\n      : on_start_counter_(on_start_counter), is_destroyed_(is_destroyed) {}\n\n  ~TestListener() override {\n    if (is_destroyed_) *is_destroyed_ = true;\n  }\n\n protected:\n  void OnTestProgramStart(const UnitTest& /*unit_test*/) override {\n    if (on_start_counter_ != nullptr) (*on_start_counter_)++;\n  }\n\n private:\n  int* on_start_counter_;\n  bool* is_destroyed_;\n};\n\n// Tests the constructor.\nTEST(TestEventListenersTest, ConstructionWorks) {\n  TestEventListeners listeners;\n\n  EXPECT_TRUE(TestEventListenersAccessor::GetRepeater(&listeners) != nullptr);\n  EXPECT_TRUE(listeners.default_result_printer() == nullptr);\n  EXPECT_TRUE(listeners.default_xml_generator() == nullptr);\n}\n\n// Tests that the TestEventListeners destructor deletes all the listeners it\n// owns.\nTEST(TestEventListenersTest, DestructionWorks) {\n  bool default_result_printer_is_destroyed = false;\n  bool default_xml_printer_is_destroyed = false;\n  bool extra_listener_is_destroyed = false;\n  TestListener* default_result_printer =\n      new TestListener(nullptr, &default_result_printer_is_destroyed);\n  TestListener* default_xml_printer =\n      new TestListener(nullptr, &default_xml_printer_is_destroyed);\n  TestListener* extra_listener =\n      new TestListener(nullptr, &extra_listener_is_destroyed);\n\n  {\n    TestEventListeners listeners;\n    TestEventListenersAccessor::SetDefaultResultPrinter(&listeners,\n                                                        default_result_printer);\n    TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners,\n                                                       default_xml_printer);\n    listeners.Append(extra_listener);\n  }\n  EXPECT_TRUE(default_result_printer_is_destroyed);\n  EXPECT_TRUE(default_xml_printer_is_destroyed);\n  EXPECT_TRUE(extra_listener_is_destroyed);\n}\n\n// Tests that a listener Append'ed to a TestEventListeners list starts\n// receiving events.\nTEST(TestEventListenersTest, Append) {\n  int on_start_counter = 0;\n  bool is_destroyed = false;\n  TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);\n  {\n    TestEventListeners listeners;\n    listeners.Append(listener);\n    TestEventListenersAccessor::GetRepeater(&listeners)\n        ->OnTestProgramStart(*UnitTest::GetInstance());\n    EXPECT_EQ(1, on_start_counter);\n  }\n  EXPECT_TRUE(is_destroyed);\n}\n\n// Tests that listeners receive events in the order they were appended to\n// the list, except for *End requests, which must be received in the reverse\n// order.\nclass SequenceTestingListener : public EmptyTestEventListener {\n public:\n  SequenceTestingListener(std::vector<std::string>* vector, const char* id)\n      : vector_(vector), id_(id) {}\n\n protected:\n  void OnTestProgramStart(const UnitTest& /*unit_test*/) override {\n    vector_->push_back(GetEventDescription(\"OnTestProgramStart\"));\n  }\n\n  void OnTestProgramEnd(const UnitTest& /*unit_test*/) override {\n    vector_->push_back(GetEventDescription(\"OnTestProgramEnd\"));\n  }\n\n  void OnTestIterationStart(const UnitTest& /*unit_test*/,\n                            int /*iteration*/) override {\n    vector_->push_back(GetEventDescription(\"OnTestIterationStart\"));\n  }\n\n  void OnTestIterationEnd(const UnitTest& /*unit_test*/,\n                          int /*iteration*/) override {\n    vector_->push_back(GetEventDescription(\"OnTestIterationEnd\"));\n  }\n\n private:\n  std::string GetEventDescription(const char* method) {\n    Message message;\n    message << id_ << \".\" << method;\n    return message.GetString();\n  }\n\n  std::vector<std::string>* vector_;\n  const char* const id_;\n\n  SequenceTestingListener(const SequenceTestingListener&) = delete;\n  SequenceTestingListener& operator=(const SequenceTestingListener&) = delete;\n};\n\nTEST(EventListenerTest, AppendKeepsOrder) {\n  std::vector<std::string> vec;\n  TestEventListeners listeners;\n  listeners.Append(new SequenceTestingListener(&vec, \"1st\"));\n  listeners.Append(new SequenceTestingListener(&vec, \"2nd\"));\n  listeners.Append(new SequenceTestingListener(&vec, \"3rd\"));\n\n  TestEventListenersAccessor::GetRepeater(&listeners)\n      ->OnTestProgramStart(*UnitTest::GetInstance());\n  ASSERT_EQ(3U, vec.size());\n  EXPECT_STREQ(\"1st.OnTestProgramStart\", vec[0].c_str());\n  EXPECT_STREQ(\"2nd.OnTestProgramStart\", vec[1].c_str());\n  EXPECT_STREQ(\"3rd.OnTestProgramStart\", vec[2].c_str());\n\n  vec.clear();\n  TestEventListenersAccessor::GetRepeater(&listeners)\n      ->OnTestProgramEnd(*UnitTest::GetInstance());\n  ASSERT_EQ(3U, vec.size());\n  EXPECT_STREQ(\"3rd.OnTestProgramEnd\", vec[0].c_str());\n  EXPECT_STREQ(\"2nd.OnTestProgramEnd\", vec[1].c_str());\n  EXPECT_STREQ(\"1st.OnTestProgramEnd\", vec[2].c_str());\n\n  vec.clear();\n  TestEventListenersAccessor::GetRepeater(&listeners)\n      ->OnTestIterationStart(*UnitTest::GetInstance(), 0);\n  ASSERT_EQ(3U, vec.size());\n  EXPECT_STREQ(\"1st.OnTestIterationStart\", vec[0].c_str());\n  EXPECT_STREQ(\"2nd.OnTestIterationStart\", vec[1].c_str());\n  EXPECT_STREQ(\"3rd.OnTestIterationStart\", vec[2].c_str());\n\n  vec.clear();\n  TestEventListenersAccessor::GetRepeater(&listeners)\n      ->OnTestIterationEnd(*UnitTest::GetInstance(), 0);\n  ASSERT_EQ(3U, vec.size());\n  EXPECT_STREQ(\"3rd.OnTestIterationEnd\", vec[0].c_str());\n  EXPECT_STREQ(\"2nd.OnTestIterationEnd\", vec[1].c_str());\n  EXPECT_STREQ(\"1st.OnTestIterationEnd\", vec[2].c_str());\n}\n\n// Tests that a listener removed from a TestEventListeners list stops receiving\n// events and is not deleted when the list is destroyed.\nTEST(TestEventListenersTest, Release) {\n  int on_start_counter = 0;\n  bool is_destroyed = false;\n  // Although Append passes the ownership of this object to the list,\n  // the following calls release it, and we need to delete it before the\n  // test ends.\n  TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);\n  {\n    TestEventListeners listeners;\n    listeners.Append(listener);\n    EXPECT_EQ(listener, listeners.Release(listener));\n    TestEventListenersAccessor::GetRepeater(&listeners)\n        ->OnTestProgramStart(*UnitTest::GetInstance());\n    EXPECT_TRUE(listeners.Release(listener) == nullptr);\n  }\n  EXPECT_EQ(0, on_start_counter);\n  EXPECT_FALSE(is_destroyed);\n  delete listener;\n}\n\n// Tests that no events are forwarded when event forwarding is disabled.\nTEST(EventListenerTest, SuppressEventForwarding) {\n  int on_start_counter = 0;\n  TestListener* listener = new TestListener(&on_start_counter, nullptr);\n\n  TestEventListeners listeners;\n  listeners.Append(listener);\n  ASSERT_TRUE(TestEventListenersAccessor::EventForwardingEnabled(listeners));\n  TestEventListenersAccessor::SuppressEventForwarding(&listeners);\n  ASSERT_FALSE(TestEventListenersAccessor::EventForwardingEnabled(listeners));\n  TestEventListenersAccessor::GetRepeater(&listeners)\n      ->OnTestProgramStart(*UnitTest::GetInstance());\n  EXPECT_EQ(0, on_start_counter);\n}\n\n// Tests that events generated by Google Test are not forwarded in\n// death test subprocesses.\nTEST(EventListenerDeathTest, EventsNotForwardedInDeathTestSubprecesses) {\n  EXPECT_DEATH_IF_SUPPORTED(\n      {\n        GTEST_CHECK_(TestEventListenersAccessor::EventForwardingEnabled(\n            *GetUnitTestImpl()->listeners()))\n            << \"expected failure\";\n      },\n      \"expected failure\");\n}\n\n// Tests that a listener installed via SetDefaultResultPrinter() starts\n// receiving events and is returned via default_result_printer() and that\n// the previous default_result_printer is removed from the list and deleted.\nTEST(EventListenerTest, default_result_printer) {\n  int on_start_counter = 0;\n  bool is_destroyed = false;\n  TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);\n\n  TestEventListeners listeners;\n  TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);\n\n  EXPECT_EQ(listener, listeners.default_result_printer());\n\n  TestEventListenersAccessor::GetRepeater(&listeners)\n      ->OnTestProgramStart(*UnitTest::GetInstance());\n\n  EXPECT_EQ(1, on_start_counter);\n\n  // Replacing default_result_printer with something else should remove it\n  // from the list and destroy it.\n  TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, nullptr);\n\n  EXPECT_TRUE(listeners.default_result_printer() == nullptr);\n  EXPECT_TRUE(is_destroyed);\n\n  // After broadcasting an event the counter is still the same, indicating\n  // the listener is not in the list anymore.\n  TestEventListenersAccessor::GetRepeater(&listeners)\n      ->OnTestProgramStart(*UnitTest::GetInstance());\n  EXPECT_EQ(1, on_start_counter);\n}\n\n// Tests that the default_result_printer listener stops receiving events\n// when removed via Release and that is not owned by the list anymore.\nTEST(EventListenerTest, RemovingDefaultResultPrinterWorks) {\n  int on_start_counter = 0;\n  bool is_destroyed = false;\n  // Although Append passes the ownership of this object to the list,\n  // the following calls release it, and we need to delete it before the\n  // test ends.\n  TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);\n  {\n    TestEventListeners listeners;\n    TestEventListenersAccessor::SetDefaultResultPrinter(&listeners, listener);\n\n    EXPECT_EQ(listener, listeners.Release(listener));\n    EXPECT_TRUE(listeners.default_result_printer() == nullptr);\n    EXPECT_FALSE(is_destroyed);\n\n    // Broadcasting events now should not affect default_result_printer.\n    TestEventListenersAccessor::GetRepeater(&listeners)\n        ->OnTestProgramStart(*UnitTest::GetInstance());\n    EXPECT_EQ(0, on_start_counter);\n  }\n  // Destroying the list should not affect the listener now, too.\n  EXPECT_FALSE(is_destroyed);\n  delete listener;\n}\n\n// Tests that a listener installed via SetDefaultXmlGenerator() starts\n// receiving events and is returned via default_xml_generator() and that\n// the previous default_xml_generator is removed from the list and deleted.\nTEST(EventListenerTest, default_xml_generator) {\n  int on_start_counter = 0;\n  bool is_destroyed = false;\n  TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);\n\n  TestEventListeners listeners;\n  TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);\n\n  EXPECT_EQ(listener, listeners.default_xml_generator());\n\n  TestEventListenersAccessor::GetRepeater(&listeners)\n      ->OnTestProgramStart(*UnitTest::GetInstance());\n\n  EXPECT_EQ(1, on_start_counter);\n\n  // Replacing default_xml_generator with something else should remove it\n  // from the list and destroy it.\n  TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, nullptr);\n\n  EXPECT_TRUE(listeners.default_xml_generator() == nullptr);\n  EXPECT_TRUE(is_destroyed);\n\n  // After broadcasting an event the counter is still the same, indicating\n  // the listener is not in the list anymore.\n  TestEventListenersAccessor::GetRepeater(&listeners)\n      ->OnTestProgramStart(*UnitTest::GetInstance());\n  EXPECT_EQ(1, on_start_counter);\n}\n\n// Tests that the default_xml_generator listener stops receiving events\n// when removed via Release and that is not owned by the list anymore.\nTEST(EventListenerTest, RemovingDefaultXmlGeneratorWorks) {\n  int on_start_counter = 0;\n  bool is_destroyed = false;\n  // Although Append passes the ownership of this object to the list,\n  // the following calls release it, and we need to delete it before the\n  // test ends.\n  TestListener* listener = new TestListener(&on_start_counter, &is_destroyed);\n  {\n    TestEventListeners listeners;\n    TestEventListenersAccessor::SetDefaultXmlGenerator(&listeners, listener);\n\n    EXPECT_EQ(listener, listeners.Release(listener));\n    EXPECT_TRUE(listeners.default_xml_generator() == nullptr);\n    EXPECT_FALSE(is_destroyed);\n\n    // Broadcasting events now should not affect default_xml_generator.\n    TestEventListenersAccessor::GetRepeater(&listeners)\n        ->OnTestProgramStart(*UnitTest::GetInstance());\n    EXPECT_EQ(0, on_start_counter);\n  }\n  // Destroying the list should not affect the listener now, too.\n  EXPECT_FALSE(is_destroyed);\n  delete listener;\n}\n\n// Tests to ensure that the alternative, verbose spellings of\n// some of the macros work.  We don't test them thoroughly as that\n// would be quite involved.  Since their implementations are\n// straightforward, and they are rarely used, we'll just rely on the\n// users to tell us when they are broken.\nGTEST_TEST(AlternativeNameTest, Works) {  // GTEST_TEST is the same as TEST.\n  GTEST_SUCCEED() << \"OK\";  // GTEST_SUCCEED is the same as SUCCEED.\n\n  // GTEST_FAIL is the same as FAIL.\n  EXPECT_FATAL_FAILURE(GTEST_FAIL() << \"An expected failure\",\n                       \"An expected failure\");\n\n  // GTEST_ASSERT_XY is the same as ASSERT_XY.\n\n  GTEST_ASSERT_EQ(0, 0);\n  EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(0, 1) << \"An expected failure\",\n                       \"An expected failure\");\n  EXPECT_FATAL_FAILURE(GTEST_ASSERT_EQ(1, 0) << \"An expected failure\",\n                       \"An expected failure\");\n\n  GTEST_ASSERT_NE(0, 1);\n  GTEST_ASSERT_NE(1, 0);\n  EXPECT_FATAL_FAILURE(GTEST_ASSERT_NE(0, 0) << \"An expected failure\",\n                       \"An expected failure\");\n\n  GTEST_ASSERT_LE(0, 0);\n  GTEST_ASSERT_LE(0, 1);\n  EXPECT_FATAL_FAILURE(GTEST_ASSERT_LE(1, 0) << \"An expected failure\",\n                       \"An expected failure\");\n\n  GTEST_ASSERT_LT(0, 1);\n  EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(0, 0) << \"An expected failure\",\n                       \"An expected failure\");\n  EXPECT_FATAL_FAILURE(GTEST_ASSERT_LT(1, 0) << \"An expected failure\",\n                       \"An expected failure\");\n\n  GTEST_ASSERT_GE(0, 0);\n  GTEST_ASSERT_GE(1, 0);\n  EXPECT_FATAL_FAILURE(GTEST_ASSERT_GE(0, 1) << \"An expected failure\",\n                       \"An expected failure\");\n\n  GTEST_ASSERT_GT(1, 0);\n  EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(0, 1) << \"An expected failure\",\n                       \"An expected failure\");\n  EXPECT_FATAL_FAILURE(GTEST_ASSERT_GT(1, 1) << \"An expected failure\",\n                       \"An expected failure\");\n}\n\n// Tests for internal utilities necessary for implementation of the universal\n// printing.\n\nclass ConversionHelperBase {};\nclass ConversionHelperDerived : public ConversionHelperBase {};\n\nstruct HasDebugStringMethods {\n  std::string DebugString() const { return \"\"; }\n  std::string ShortDebugString() const { return \"\"; }\n};\n\nstruct InheritsDebugStringMethods : public HasDebugStringMethods {};\n\nstruct WrongTypeDebugStringMethod {\n  std::string DebugString() const { return \"\"; }\n  int ShortDebugString() const { return 1; }\n};\n\nstruct NotConstDebugStringMethod {\n  std::string DebugString() { return \"\"; }\n  std::string ShortDebugString() const { return \"\"; }\n};\n\nstruct MissingDebugStringMethod {\n  std::string DebugString() { return \"\"; }\n};\n\nstruct IncompleteType;\n\n// Tests that HasDebugStringAndShortDebugString<T>::value is a compile-time\n// constant.\nTEST(HasDebugStringAndShortDebugStringTest, ValueIsCompileTimeConstant) {\n  static_assert(HasDebugStringAndShortDebugString<HasDebugStringMethods>::value,\n                \"const_true\");\n  static_assert(\n      HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value,\n      \"const_true\");\n  static_assert(HasDebugStringAndShortDebugString<\n                    const InheritsDebugStringMethods>::value,\n                \"const_true\");\n  static_assert(\n      !HasDebugStringAndShortDebugString<WrongTypeDebugStringMethod>::value,\n      \"const_false\");\n  static_assert(\n      !HasDebugStringAndShortDebugString<NotConstDebugStringMethod>::value,\n      \"const_false\");\n  static_assert(\n      !HasDebugStringAndShortDebugString<MissingDebugStringMethod>::value,\n      \"const_false\");\n  static_assert(!HasDebugStringAndShortDebugString<IncompleteType>::value,\n                \"const_false\");\n  static_assert(!HasDebugStringAndShortDebugString<int>::value, \"const_false\");\n}\n\n// Tests that HasDebugStringAndShortDebugString<T>::value is true when T has\n// needed methods.\nTEST(HasDebugStringAndShortDebugStringTest,\n     ValueIsTrueWhenTypeHasDebugStringAndShortDebugString) {\n  EXPECT_TRUE(\n      HasDebugStringAndShortDebugString<InheritsDebugStringMethods>::value);\n}\n\n// Tests that HasDebugStringAndShortDebugString<T>::value is false when T\n// doesn't have needed methods.\nTEST(HasDebugStringAndShortDebugStringTest,\n     ValueIsFalseWhenTypeIsNotAProtocolMessage) {\n  EXPECT_FALSE(HasDebugStringAndShortDebugString<int>::value);\n  EXPECT_FALSE(\n      HasDebugStringAndShortDebugString<const ConversionHelperBase>::value);\n}\n\n// Tests GTEST_REMOVE_REFERENCE_AND_CONST_.\n\ntemplate <typename T1, typename T2>\nvoid TestGTestRemoveReferenceAndConst() {\n  static_assert(std::is_same<T1, GTEST_REMOVE_REFERENCE_AND_CONST_(T2)>::value,\n                \"GTEST_REMOVE_REFERENCE_AND_CONST_ failed.\");\n}\n\nTEST(RemoveReferenceToConstTest, Works) {\n  TestGTestRemoveReferenceAndConst<int, int>();\n  TestGTestRemoveReferenceAndConst<double, double&>();\n  TestGTestRemoveReferenceAndConst<char, const char>();\n  TestGTestRemoveReferenceAndConst<char, const char&>();\n  TestGTestRemoveReferenceAndConst<const char*, const char*>();\n}\n\n// Tests GTEST_REFERENCE_TO_CONST_.\n\ntemplate <typename T1, typename T2>\nvoid TestGTestReferenceToConst() {\n  static_assert(std::is_same<T1, GTEST_REFERENCE_TO_CONST_(T2)>::value,\n                \"GTEST_REFERENCE_TO_CONST_ failed.\");\n}\n\nTEST(GTestReferenceToConstTest, Works) {\n  TestGTestReferenceToConst<const char&, char>();\n  TestGTestReferenceToConst<const int&, const int>();\n  TestGTestReferenceToConst<const double&, double>();\n  TestGTestReferenceToConst<const std::string&, const std::string&>();\n}\n\n// Tests IsContainerTest.\n\nclass NonContainer {};\n\nTEST(IsContainerTestTest, WorksForNonContainer) {\n  EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<int>(0)));\n  EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<char[5]>(0)));\n  EXPECT_EQ(sizeof(IsNotContainer), sizeof(IsContainerTest<NonContainer>(0)));\n}\n\nTEST(IsContainerTestTest, WorksForContainer) {\n  EXPECT_EQ(sizeof(IsContainer), sizeof(IsContainerTest<std::vector<bool>>(0)));\n  EXPECT_EQ(sizeof(IsContainer),\n            sizeof(IsContainerTest<std::map<int, double>>(0)));\n}\n\nstruct ConstOnlyContainerWithPointerIterator {\n  using const_iterator = int*;\n  const_iterator begin() const;\n  const_iterator end() const;\n};\n\nstruct ConstOnlyContainerWithClassIterator {\n  struct const_iterator {\n    const int& operator*() const;\n    const_iterator& operator++(/* pre-increment */);\n  };\n  const_iterator begin() const;\n  const_iterator end() const;\n};\n\nTEST(IsContainerTestTest, ConstOnlyContainer) {\n  EXPECT_EQ(sizeof(IsContainer),\n            sizeof(IsContainerTest<ConstOnlyContainerWithPointerIterator>(0)));\n  EXPECT_EQ(sizeof(IsContainer),\n            sizeof(IsContainerTest<ConstOnlyContainerWithClassIterator>(0)));\n}\n\n// Tests IsHashTable.\nstruct AHashTable {\n  typedef void hasher;\n};\nstruct NotReallyAHashTable {\n  typedef void hasher;\n  typedef void reverse_iterator;\n};\nTEST(IsHashTable, Basic) {\n  EXPECT_TRUE(testing::internal::IsHashTable<AHashTable>::value);\n  EXPECT_FALSE(testing::internal::IsHashTable<NotReallyAHashTable>::value);\n  EXPECT_FALSE(testing::internal::IsHashTable<std::vector<int>>::value);\n  EXPECT_TRUE(testing::internal::IsHashTable<std::unordered_set<int>>::value);\n}\n\n// Tests ArrayEq().\n\nTEST(ArrayEqTest, WorksForDegeneratedArrays) {\n  EXPECT_TRUE(ArrayEq(5, 5L));\n  EXPECT_FALSE(ArrayEq('a', 0));\n}\n\nTEST(ArrayEqTest, WorksForOneDimensionalArrays) {\n  // Note that a and b are distinct but compatible types.\n  const int a[] = {0, 1};\n  long b[] = {0, 1};\n  EXPECT_TRUE(ArrayEq(a, b));\n  EXPECT_TRUE(ArrayEq(a, 2, b));\n\n  b[0] = 2;\n  EXPECT_FALSE(ArrayEq(a, b));\n  EXPECT_FALSE(ArrayEq(a, 1, b));\n}\n\nTEST(ArrayEqTest, WorksForTwoDimensionalArrays) {\n  const char a[][3] = {\"hi\", \"lo\"};\n  const char b[][3] = {\"hi\", \"lo\"};\n  const char c[][3] = {\"hi\", \"li\"};\n\n  EXPECT_TRUE(ArrayEq(a, b));\n  EXPECT_TRUE(ArrayEq(a, 2, b));\n\n  EXPECT_FALSE(ArrayEq(a, c));\n  EXPECT_FALSE(ArrayEq(a, 2, c));\n}\n\n// Tests ArrayAwareFind().\n\nTEST(ArrayAwareFindTest, WorksForOneDimensionalArray) {\n  const char a[] = \"hello\";\n  EXPECT_EQ(a + 4, ArrayAwareFind(a, a + 5, 'o'));\n  EXPECT_EQ(a + 5, ArrayAwareFind(a, a + 5, 'x'));\n}\n\nTEST(ArrayAwareFindTest, WorksForTwoDimensionalArray) {\n  int a[][2] = {{0, 1}, {2, 3}, {4, 5}};\n  const int b[2] = {2, 3};\n  EXPECT_EQ(a + 1, ArrayAwareFind(a, a + 3, b));\n\n  const int c[2] = {6, 7};\n  EXPECT_EQ(a + 3, ArrayAwareFind(a, a + 3, c));\n}\n\n// Tests CopyArray().\n\nTEST(CopyArrayTest, WorksForDegeneratedArrays) {\n  int n = 0;\n  CopyArray('a', &n);\n  EXPECT_EQ('a', n);\n}\n\nTEST(CopyArrayTest, WorksForOneDimensionalArrays) {\n  const char a[3] = \"hi\";\n  int b[3];\n#ifndef __BORLANDC__  // C++Builder cannot compile some array size deductions.\n  CopyArray(a, &b);\n  EXPECT_TRUE(ArrayEq(a, b));\n#endif\n\n  int c[3];\n  CopyArray(a, 3, c);\n  EXPECT_TRUE(ArrayEq(a, c));\n}\n\nTEST(CopyArrayTest, WorksForTwoDimensionalArrays) {\n  const int a[2][3] = {{0, 1, 2}, {3, 4, 5}};\n  int b[2][3];\n#ifndef __BORLANDC__  // C++Builder cannot compile some array size deductions.\n  CopyArray(a, &b);\n  EXPECT_TRUE(ArrayEq(a, b));\n#endif\n\n  int c[2][3];\n  CopyArray(a, 2, c);\n  EXPECT_TRUE(ArrayEq(a, c));\n}\n\n// Tests NativeArray.\n\nTEST(NativeArrayTest, ConstructorFromArrayWorks) {\n  const int a[3] = {0, 1, 2};\n  NativeArray<int> na(a, 3, RelationToSourceReference());\n  EXPECT_EQ(3U, na.size());\n  EXPECT_EQ(a, na.begin());\n}\n\nTEST(NativeArrayTest, CreatesAndDeletesCopyOfArrayWhenAskedTo) {\n  typedef int Array[2];\n  Array* a = new Array[1];\n  (*a)[0] = 0;\n  (*a)[1] = 1;\n  NativeArray<int> na(*a, 2, RelationToSourceCopy());\n  EXPECT_NE(*a, na.begin());\n  delete[] a;\n  EXPECT_EQ(0, na.begin()[0]);\n  EXPECT_EQ(1, na.begin()[1]);\n\n  // We rely on the heap checker to verify that na deletes the copy of\n  // array.\n}\n\nTEST(NativeArrayTest, TypeMembersAreCorrect) {\n  StaticAssertTypeEq<char, NativeArray<char>::value_type>();\n  StaticAssertTypeEq<int[2], NativeArray<int[2]>::value_type>();\n\n  StaticAssertTypeEq<const char*, NativeArray<char>::const_iterator>();\n  StaticAssertTypeEq<const bool(*)[2], NativeArray<bool[2]>::const_iterator>();\n}\n\nTEST(NativeArrayTest, MethodsWork) {\n  const int a[3] = {0, 1, 2};\n  NativeArray<int> na(a, 3, RelationToSourceCopy());\n  ASSERT_EQ(3U, na.size());\n  EXPECT_EQ(3, na.end() - na.begin());\n\n  NativeArray<int>::const_iterator it = na.begin();\n  EXPECT_EQ(0, *it);\n  ++it;\n  EXPECT_EQ(1, *it);\n  it++;\n  EXPECT_EQ(2, *it);\n  ++it;\n  EXPECT_EQ(na.end(), it);\n\n  EXPECT_TRUE(na == na);\n\n  NativeArray<int> na2(a, 3, RelationToSourceReference());\n  EXPECT_TRUE(na == na2);\n\n  const int b1[3] = {0, 1, 1};\n  const int b2[4] = {0, 1, 2, 3};\n  EXPECT_FALSE(na == NativeArray<int>(b1, 3, RelationToSourceReference()));\n  EXPECT_FALSE(na == NativeArray<int>(b2, 4, RelationToSourceCopy()));\n}\n\nTEST(NativeArrayTest, WorksForTwoDimensionalArray) {\n  const char a[2][3] = {\"hi\", \"lo\"};\n  NativeArray<char[3]> na(a, 2, RelationToSourceReference());\n  ASSERT_EQ(2U, na.size());\n  EXPECT_EQ(a, na.begin());\n}\n\n// IndexSequence\nTEST(IndexSequence, MakeIndexSequence) {\n  using testing::internal::IndexSequence;\n  using testing::internal::MakeIndexSequence;\n  EXPECT_TRUE(\n      (std::is_same<IndexSequence<>, MakeIndexSequence<0>::type>::value));\n  EXPECT_TRUE(\n      (std::is_same<IndexSequence<0>, MakeIndexSequence<1>::type>::value));\n  EXPECT_TRUE(\n      (std::is_same<IndexSequence<0, 1>, MakeIndexSequence<2>::type>::value));\n  EXPECT_TRUE((\n      std::is_same<IndexSequence<0, 1, 2>, MakeIndexSequence<3>::type>::value));\n  EXPECT_TRUE(\n      (std::is_base_of<IndexSequence<0, 1, 2>, MakeIndexSequence<3>>::value));\n}\n\n// ElemFromList\nTEST(ElemFromList, Basic) {\n  using testing::internal::ElemFromList;\n  EXPECT_TRUE(\n      (std::is_same<int, ElemFromList<0, int, double, char>::type>::value));\n  EXPECT_TRUE(\n      (std::is_same<double, ElemFromList<1, int, double, char>::type>::value));\n  EXPECT_TRUE(\n      (std::is_same<char, ElemFromList<2, int, double, char>::type>::value));\n  EXPECT_TRUE((\n      std::is_same<char, ElemFromList<7, int, int, int, int, int, int, int,\n                                      char, int, int, int, int>::type>::value));\n}\n\n// FlatTuple\nTEST(FlatTuple, Basic) {\n  using testing::internal::FlatTuple;\n\n  FlatTuple<int, double, const char*> tuple = {};\n  EXPECT_EQ(0, tuple.Get<0>());\n  EXPECT_EQ(0.0, tuple.Get<1>());\n  EXPECT_EQ(nullptr, tuple.Get<2>());\n\n  tuple = FlatTuple<int, double, const char*>(\n      testing::internal::FlatTupleConstructTag{}, 7, 3.2, \"Foo\");\n  EXPECT_EQ(7, tuple.Get<0>());\n  EXPECT_EQ(3.2, tuple.Get<1>());\n  EXPECT_EQ(std::string(\"Foo\"), tuple.Get<2>());\n\n  tuple.Get<1>() = 5.1;\n  EXPECT_EQ(5.1, tuple.Get<1>());\n}\n\nnamespace {\nstd::string AddIntToString(int i, const std::string& s) {\n  return s + std::to_string(i);\n}\n}  // namespace\n\nTEST(FlatTuple, Apply) {\n  using testing::internal::FlatTuple;\n\n  FlatTuple<int, std::string> tuple{testing::internal::FlatTupleConstructTag{},\n                                    5, \"Hello\"};\n\n  // Lambda.\n  EXPECT_TRUE(tuple.Apply([](int i, const std::string& s) -> bool {\n    return i == static_cast<int>(s.size());\n  }));\n\n  // Function.\n  EXPECT_EQ(tuple.Apply(AddIntToString), \"Hello5\");\n\n  // Mutating operations.\n  tuple.Apply([](int& i, std::string& s) {\n    ++i;\n    s += s;\n  });\n  EXPECT_EQ(tuple.Get<0>(), 6);\n  EXPECT_EQ(tuple.Get<1>(), \"HelloHello\");\n}\n\nstruct ConstructionCounting {\n  ConstructionCounting() { ++default_ctor_calls; }\n  ~ConstructionCounting() { ++dtor_calls; }\n  ConstructionCounting(const ConstructionCounting&) { ++copy_ctor_calls; }\n  ConstructionCounting(ConstructionCounting&&) noexcept { ++move_ctor_calls; }\n  ConstructionCounting& operator=(const ConstructionCounting&) {\n    ++copy_assignment_calls;\n    return *this;\n  }\n  ConstructionCounting& operator=(ConstructionCounting&&) noexcept {\n    ++move_assignment_calls;\n    return *this;\n  }\n\n  static void Reset() {\n    default_ctor_calls = 0;\n    dtor_calls = 0;\n    copy_ctor_calls = 0;\n    move_ctor_calls = 0;\n    copy_assignment_calls = 0;\n    move_assignment_calls = 0;\n  }\n\n  static int default_ctor_calls;\n  static int dtor_calls;\n  static int copy_ctor_calls;\n  static int move_ctor_calls;\n  static int copy_assignment_calls;\n  static int move_assignment_calls;\n};\n\nint ConstructionCounting::default_ctor_calls = 0;\nint ConstructionCounting::dtor_calls = 0;\nint ConstructionCounting::copy_ctor_calls = 0;\nint ConstructionCounting::move_ctor_calls = 0;\nint ConstructionCounting::copy_assignment_calls = 0;\nint ConstructionCounting::move_assignment_calls = 0;\n\nTEST(FlatTuple, ConstructorCalls) {\n  using testing::internal::FlatTuple;\n\n  // Default construction.\n  ConstructionCounting::Reset();\n  { FlatTuple<ConstructionCounting> tuple; }\n  EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);\n  EXPECT_EQ(ConstructionCounting::dtor_calls, 1);\n  EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);\n  EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);\n  EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);\n  EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);\n\n  // Copy construction.\n  ConstructionCounting::Reset();\n  {\n    ConstructionCounting elem;\n    FlatTuple<ConstructionCounting> tuple{\n        testing::internal::FlatTupleConstructTag{}, elem};\n  }\n  EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);\n  EXPECT_EQ(ConstructionCounting::dtor_calls, 2);\n  EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 1);\n  EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);\n  EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);\n  EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);\n\n  // Move construction.\n  ConstructionCounting::Reset();\n  {\n    FlatTuple<ConstructionCounting> tuple{\n        testing::internal::FlatTupleConstructTag{}, ConstructionCounting{}};\n  }\n  EXPECT_EQ(ConstructionCounting::default_ctor_calls, 1);\n  EXPECT_EQ(ConstructionCounting::dtor_calls, 2);\n  EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);\n  EXPECT_EQ(ConstructionCounting::move_ctor_calls, 1);\n  EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);\n  EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);\n\n  // Copy assignment.\n  // TODO(ofats): it should be testing assignment operator of FlatTuple, not its\n  // elements\n  ConstructionCounting::Reset();\n  {\n    FlatTuple<ConstructionCounting> tuple;\n    ConstructionCounting elem;\n    tuple.Get<0>() = elem;\n  }\n  EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2);\n  EXPECT_EQ(ConstructionCounting::dtor_calls, 2);\n  EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);\n  EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);\n  EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 1);\n  EXPECT_EQ(ConstructionCounting::move_assignment_calls, 0);\n\n  // Move assignment.\n  // TODO(ofats): it should be testing assignment operator of FlatTuple, not its\n  // elements\n  ConstructionCounting::Reset();\n  {\n    FlatTuple<ConstructionCounting> tuple;\n    tuple.Get<0>() = ConstructionCounting{};\n  }\n  EXPECT_EQ(ConstructionCounting::default_ctor_calls, 2);\n  EXPECT_EQ(ConstructionCounting::dtor_calls, 2);\n  EXPECT_EQ(ConstructionCounting::copy_ctor_calls, 0);\n  EXPECT_EQ(ConstructionCounting::move_ctor_calls, 0);\n  EXPECT_EQ(ConstructionCounting::copy_assignment_calls, 0);\n  EXPECT_EQ(ConstructionCounting::move_assignment_calls, 1);\n\n  ConstructionCounting::Reset();\n}\n\nTEST(FlatTuple, ManyTypes) {\n  using testing::internal::FlatTuple;\n\n  // Instantiate FlatTuple with 257 ints.\n  // Tests show that we can do it with thousands of elements, but very long\n  // compile times makes it unusuitable for this test.\n#define GTEST_FLAT_TUPLE_INT8 int, int, int, int, int, int, int, int,\n#define GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT8 GTEST_FLAT_TUPLE_INT8\n#define GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT16 GTEST_FLAT_TUPLE_INT16\n#define GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT32 GTEST_FLAT_TUPLE_INT32\n#define GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT64 GTEST_FLAT_TUPLE_INT64\n#define GTEST_FLAT_TUPLE_INT256 GTEST_FLAT_TUPLE_INT128 GTEST_FLAT_TUPLE_INT128\n\n  // Let's make sure that we can have a very long list of types without blowing\n  // up the template instantiation depth.\n  FlatTuple<GTEST_FLAT_TUPLE_INT256 int> tuple;\n\n  tuple.Get<0>() = 7;\n  tuple.Get<99>() = 17;\n  tuple.Get<256>() = 1000;\n  EXPECT_EQ(7, tuple.Get<0>());\n  EXPECT_EQ(17, tuple.Get<99>());\n  EXPECT_EQ(1000, tuple.Get<256>());\n}\n\n// Tests SkipPrefix().\n\nTEST(SkipPrefixTest, SkipsWhenPrefixMatches) {\n  const char* const str = \"hello\";\n\n  const char* p = str;\n  EXPECT_TRUE(SkipPrefix(\"\", &p));\n  EXPECT_EQ(str, p);\n\n  p = str;\n  EXPECT_TRUE(SkipPrefix(\"hell\", &p));\n  EXPECT_EQ(str + 4, p);\n}\n\nTEST(SkipPrefixTest, DoesNotSkipWhenPrefixDoesNotMatch) {\n  const char* const str = \"world\";\n\n  const char* p = str;\n  EXPECT_FALSE(SkipPrefix(\"W\", &p));\n  EXPECT_EQ(str, p);\n\n  p = str;\n  EXPECT_FALSE(SkipPrefix(\"world!\", &p));\n  EXPECT_EQ(str, p);\n}\n\n// Tests ad_hoc_test_result().\nTEST(AdHocTestResultTest, AdHocTestResultForUnitTestDoesNotShowFailure) {\n  const testing::TestResult& test_result =\n      testing::UnitTest::GetInstance()->ad_hoc_test_result();\n  EXPECT_FALSE(test_result.Failed());\n}\n\nclass DynamicUnitTestFixture : public testing::Test {};\n\nclass DynamicTest : public DynamicUnitTestFixture {\n  void TestBody() override { EXPECT_TRUE(true); }\n};\n\nauto* dynamic_test = testing::RegisterTest(\n    \"DynamicUnitTestFixture\", \"DynamicTest\", \"TYPE\", \"VALUE\", __FILE__,\n    __LINE__, []() -> DynamicUnitTestFixture* { return new DynamicTest; });\n\nTEST(RegisterTest, WasRegistered) {\n  auto* unittest = testing::UnitTest::GetInstance();\n  for (int i = 0; i < unittest->total_test_suite_count(); ++i) {\n    auto* tests = unittest->GetTestSuite(i);\n    if (tests->name() != std::string(\"DynamicUnitTestFixture\")) continue;\n    for (int j = 0; j < tests->total_test_count(); ++j) {\n      if (tests->GetTestInfo(j)->name() != std::string(\"DynamicTest\")) continue;\n      // Found it.\n      EXPECT_STREQ(tests->GetTestInfo(j)->value_param(), \"VALUE\");\n      EXPECT_STREQ(tests->GetTestInfo(j)->type_param(), \"TYPE\");\n      return;\n    }\n  }\n\n  FAIL() << \"Didn't find the test!\";\n}\n\n// Test that the pattern globbing algorithm is linear. If not, this test should\n// time out.\nTEST(PatternGlobbingTest, MatchesFilterLinearRuntime) {\n  std::string name(100, 'a');  // Construct the string (a^100)b\n  name.push_back('b');\n\n  std::string pattern;  // Construct the string ((a*)^100)b\n  for (int i = 0; i < 100; ++i) {\n    pattern.append(\"a*\");\n  }\n  pattern.push_back('b');\n\n  EXPECT_TRUE(\n      testing::internal::UnitTestOptions::MatchesFilter(name, pattern.c_str()));\n}\n\nTEST(PatternGlobbingTest, MatchesFilterWithMultiplePatterns) {\n  const std::string name = \"aaaa\";\n  EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(name, \"a*\"));\n  EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(name, \"a*:\"));\n  EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter(name, \"ab\"));\n  EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter(name, \"ab:\"));\n  EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(name, \"ab:a*\"));\n}\n\nTEST(PatternGlobbingTest, MatchesFilterEdgeCases) {\n  EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter(\"\", \"*a\"));\n  EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(\"\", \"*\"));\n  EXPECT_FALSE(testing::internal::UnitTestOptions::MatchesFilter(\"a\", \"\"));\n  EXPECT_TRUE(testing::internal::UnitTestOptions::MatchesFilter(\"\", \"\"));\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_xml_outfile1_test_.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// gtest_xml_outfile1_test_ writes some xml via TestProperty used by\n// gtest_xml_outfiles_test.py\n\n#include \"gtest/gtest.h\"\n\nclass PropertyOne : public testing::Test {\n protected:\n  void SetUp() override { RecordProperty(\"SetUpProp\", 1); }\n  void TearDown() override { RecordProperty(\"TearDownProp\", 1); }\n};\n\nTEST_F(PropertyOne, TestSomeProperties) {\n  RecordProperty(\"TestSomeProperty\", 1);\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_xml_outfile2_test_.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// gtest_xml_outfile2_test_ writes some xml via TestProperty used by\n// gtest_xml_outfiles_test.py\n\n#include \"gtest/gtest.h\"\n\nclass PropertyTwo : public testing::Test {\n protected:\n  void SetUp() override { RecordProperty(\"SetUpProp\", 2); }\n  void TearDown() override { RecordProperty(\"TearDownProp\", 2); }\n};\n\nTEST_F(PropertyTwo, TestSomeProperties) {\n  RecordProperty(\"TestSomeProperty\", 2);\n}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_xml_outfiles_test.py",
    "content": "#!/usr/bin/env python\n#\n# Copyright 2008, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Unit test for the gtest_xml_output module.\"\"\"\n\nimport os\nfrom xml.dom import minidom, Node\nfrom googletest.test import gtest_test_utils\nfrom googletest.test import gtest_xml_test_utils\n\nGTEST_OUTPUT_SUBDIR = \"xml_outfiles\"\nGTEST_OUTPUT_1_TEST = \"gtest_xml_outfile1_test_\"\nGTEST_OUTPUT_2_TEST = \"gtest_xml_outfile2_test_\"\n\nEXPECTED_XML_1 = \"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<testsuites tests=\"1\" failures=\"0\" disabled=\"0\" errors=\"0\" time=\"*\" timestamp=\"*\" name=\"AllTests\">\n  <testsuite name=\"PropertyOne\" tests=\"1\" failures=\"0\" skipped=\"0\" disabled=\"0\" errors=\"0\" time=\"*\" timestamp=\"*\">\n    <testcase name=\"TestSomeProperties\" file=\"gtest_xml_outfile1_test_.cc\" line=\"41\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"PropertyOne\">\n      <properties>\n        <property name=\"SetUpProp\" value=\"1\"/>\n        <property name=\"TestSomeProperty\" value=\"1\"/>\n        <property name=\"TearDownProp\" value=\"1\"/>\n      </properties>\n    </testcase>\n  </testsuite>\n</testsuites>\n\"\"\"\n\nEXPECTED_XML_2 = \"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<testsuites tests=\"1\" failures=\"0\" disabled=\"0\" errors=\"0\" time=\"*\" timestamp=\"*\" name=\"AllTests\">\n  <testsuite name=\"PropertyTwo\" tests=\"1\" failures=\"0\" skipped=\"0\" disabled=\"0\" errors=\"0\" time=\"*\" timestamp=\"*\">\n    <testcase name=\"TestSomeProperties\" file=\"gtest_xml_outfile2_test_.cc\" line=\"41\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"PropertyTwo\">\n      <properties>\n        <property name=\"SetUpProp\" value=\"2\"/>\n        <property name=\"TestSomeProperty\" value=\"2\"/>\n        <property name=\"TearDownProp\" value=\"2\"/>\n      </properties>\n    </testcase>\n  </testsuite>\n</testsuites>\n\"\"\"\n\n\nclass GTestXMLOutFilesTest(gtest_xml_test_utils.GTestXMLTestCase):\n  \"\"\"Unit test for Google Test's XML output functionality.\"\"\"\n\n  def setUp(self):\n    # We want the trailing '/' that the last \"\" provides in os.path.join, for\n    # telling Google Test to create an output directory instead of a single file\n    # for xml output.\n    self.output_dir_ = os.path.join(gtest_test_utils.GetTempDir(),\n                                    GTEST_OUTPUT_SUBDIR, \"\")\n    self.DeleteFilesAndDir()\n\n  def tearDown(self):\n    self.DeleteFilesAndDir()\n\n  def DeleteFilesAndDir(self):\n    try:\n      os.remove(os.path.join(self.output_dir_, GTEST_OUTPUT_1_TEST + \".xml\"))\n    except os.error:\n      pass\n    try:\n      os.remove(os.path.join(self.output_dir_, GTEST_OUTPUT_2_TEST + \".xml\"))\n    except os.error:\n      pass\n    try:\n      os.rmdir(self.output_dir_)\n    except os.error:\n      pass\n\n  def testOutfile1(self):\n    self._TestOutFile(GTEST_OUTPUT_1_TEST, EXPECTED_XML_1)\n\n  def testOutfile2(self):\n    self._TestOutFile(GTEST_OUTPUT_2_TEST, EXPECTED_XML_2)\n\n  def _TestOutFile(self, test_name, expected_xml):\n    gtest_prog_path = gtest_test_utils.GetTestExecutablePath(test_name)\n    command = [gtest_prog_path, \"--gtest_output=xml:%s\" % self.output_dir_]\n    p = gtest_test_utils.Subprocess(command,\n                                    working_dir=gtest_test_utils.GetTempDir())\n    self.assert_(p.exited)\n    self.assertEquals(0, p.exit_code)\n\n    output_file_name1 = test_name + \".xml\"\n    output_file1 = os.path.join(self.output_dir_, output_file_name1)\n    output_file_name2 = 'lt-' + output_file_name1\n    output_file2 = os.path.join(self.output_dir_, output_file_name2)\n    self.assert_(os.path.isfile(output_file1) or os.path.isfile(output_file2),\n                 output_file1)\n\n    expected = minidom.parseString(expected_xml)\n    if os.path.isfile(output_file1):\n      actual = minidom.parse(output_file1)\n    else:\n      actual = minidom.parse(output_file2)\n    self.NormalizeXml(actual.documentElement)\n    self.AssertEquivalentNodes(expected.documentElement,\n                               actual.documentElement)\n    expected.unlink()\n    actual.unlink()\n\n\nif __name__ == \"__main__\":\n  os.environ[\"GTEST_STACK_TRACE_DEPTH\"] = \"0\"\n  gtest_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_xml_output_unittest.py",
    "content": "#!/usr/bin/env python\n#\n# Copyright 2006, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Unit test for the gtest_xml_output module\"\"\"\n\nimport datetime\nimport errno\nimport os\nimport re\nimport sys\nfrom xml.dom import minidom, Node\n\nfrom googletest.test import gtest_test_utils\nfrom googletest.test import gtest_xml_test_utils\n\nGTEST_FILTER_FLAG = '--gtest_filter'\nGTEST_LIST_TESTS_FLAG = '--gtest_list_tests'\nGTEST_OUTPUT_FLAG = '--gtest_output'\nGTEST_DEFAULT_OUTPUT_FILE = 'test_detail.xml'\nGTEST_PROGRAM_NAME = 'gtest_xml_output_unittest_'\n\n# The flag indicating stacktraces are not supported\nNO_STACKTRACE_SUPPORT_FLAG = '--no_stacktrace_support'\n\n# The environment variables for test sharding.\nTOTAL_SHARDS_ENV_VAR = 'GTEST_TOTAL_SHARDS'\nSHARD_INDEX_ENV_VAR = 'GTEST_SHARD_INDEX'\nSHARD_STATUS_FILE_ENV_VAR = 'GTEST_SHARD_STATUS_FILE'\n\nSUPPORTS_STACK_TRACES = NO_STACKTRACE_SUPPORT_FLAG not in sys.argv\n\nif SUPPORTS_STACK_TRACES:\n  STACK_TRACE_TEMPLATE = '\\nStack trace:\\n*'\nelse:\n  STACK_TRACE_TEMPLATE = ''\n  # unittest.main() can't handle unknown flags\n  sys.argv.remove(NO_STACKTRACE_SUPPORT_FLAG)\n\nEXPECTED_NON_EMPTY_XML = \"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<testsuites tests=\"26\" failures=\"5\" disabled=\"2\" errors=\"0\" time=\"*\" timestamp=\"*\" name=\"AllTests\" ad_hoc_property=\"42\">\n  <testsuite name=\"SuccessfulTest\" tests=\"1\" failures=\"0\" disabled=\"0\" skipped=\"0\" errors=\"0\" time=\"*\" timestamp=\"*\">\n    <testcase name=\"Succeeds\" file=\"gtest_xml_output_unittest_.cc\" line=\"51\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"SuccessfulTest\"/>\n  </testsuite>\n  <testsuite name=\"FailedTest\" tests=\"1\" failures=\"1\" disabled=\"0\" skipped=\"0\" errors=\"0\" time=\"*\" timestamp=\"*\">\n    <testcase name=\"Fails\" file=\"gtest_xml_output_unittest_.cc\" line=\"59\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"FailedTest\">\n      <failure message=\"gtest_xml_output_unittest_.cc:*&#x0A;Expected equality of these values:&#x0A;  1&#x0A;  2\" type=\"\"><![CDATA[gtest_xml_output_unittest_.cc:*\nExpected equality of these values:\n  1\n  2%(stack)s]]></failure>\n    </testcase>\n  </testsuite>\n  <testsuite name=\"MixedResultTest\" tests=\"3\" failures=\"1\" disabled=\"1\" skipped=\"0\" errors=\"0\" time=\"*\" timestamp=\"*\">\n    <testcase name=\"Succeeds\" file=\"gtest_xml_output_unittest_.cc\" line=\"86\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"MixedResultTest\"/>\n    <testcase name=\"Fails\" file=\"gtest_xml_output_unittest_.cc\" line=\"91\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"MixedResultTest\">\n      <failure message=\"gtest_xml_output_unittest_.cc:*&#x0A;Expected equality of these values:&#x0A;  1&#x0A;  2\" type=\"\"><![CDATA[gtest_xml_output_unittest_.cc:*\nExpected equality of these values:\n  1\n  2%(stack)s]]></failure>\n      <failure message=\"gtest_xml_output_unittest_.cc:*&#x0A;Expected equality of these values:&#x0A;  2&#x0A;  3\" type=\"\"><![CDATA[gtest_xml_output_unittest_.cc:*\nExpected equality of these values:\n  2\n  3%(stack)s]]></failure>\n    </testcase>\n    <testcase name=\"DISABLED_test\" file=\"gtest_xml_output_unittest_.cc\" line=\"96\" status=\"notrun\" result=\"suppressed\" time=\"*\" timestamp=\"*\" classname=\"MixedResultTest\"/>\n  </testsuite>\n  <testsuite name=\"XmlQuotingTest\" tests=\"1\" failures=\"1\" disabled=\"0\" skipped=\"0\" errors=\"0\" time=\"*\" timestamp=\"*\">\n    <testcase name=\"OutputsCData\" file=\"gtest_xml_output_unittest_.cc\" line=\"100\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"XmlQuotingTest\">\n      <failure message=\"gtest_xml_output_unittest_.cc:*&#x0A;Failed&#x0A;XML output: &lt;?xml encoding=&quot;utf-8&quot;&gt;&lt;top&gt;&lt;![CDATA[cdata text]]&gt;&lt;/top&gt;\" type=\"\"><![CDATA[gtest_xml_output_unittest_.cc:*\nFailed\nXML output: <?xml encoding=\"utf-8\"><top><![CDATA[cdata text]]>]]&gt;<![CDATA[</top>%(stack)s]]></failure>\n    </testcase>\n  </testsuite>\n  <testsuite name=\"InvalidCharactersTest\" tests=\"1\" failures=\"1\" disabled=\"0\" skipped=\"0\" errors=\"0\" time=\"*\" timestamp=\"*\">\n    <testcase name=\"InvalidCharactersInMessage\" file=\"gtest_xml_output_unittest_.cc\" line=\"107\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"InvalidCharactersTest\">\n      <failure message=\"gtest_xml_output_unittest_.cc:*&#x0A;Failed&#x0A;Invalid characters in brackets []\" type=\"\"><![CDATA[gtest_xml_output_unittest_.cc:*\nFailed\nInvalid characters in brackets []%(stack)s]]></failure>\n    </testcase>\n  </testsuite>\n  <testsuite name=\"DisabledTest\" tests=\"1\" failures=\"0\" disabled=\"1\" skipped=\"0\" errors=\"0\" time=\"*\" timestamp=\"*\">\n    <testcase name=\"DISABLED_test_not_run\" file=\"gtest_xml_output_unittest_.cc\" line=\"66\" status=\"notrun\" result=\"suppressed\" time=\"*\" timestamp=\"*\" classname=\"DisabledTest\"/>\n  </testsuite>\n  <testsuite name=\"SkippedTest\" tests=\"3\" failures=\"1\" disabled=\"0\" skipped=\"2\" errors=\"0\" time=\"*\" timestamp=\"*\">\n    <testcase name=\"Skipped\" status=\"run\" file=\"gtest_xml_output_unittest_.cc\" line=\"73\" result=\"skipped\" time=\"*\" timestamp=\"*\" classname=\"SkippedTest\">\n      <skipped message=\"gtest_xml_output_unittest_.cc:*&#x0A;\"><![CDATA[gtest_xml_output_unittest_.cc:*\n%(stack)s]]></skipped>\n    </testcase>\n    <testcase name=\"SkippedWithMessage\" file=\"gtest_xml_output_unittest_.cc\" line=\"77\" status=\"run\" result=\"skipped\" time=\"*\" timestamp=\"*\" classname=\"SkippedTest\">\n      <skipped message=\"gtest_xml_output_unittest_.cc:*&#x0A;It is good practice to tell why you skip a test.\"><![CDATA[gtest_xml_output_unittest_.cc:*\nIt is good practice to tell why you skip a test.%(stack)s]]></skipped>\n    </testcase>\n    <testcase name=\"SkippedAfterFailure\" file=\"gtest_xml_output_unittest_.cc\" line=\"81\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"SkippedTest\">\n      <failure message=\"gtest_xml_output_unittest_.cc:*&#x0A;Expected equality of these values:&#x0A;  1&#x0A;  2\" type=\"\"><![CDATA[gtest_xml_output_unittest_.cc:*\nExpected equality of these values:\n  1\n  2%(stack)s]]></failure>\n      <skipped message=\"gtest_xml_output_unittest_.cc:*&#x0A;It is good practice to tell why you skip a test.\"><![CDATA[gtest_xml_output_unittest_.cc:*\nIt is good practice to tell why you skip a test.%(stack)s]]></skipped>\n    </testcase>\n\n  </testsuite>\n  <testsuite name=\"PropertyRecordingTest\" tests=\"4\" failures=\"0\" disabled=\"0\" skipped=\"0\" errors=\"0\" time=\"*\" timestamp=\"*\" SetUpTestSuite=\"yes\" TearDownTestSuite=\"aye\">\n    <testcase name=\"OneProperty\" file=\"gtest_xml_output_unittest_.cc\" line=\"119\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"PropertyRecordingTest\">\n      <properties>\n        <property name=\"key_1\" value=\"1\"/>\n      </properties>\n    </testcase>\n    <testcase name=\"IntValuedProperty\" file=\"gtest_xml_output_unittest_.cc\" line=\"123\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"PropertyRecordingTest\">\n      <properties>\n        <property name=\"key_int\" value=\"1\"/>\n      </properties>\n    </testcase>\n    <testcase name=\"ThreeProperties\" file=\"gtest_xml_output_unittest_.cc\" line=\"127\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"PropertyRecordingTest\">\n      <properties>\n        <property name=\"key_1\" value=\"1\"/>\n        <property name=\"key_2\" value=\"2\"/>\n        <property name=\"key_3\" value=\"3\"/>\n      </properties>\n    </testcase>\n    <testcase name=\"TwoValuesForOneKeyUsesLastValue\" file=\"gtest_xml_output_unittest_.cc\" line=\"133\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"PropertyRecordingTest\">\n      <properties>\n        <property name=\"key_1\" value=\"2\"/>\n      </properties>\n    </testcase>\n  </testsuite>\n  <testsuite name=\"NoFixtureTest\" tests=\"3\" failures=\"0\" disabled=\"0\" skipped=\"0\" errors=\"0\" time=\"*\" timestamp=\"*\">\n     <testcase name=\"RecordProperty\" file=\"gtest_xml_output_unittest_.cc\" line=\"138\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"NoFixtureTest\">\n       <properties>\n         <property name=\"key\" value=\"1\"/>\n       </properties>\n     </testcase>\n     <testcase name=\"ExternalUtilityThatCallsRecordIntValuedProperty\" file=\"gtest_xml_output_unittest_.cc\" line=\"151\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"NoFixtureTest\">\n       <properties>\n         <property name=\"key_for_utility_int\" value=\"1\"/>\n       </properties>\n     </testcase>\n     <testcase name=\"ExternalUtilityThatCallsRecordStringValuedProperty\" file=\"gtest_xml_output_unittest_.cc\" line=\"155\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"NoFixtureTest\">\n       <properties>\n         <property name=\"key_for_utility_string\" value=\"1\"/>\n       </properties>\n     </testcase>\n  </testsuite>\n  <testsuite name=\"Single/ValueParamTest\" tests=\"4\" failures=\"0\" disabled=\"0\" skipped=\"0\" errors=\"0\" time=\"*\" timestamp=\"*\">\n    <testcase name=\"HasValueParamAttribute/0\" file=\"gtest_xml_output_unittest_.cc\" line=\"162\" value_param=\"33\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"Single/ValueParamTest\" />\n    <testcase name=\"HasValueParamAttribute/1\" file=\"gtest_xml_output_unittest_.cc\" line=\"162\" value_param=\"42\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"Single/ValueParamTest\" />\n    <testcase name=\"AnotherTestThatHasValueParamAttribute/0\" file=\"gtest_xml_output_unittest_.cc\" line=\"163\" value_param=\"33\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"Single/ValueParamTest\" />\n    <testcase name=\"AnotherTestThatHasValueParamAttribute/1\" file=\"gtest_xml_output_unittest_.cc\" line=\"163\" value_param=\"42\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"Single/ValueParamTest\" />\n  </testsuite>\n  <testsuite name=\"TypedTest/0\" tests=\"1\" failures=\"0\" disabled=\"0\" skipped=\"0\" errors=\"0\" time=\"*\" timestamp=\"*\">\n    <testcase name=\"HasTypeParamAttribute\" file=\"gtest_xml_output_unittest_.cc\" line=\"171\" type_param=\"*\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"TypedTest/0\" />\n  </testsuite>\n  <testsuite name=\"TypedTest/1\" tests=\"1\" failures=\"0\" disabled=\"0\" skipped=\"0\" errors=\"0\" time=\"*\" timestamp=\"*\">\n    <testcase name=\"HasTypeParamAttribute\" file=\"gtest_xml_output_unittest_.cc\" line=\"171\" type_param=\"*\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"TypedTest/1\" />\n  </testsuite>\n  <testsuite name=\"Single/TypeParameterizedTestSuite/0\" tests=\"1\" failures=\"0\" disabled=\"0\" skipped=\"0\" errors=\"0\" time=\"*\" timestamp=\"*\">\n    <testcase name=\"HasTypeParamAttribute\" file=\"gtest_xml_output_unittest_.cc\" line=\"178\" type_param=\"*\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"Single/TypeParameterizedTestSuite/0\" />\n  </testsuite>\n  <testsuite name=\"Single/TypeParameterizedTestSuite/1\" tests=\"1\" failures=\"0\" disabled=\"0\" skipped=\"0\" errors=\"0\" time=\"*\" timestamp=\"*\">\n    <testcase name=\"HasTypeParamAttribute\" file=\"gtest_xml_output_unittest_.cc\" line=\"178\" type_param=\"*\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"Single/TypeParameterizedTestSuite/1\" />\n  </testsuite>\n</testsuites>\"\"\" % {\n    'stack': STACK_TRACE_TEMPLATE\n}\n\nEXPECTED_FILTERED_TEST_XML = \"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<testsuites tests=\"1\" failures=\"0\" disabled=\"0\" errors=\"0\" time=\"*\"\n            timestamp=\"*\" name=\"AllTests\" ad_hoc_property=\"42\">\n  <testsuite name=\"SuccessfulTest\" tests=\"1\" failures=\"0\" disabled=\"0\" skipped=\"0\"\n             errors=\"0\" time=\"*\" timestamp=\"*\">\n    <testcase name=\"Succeeds\" file=\"gtest_xml_output_unittest_.cc\" line=\"51\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"SuccessfulTest\"/>\n  </testsuite>\n</testsuites>\"\"\"\n\nEXPECTED_SHARDED_TEST_XML = \"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<testsuites tests=\"3\" failures=\"0\" disabled=\"0\" errors=\"0\" time=\"*\" timestamp=\"*\" name=\"AllTests\" ad_hoc_property=\"42\">\n  <testsuite name=\"SuccessfulTest\" tests=\"1\" failures=\"0\" disabled=\"0\" skipped=\"0\" errors=\"0\" time=\"*\" timestamp=\"*\">\n    <testcase name=\"Succeeds\" file=\"gtest_xml_output_unittest_.cc\" line=\"51\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"SuccessfulTest\"/>\n  </testsuite>\n  <testsuite name=\"PropertyRecordingTest\" tests=\"1\" failures=\"0\" disabled=\"0\" skipped=\"0\" errors=\"0\" time=\"*\" timestamp=\"*\" SetUpTestSuite=\"yes\" TearDownTestSuite=\"aye\">\n    <testcase name=\"IntValuedProperty\" file=\"gtest_xml_output_unittest_.cc\" line=\"123\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"PropertyRecordingTest\">\n      <properties>\n        <property name=\"key_int\" value=\"1\"/>\n      </properties>\n    </testcase>\n  </testsuite>\n  <testsuite name=\"Single/ValueParamTest\" tests=\"1\" failures=\"0\" disabled=\"0\" skipped=\"0\" errors=\"0\" time=\"*\" timestamp=\"*\">\n    <testcase name=\"HasValueParamAttribute/0\" file=\"gtest_xml_output_unittest_.cc\" line=\"162\" value_param=\"33\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"Single/ValueParamTest\" />\n  </testsuite>\n</testsuites>\"\"\"\n\nEXPECTED_NO_TEST_XML = \"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<testsuites tests=\"0\" failures=\"0\" disabled=\"0\" errors=\"0\" time=\"*\"\n            timestamp=\"*\" name=\"AllTests\">\n  <testsuite name=\"NonTestSuiteFailure\" tests=\"1\" failures=\"1\" disabled=\"0\" skipped=\"0\" errors=\"0\" time=\"*\" timestamp=\"*\">\n    <testcase name=\"\" status=\"run\" result=\"completed\" time=\"*\" timestamp=\"*\" classname=\"\">\n      <failure message=\"gtest_no_test_unittest.cc:*&#x0A;Expected equality of these values:&#x0A;  1&#x0A;  2\" type=\"\"><![CDATA[gtest_no_test_unittest.cc:*\nExpected equality of these values:\n  1\n  2%(stack)s]]></failure>\n    </testcase>\n  </testsuite>\n</testsuites>\"\"\" % {\n    'stack': STACK_TRACE_TEMPLATE\n}\n\nGTEST_PROGRAM_PATH = gtest_test_utils.GetTestExecutablePath(GTEST_PROGRAM_NAME)\n\nSUPPORTS_TYPED_TESTS = 'TypedTest' in gtest_test_utils.Subprocess(\n    [GTEST_PROGRAM_PATH, GTEST_LIST_TESTS_FLAG], capture_stderr=False).output\n\n\nclass GTestXMLOutputUnitTest(gtest_xml_test_utils.GTestXMLTestCase):\n  \"\"\"\n  Unit test for Google Test's XML output functionality.\n  \"\"\"\n\n  # This test currently breaks on platforms that do not support typed and\n  # type-parameterized tests, so we don't run it under them.\n  if SUPPORTS_TYPED_TESTS:\n    def testNonEmptyXmlOutput(self):\n      \"\"\"\n      Runs a test program that generates a non-empty XML output, and\n      tests that the XML output is expected.\n      \"\"\"\n      self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_NON_EMPTY_XML, 1)\n\n  def testNoTestXmlOutput(self):\n    \"\"\"Verifies XML output for a Google Test binary without actual tests.\n\n    Runs a test program that generates an XML output for a binary without tests,\n    and tests that the XML output is expected.\n    \"\"\"\n\n    self._TestXmlOutput('gtest_no_test_unittest', EXPECTED_NO_TEST_XML, 0)\n\n  def testTimestampValue(self):\n    \"\"\"Checks whether the timestamp attribute in the XML output is valid.\n\n    Runs a test program that generates an empty XML output, and checks if\n    the timestamp attribute in the testsuites tag is valid.\n    \"\"\"\n    actual = self._GetXmlOutput('gtest_no_test_unittest', [], {}, 0)\n    date_time_str = actual.documentElement.getAttributeNode('timestamp').value\n    # datetime.strptime() is only available in Python 2.5+ so we have to\n    # parse the expected datetime manually.\n    match = re.match(r'(\\d+)-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d):(\\d\\d)', date_time_str)\n    self.assertTrue(\n        re.match,\n        'XML datettime string %s has incorrect format' % date_time_str)\n    date_time_from_xml = datetime.datetime(\n        year=int(match.group(1)), month=int(match.group(2)),\n        day=int(match.group(3)), hour=int(match.group(4)),\n        minute=int(match.group(5)), second=int(match.group(6)))\n\n    time_delta = abs(datetime.datetime.now() - date_time_from_xml)\n    # timestamp value should be near the current local time\n    self.assertTrue(time_delta < datetime.timedelta(seconds=600),\n                    'time_delta is %s' % time_delta)\n    actual.unlink()\n\n  def testDefaultOutputFile(self):\n    \"\"\"\n    Confirms that Google Test produces an XML output file with the expected\n    default name if no name is explicitly specified.\n    \"\"\"\n    output_file = os.path.join(gtest_test_utils.GetTempDir(),\n                               GTEST_DEFAULT_OUTPUT_FILE)\n    gtest_prog_path = gtest_test_utils.GetTestExecutablePath(\n        'gtest_no_test_unittest')\n    try:\n      os.remove(output_file)\n    except OSError:\n      e = sys.exc_info()[1]\n      if e.errno != errno.ENOENT:\n        raise\n\n    p = gtest_test_utils.Subprocess(\n        [gtest_prog_path, '%s=xml' % GTEST_OUTPUT_FLAG],\n        working_dir=gtest_test_utils.GetTempDir())\n    self.assert_(p.exited)\n    self.assertEquals(0, p.exit_code)\n    self.assert_(os.path.isfile(output_file))\n\n  def testSuppressedXmlOutput(self):\n    \"\"\"\n    Tests that no XML file is generated if the default XML listener is\n    shut down before RUN_ALL_TESTS is invoked.\n    \"\"\"\n\n    xml_path = os.path.join(gtest_test_utils.GetTempDir(),\n                            GTEST_PROGRAM_NAME + 'out.xml')\n    if os.path.isfile(xml_path):\n      os.remove(xml_path)\n\n    command = [GTEST_PROGRAM_PATH,\n               '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path),\n               '--shut_down_xml']\n    p = gtest_test_utils.Subprocess(command)\n    if p.terminated_by_signal:\n      # p.signal is available only if p.terminated_by_signal is True.\n      self.assertFalse(\n          p.terminated_by_signal,\n          '%s was killed by signal %d' % (GTEST_PROGRAM_NAME, p.signal))\n    else:\n      self.assert_(p.exited)\n      self.assertEquals(1, p.exit_code,\n                        \"'%s' exited with code %s, which doesn't match \"\n                        'the expected exit code %s.'\n                        % (command, p.exit_code, 1))\n\n    self.assert_(not os.path.isfile(xml_path))\n\n  def testFilteredTestXmlOutput(self):\n    \"\"\"Verifies XML output when a filter is applied.\n\n    Runs a test program that executes only some tests and verifies that\n    non-selected tests do not show up in the XML output.\n    \"\"\"\n\n    self._TestXmlOutput(GTEST_PROGRAM_NAME, EXPECTED_FILTERED_TEST_XML, 0,\n                        extra_args=['%s=SuccessfulTest.*' % GTEST_FILTER_FLAG])\n\n  def testShardedTestXmlOutput(self):\n    \"\"\"Verifies XML output when run using multiple shards.\n\n    Runs a test program that executes only one shard and verifies that tests\n    from other shards do not show up in the XML output.\n    \"\"\"\n\n    self._TestXmlOutput(\n        GTEST_PROGRAM_NAME,\n        EXPECTED_SHARDED_TEST_XML,\n        0,\n        extra_env={SHARD_INDEX_ENV_VAR: '0',\n                   TOTAL_SHARDS_ENV_VAR: '10'})\n\n  def _GetXmlOutput(self, gtest_prog_name, extra_args, extra_env,\n                    expected_exit_code):\n    \"\"\"\n    Returns the xml output generated by running the program gtest_prog_name.\n    Furthermore, the program's exit code must be expected_exit_code.\n    \"\"\"\n    xml_path = os.path.join(gtest_test_utils.GetTempDir(),\n                            gtest_prog_name + 'out.xml')\n    gtest_prog_path = gtest_test_utils.GetTestExecutablePath(gtest_prog_name)\n\n    command = ([gtest_prog_path, '%s=xml:%s' % (GTEST_OUTPUT_FLAG, xml_path)] +\n               extra_args)\n    environ_copy = os.environ.copy()\n    if extra_env:\n      environ_copy.update(extra_env)\n    p = gtest_test_utils.Subprocess(command, env=environ_copy)\n\n    if p.terminated_by_signal:\n      self.assert_(False,\n                   '%s was killed by signal %d' % (gtest_prog_name, p.signal))\n    else:\n      self.assert_(p.exited)\n      self.assertEquals(expected_exit_code, p.exit_code,\n                        \"'%s' exited with code %s, which doesn't match \"\n                        'the expected exit code %s.'\n                        % (command, p.exit_code, expected_exit_code))\n    actual = minidom.parse(xml_path)\n    return actual\n\n  def _TestXmlOutput(self, gtest_prog_name, expected_xml,\n                     expected_exit_code, extra_args=None, extra_env=None):\n    \"\"\"\n    Asserts that the XML document generated by running the program\n    gtest_prog_name matches expected_xml, a string containing another\n    XML document.  Furthermore, the program's exit code must be\n    expected_exit_code.\n    \"\"\"\n\n    actual = self._GetXmlOutput(gtest_prog_name, extra_args or [],\n                                extra_env or {}, expected_exit_code)\n    expected = minidom.parseString(expected_xml)\n    self.NormalizeXml(actual.documentElement)\n    self.AssertEquivalentNodes(expected.documentElement,\n                               actual.documentElement)\n    expected.unlink()\n    actual.unlink()\n\n\nif __name__ == '__main__':\n  os.environ['GTEST_STACK_TRACE_DEPTH'] = '1'\n  gtest_test_utils.Main()\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_xml_output_unittest_.cc",
    "content": "// Copyright 2006, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Unit test for Google Test XML output.\n//\n// A user can specify XML output in a Google Test program to run via\n// either the GTEST_OUTPUT environment variable or the --gtest_output\n// flag.  This is used for testing such functionality.\n//\n// This program will be invoked from a Python unit test.  Don't run it\n// directly.\n// clang-format off\n\n#include \"gtest/gtest.h\"\n\nusing ::testing::InitGoogleTest;\nusing ::testing::Test;\nusing ::testing::TestEventListeners;\nusing ::testing::TestWithParam;\nusing ::testing::UnitTest;\nusing ::testing::Values;\n\nclass SuccessfulTest : public Test {};\n\nTEST_F(SuccessfulTest, Succeeds) {\n  SUCCEED() << \"This is a success.\";\n  ASSERT_EQ(1, 1);\n}\n\nclass FailedTest : public Test {\n};\n\nTEST_F(FailedTest, Fails) {\n  ASSERT_EQ(1, 2);\n}\n\nclass DisabledTest : public Test {\n};\n\nTEST_F(DisabledTest, DISABLED_test_not_run) {\n  FAIL() << \"Unexpected failure: Disabled test should not be run\";\n}\n\nclass SkippedTest : public Test {\n};\n\nTEST_F(SkippedTest, Skipped) {\n  GTEST_SKIP();\n}\n\nTEST_F(SkippedTest, SkippedWithMessage) {\n  GTEST_SKIP() << \"It is good practice to tell why you skip a test.\";\n}\n\nTEST_F(SkippedTest, SkippedAfterFailure) {\n  EXPECT_EQ(1, 2);\n  GTEST_SKIP() << \"It is good practice to tell why you skip a test.\";\n}\n\nTEST(MixedResultTest, Succeeds) {\n  EXPECT_EQ(1, 1);\n  ASSERT_EQ(1, 1);\n}\n\nTEST(MixedResultTest, Fails) {\n  EXPECT_EQ(1, 2);\n  ASSERT_EQ(2, 3);\n}\n\nTEST(MixedResultTest, DISABLED_test) {\n  FAIL() << \"Unexpected failure: Disabled test should not be run\";\n}\n\nTEST(XmlQuotingTest, OutputsCData) {\n  FAIL() << \"XML output: \"\n            \"<?xml encoding=\\\"utf-8\\\"><top><![CDATA[cdata text]]></top>\";\n}\n\n// Helps to test that invalid characters produced by test code do not make\n// it into the XML file.\nTEST(InvalidCharactersTest, InvalidCharactersInMessage) {\n  FAIL() << \"Invalid characters in brackets [\\x1\\x2]\";\n}\n\nclass PropertyRecordingTest : public Test {\n public:\n  static void SetUpTestSuite() { RecordProperty(\"SetUpTestSuite\", \"yes\"); }\n  static void TearDownTestSuite() {\n    RecordProperty(\"TearDownTestSuite\", \"aye\");\n  }\n};\n\nTEST_F(PropertyRecordingTest, OneProperty) {\n  RecordProperty(\"key_1\", \"1\");\n}\n\nTEST_F(PropertyRecordingTest, IntValuedProperty) {\n  RecordProperty(\"key_int\", 1);\n}\n\nTEST_F(PropertyRecordingTest, ThreeProperties) {\n  RecordProperty(\"key_1\", \"1\");\n  RecordProperty(\"key_2\", \"2\");\n  RecordProperty(\"key_3\", \"3\");\n}\n\nTEST_F(PropertyRecordingTest, TwoValuesForOneKeyUsesLastValue) {\n  RecordProperty(\"key_1\", \"1\");\n  RecordProperty(\"key_1\", \"2\");\n}\n\nTEST(NoFixtureTest, RecordProperty) {\n  RecordProperty(\"key\", \"1\");\n}\n\nvoid ExternalUtilityThatCallsRecordProperty(const std::string& key, int value) {\n  testing::Test::RecordProperty(key, value);\n}\n\nvoid ExternalUtilityThatCallsRecordProperty(const std::string& key,\n                                            const std::string& value) {\n  testing::Test::RecordProperty(key, value);\n}\n\nTEST(NoFixtureTest, ExternalUtilityThatCallsRecordIntValuedProperty) {\n  ExternalUtilityThatCallsRecordProperty(\"key_for_utility_int\", 1);\n}\n\nTEST(NoFixtureTest, ExternalUtilityThatCallsRecordStringValuedProperty) {\n  ExternalUtilityThatCallsRecordProperty(\"key_for_utility_string\", \"1\");\n}\n\n// Verifies that the test parameter value is output in the 'value_param'\n// XML attribute for value-parameterized tests.\nclass ValueParamTest : public TestWithParam<int> {};\nTEST_P(ValueParamTest, HasValueParamAttribute) {}\nTEST_P(ValueParamTest, AnotherTestThatHasValueParamAttribute) {}\nINSTANTIATE_TEST_SUITE_P(Single, ValueParamTest, Values(33, 42));\n\n// Verifies that the type parameter name is output in the 'type_param'\n// XML attribute for typed tests.\ntemplate <typename T> class TypedTest : public Test {};\ntypedef testing::Types<int, long> TypedTestTypes;\nTYPED_TEST_SUITE(TypedTest, TypedTestTypes);\nTYPED_TEST(TypedTest, HasTypeParamAttribute) {}\n\n// Verifies that the type parameter name is output in the 'type_param'\n// XML attribute for type-parameterized tests.\ntemplate <typename T>\nclass TypeParameterizedTestSuite : public Test {};\nTYPED_TEST_SUITE_P(TypeParameterizedTestSuite);\nTYPED_TEST_P(TypeParameterizedTestSuite, HasTypeParamAttribute) {}\nREGISTER_TYPED_TEST_SUITE_P(TypeParameterizedTestSuite, HasTypeParamAttribute);\ntypedef testing::Types<int, long> TypeParameterizedTestSuiteTypes;  // NOLINT\nINSTANTIATE_TYPED_TEST_SUITE_P(Single, TypeParameterizedTestSuite,\n                               TypeParameterizedTestSuiteTypes);\n\nint main(int argc, char** argv) {\n  InitGoogleTest(&argc, argv);\n\n  if (argc > 1 && strcmp(argv[1], \"--shut_down_xml\") == 0) {\n    TestEventListeners& listeners = UnitTest::GetInstance()->listeners();\n    delete listeners.Release(listeners.default_xml_generator());\n  }\n  testing::Test::RecordProperty(\"ad_hoc_property\", \"42\");\n  return RUN_ALL_TESTS();\n}\n\n// clang-format on\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/gtest_xml_test_utils.py",
    "content": "# Copyright 2006, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\"\"\"Unit test utilities for gtest_xml_output\"\"\"\n\nimport re\nfrom xml.dom import minidom, Node\nfrom googletest.test import gtest_test_utils\n\nGTEST_DEFAULT_OUTPUT_FILE = 'test_detail.xml'\n\nclass GTestXMLTestCase(gtest_test_utils.TestCase):\n  \"\"\"\n  Base class for tests of Google Test's XML output functionality.\n  \"\"\"\n\n\n  def AssertEquivalentNodes(self, expected_node, actual_node):\n    \"\"\"\n    Asserts that actual_node (a DOM node object) is equivalent to\n    expected_node (another DOM node object), in that either both of\n    them are CDATA nodes and have the same value, or both are DOM\n    elements and actual_node meets all of the following conditions:\n\n    *  It has the same tag name as expected_node.\n    *  It has the same set of attributes as expected_node, each with\n       the same value as the corresponding attribute of expected_node.\n       Exceptions are any attribute named \"time\", which needs only be\n       convertible to a floating-point number and any attribute named\n       \"type_param\" which only has to be non-empty.\n    *  It has an equivalent set of child nodes (including elements and\n       CDATA sections) as expected_node.  Note that we ignore the\n       order of the children as they are not guaranteed to be in any\n       particular order.\n    \"\"\"\n\n    if expected_node.nodeType == Node.CDATA_SECTION_NODE:\n      self.assertEquals(Node.CDATA_SECTION_NODE, actual_node.nodeType)\n      self.assertEquals(expected_node.nodeValue, actual_node.nodeValue)\n      return\n\n    self.assertEquals(Node.ELEMENT_NODE, actual_node.nodeType)\n    self.assertEquals(Node.ELEMENT_NODE, expected_node.nodeType)\n    self.assertEquals(expected_node.tagName, actual_node.tagName)\n\n    expected_attributes = expected_node.attributes\n    actual_attributes = actual_node.attributes\n    self.assertEquals(\n        expected_attributes.length, actual_attributes.length,\n        'attribute numbers differ in element %s:\\nExpected: %r\\nActual: %r' % (\n            actual_node.tagName, expected_attributes.keys(),\n            actual_attributes.keys()))\n    for i in range(expected_attributes.length):\n      expected_attr = expected_attributes.item(i)\n      actual_attr = actual_attributes.get(expected_attr.name)\n      self.assert_(\n          actual_attr is not None,\n          'expected attribute %s not found in element %s' %\n          (expected_attr.name, actual_node.tagName))\n      self.assertEquals(\n          expected_attr.value, actual_attr.value,\n          ' values of attribute %s in element %s differ: %s vs %s' %\n          (expected_attr.name, actual_node.tagName,\n           expected_attr.value, actual_attr.value))\n\n    expected_children = self._GetChildren(expected_node)\n    actual_children = self._GetChildren(actual_node)\n    self.assertEquals(\n        len(expected_children), len(actual_children),\n        'number of child elements differ in element ' + actual_node.tagName)\n    for child_id, child in expected_children.items():\n      self.assert_(child_id in actual_children,\n                   '<%s> is not in <%s> (in element %s)' %\n                   (child_id, actual_children, actual_node.tagName))\n      self.AssertEquivalentNodes(child, actual_children[child_id])\n\n  identifying_attribute = {\n      'testsuites': 'name',\n      'testsuite': 'name',\n      'testcase': 'name',\n      'failure': 'message',\n      'skipped': 'message',\n      'property': 'name',\n  }\n\n  def _GetChildren(self, element):\n    \"\"\"\n    Fetches all of the child nodes of element, a DOM Element object.\n    Returns them as the values of a dictionary keyed by the IDs of the\n    children.  For <testsuites>, <testsuite>, <testcase>, and <property>\n    elements, the ID is the value of their \"name\" attribute; for <failure>\n    elements, it is the value of the \"message\" attribute; for <properties>\n    elements, it is the value of their parent's \"name\" attribute plus the\n    literal string \"properties\"; CDATA sections and non-whitespace\n    text nodes are concatenated into a single CDATA section with ID\n    \"detail\".  An exception is raised if any element other than the above\n    four is encountered, if two child elements with the same identifying\n    attributes are encountered, or if any other type of node is encountered.\n    \"\"\"\n\n    children = {}\n    for child in element.childNodes:\n      if child.nodeType == Node.ELEMENT_NODE:\n        if child.tagName == 'properties':\n          self.assert_(child.parentNode is not None,\n                       'Encountered <properties> element without a parent')\n          child_id = child.parentNode.getAttribute('name') + '-properties'\n        else:\n          self.assert_(child.tagName in self.identifying_attribute,\n                       'Encountered unknown element <%s>' % child.tagName)\n          child_id = child.getAttribute(\n              self.identifying_attribute[child.tagName])\n        self.assert_(child_id not in children)\n        children[child_id] = child\n      elif child.nodeType in [Node.TEXT_NODE, Node.CDATA_SECTION_NODE]:\n        if 'detail' not in children:\n          if (child.nodeType == Node.CDATA_SECTION_NODE or\n              not child.nodeValue.isspace()):\n            children['detail'] = child.ownerDocument.createCDATASection(\n                child.nodeValue)\n        else:\n          children['detail'].nodeValue += child.nodeValue\n      else:\n        self.fail('Encountered unexpected node type %d' % child.nodeType)\n    return children\n\n  def NormalizeXml(self, element):\n    \"\"\"\n    Normalizes Google Test's XML output to eliminate references to transient\n    information that may change from run to run.\n\n    *  The \"time\" attribute of <testsuites>, <testsuite> and <testcase>\n       elements is replaced with a single asterisk, if it contains\n       only digit characters.\n    *  The \"timestamp\" attribute of <testsuites> elements is replaced with a\n       single asterisk, if it contains a valid ISO8601 datetime value.\n    *  The \"type_param\" attribute of <testcase> elements is replaced with a\n       single asterisk (if it sn non-empty) as it is the type name returned\n       by the compiler and is platform dependent.\n    *  The line info reported in the first line of the \"message\"\n       attribute and CDATA section of <failure> elements is replaced with the\n       file's basename and a single asterisk for the line number.\n    *  The directory names in file paths are removed.\n    *  The stack traces are removed.\n    \"\"\"\n\n    if element.tagName == 'testcase':\n      source_file = element.getAttributeNode('file')\n      if source_file:\n        source_file.value = re.sub(r'^.*[/\\\\](.*)', '\\\\1', source_file.value)\n    if element.tagName in ('testsuites', 'testsuite', 'testcase'):\n      timestamp = element.getAttributeNode('timestamp')\n      timestamp.value = re.sub(r'^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d\\.\\d\\d\\d$',\n                               '*', timestamp.value)\n    if element.tagName in ('testsuites', 'testsuite', 'testcase'):\n      time = element.getAttributeNode('time')\n      time.value = re.sub(r'^\\d+(\\.\\d+)?$', '*', time.value)\n      type_param = element.getAttributeNode('type_param')\n      if type_param and type_param.value:\n        type_param.value = '*'\n    elif element.tagName == 'failure' or element.tagName == 'skipped':\n      source_line_pat = r'^.*[/\\\\](.*:)\\d+\\n'\n      # Replaces the source line information with a normalized form.\n      message = element.getAttributeNode('message')\n      message.value = re.sub(source_line_pat, '\\\\1*\\n', message.value)\n      for child in element.childNodes:\n        if child.nodeType == Node.CDATA_SECTION_NODE:\n          # Replaces the source line information with a normalized form.\n          cdata = re.sub(source_line_pat, '\\\\1*\\n', child.nodeValue)\n          # Removes the actual stack trace.\n          child.nodeValue = re.sub(r'Stack trace:\\n(.|\\n)*',\n                                   'Stack trace:\\n*', cdata)\n    for child in element.childNodes:\n      if child.nodeType == Node.ELEMENT_NODE:\n        self.NormalizeXml(child)\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/production.cc",
    "content": "// Copyright 2006, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// This is part of the unit test for gtest_prod.h.\n\n#include \"production.h\"\n\nPrivateCode::PrivateCode() : x_(0) {}\n"
  },
  {
    "path": "3rd/googletest-1.12.1/googletest/test/production.h",
    "content": "// Copyright 2006, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n//\n// This is part of the unit test for gtest_prod.h.\n\n#ifndef GOOGLETEST_TEST_PRODUCTION_H_\n#define GOOGLETEST_TEST_PRODUCTION_H_\n\n#include \"gtest/gtest_prod.h\"\n\nclass PrivateCode {\n public:\n  // Declares a friend test that does not use a fixture.\n  FRIEND_TEST(PrivateCodeTest, CanAccessPrivateMembers);\n\n  // Declares a friend test that uses a fixture.\n  FRIEND_TEST(PrivateCodeFixtureTest, CanAccessPrivateMembers);\n\n  PrivateCode();\n\n  int x() const { return x_; }\n\n private:\n  void set_x(int an_x) { x_ = an_x; }\n  int x_;\n};\n\n#endif  // GOOGLETEST_TEST_PRODUCTION_H_\n"
  },
  {
    "path": "CMakeLists.txt",
    "content": "# Copyright (C) 2018 ichenq@outlook.com. All rights reserved.\n# Distributed under the terms and conditions of the Apache License.\n# See accompanying files LICENSE.\n\ncmake_minimum_required(VERSION 3.0)\n\nproject (TimerBench)\n\nset (CMAKE_CXX_STANDARD 11)\nset (GOOGLETEST_PATH ${CMAKE_SOURCE_DIR}/3rd/googletest-1.12.1/googletest)\nset (GTEST_ROOT_DIR ${GOOGLETEST_PATH})\nset (GBENCH_ROOT_DIR ${CMAKE_SOURCE_DIR}/3rd/benchmark-1.8.2)\n\ninclude_directories(\n    src\n    ${GTEST_ROOT_DIR}\n    ${GTEST_ROOT_DIR}/include\n    ${GBENCH_ROOT_DIR}/include\n)\n\nif (WIN32)\n    add_definitions(\n        -DNOMINMAX\n        -DWIN32_LEAN_AND_MEAN\n        -D_WIN32_WINNT=0x0600\n        -D_CRT_SECURE_NO_WARNINGS\n        -D_SCL_SECURE_NO_WARNINGS\n        -D_WINSOCK_DEPRECATED_NO_WARNINGS\n    )\nendif()\n\nfile(GLOB_RECURSE LIB_HEADER_FILES src/*.h)\nfile(GLOB_RECURSE LIB_SOURCE_FILES src/*.cpp)\nfile(GLOB_RECURSE TEST_SOURCE_FILES test/*.cpp)\n\nadd_subdirectory(${GBENCH_ROOT_DIR})\n\nadd_executable(TimerBench\n    ${LIB_HEADER_FILES} ${LIB_SOURCE_FILES}\n    ${TEST_HEADER_FILES} ${TEST_SOURCE_FILES}\n    ${GTEST_ROOT_DIR}/src/gtest-all.cc\n)\n\ntarget_link_libraries(TimerBench benchmark::benchmark)\n\nif (UNIX)\n    target_link_libraries(TimerBench  pthread)\nendif(UNIX)\n"
  },
  {
    "path": "Dockerfile",
    "content": "FROM gcc:11-bullseye as build-env\n\n# install build tools\nRUN apt-get update -y && apt-get install -y --no-install-recommends \\\n    build-essential cmake && rm -rf /var/lib/apt/lists/*;\n\n\nFROM build-env as builder\n\nWORKDIR /work\nCOPY . .\n# build binaries\nRUN mkdir cmake-build; cd cmake-build && cmake -DCMAKE_BUILD_TYPE=Release ..\nRUN cd cmake-build && make && ./TimerBench\n\nFROM alpine:3.15\nWORKDIR /app\nCOPY --from=builder /work/cmake-build/TimerBench .\n\n# CMD [\"./TimerBench\"]\n"
  },
  {
    "path": "LICENSE",
    "content": "GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    {{ project }}  Copyright (C) {{ year }}  {{ organization }}\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# timer-benchmark\n\n测试不同的数据结构（最小堆、四叉堆、红黑树、时间轮）实现的定时器的性能差异。\n\nas [Hashed and Hierarchical Timing Wheels](http://www.cs.columbia.edu/~nahum/w6998/papers/sosp87-timing-wheels.pdf) implies\n\na timer module has 3 component routines:\n\n``` C++\n// start a timer that will expire after `interval` unit of time\n// return an unique id of the pending timer\nint Start(interval, expiry_action)\n\n// cancel a timer identified by `timer_id`\nvoid Cancel(timer_id)\n\n// per-tick bookking routine\n// in single-thread timer scheduler implementions, this routine will run timeout actions\nint Update(now)\n```\n\nuse [min-heap](https://en.wikipedia.org/wiki/Heap_(data_structure)), quaternary heap( [4-ary heap](https://en.wikipedia.org/wiki/D-ary_heap) ),\nbalanced binary search tree( [red-black tree](https://en.wikipedia.org/wiki/Red-black_tree) ), [hashed timing wheel](https://netty.io/4.0/api/io/netty/util/HashedWheelTimer.html)\nand [Hierarchical timing wheel](https://lwn.net/Articles/646950/) to implement different time scheduler.\n\n\n## Big(O) complexity of algorithm\n\nFIFO means whether same deadline timers expire in FIFO order.\n\nFIFO的意思是相同到期时间的定时器是否按FIFO的顺序到期\n\nalgo                      |          | Start()  | Cancel() | Tick()   |  FIFO  | implemention file\n--------------------------|----------|----------|----------|----------|--------|-----------------------\nbinary heap               | 最小堆   | O(log N) | O(log N) | O(1)     |   no   | [PriorityQueueTimer](src/PriorityQueueTimer.h)\n4-ary heap                | 四叉堆   | O(log N) | O(log N) | O(1)     |   no   | [QuatHeapTimer](src/QuatHeapTimer.h)\nredblack tree             | 红黑树   | O(log N) | O(log N) | O(log N) |   no   | [RBTreeTimer](src/RBTreeTimer.h)\nhashed timing wheel       | 时间轮   | O(1)     | O(1)     | O(1)     |   yes  | [HashedWheelTimer](src/HashedWheelTimer.h)\nhierarchical timing wheel | 多级时间轮 | O(1)   | O(1)     | O(1)     |   yes  | [HHWheelTimer](src/HHWheelTimer.h)\n\n\n## How To Build\n\n### Obtain CMake\n\nObtain [CMake](https://cmake.org) first.\n\n* `sudo apt install cmake` on Ubuntu or Debian\n* `sudo yum install cmake` on Redhat or CentOS\n* `choco install cmake` on Windows use [choco](https://chocolatey.org/)\n\nrun shell command\n\n* `mkdir cmake-build; cd cmake-build && cmake -DCMAKE_BUILD_TYPE=Release .. && cmake --build .`\n\n\n\n## Benchmarks\n\n## Benchmark result\n\nWin10 x64 6-core 3.93MHz CPU\n\n\nBenchmark               |        Time     |       CPU  | Iterations\n------------------------|-----------------|------------|---------------\nBM_PQTimerAdd           |      441 ns     |    433 ns  |   1947826\nBM_QuadHeapTimerAdd     |      429 ns     |    427 ns  |   1866667\nBM_RBTreeTimerAdd       |     1231 ns     |   1228 ns  |   1120000\nBM_HashWheelTimerAdd    |      430 ns     |    436 ns  |   1792000\nBM_HHWheelTimerAdd      |      669 ns     |    672 ns  |   1000000\nBM_PQTimerCancel        |      668 ns     |    656 ns  |   1000000\nBM_QuadHeapTimerCancel  |      351 ns     |    349 ns  |   2240000\nBM_RBTreeTimerCancel    |     1685 ns     |   1692 ns  |    896000\nBM_HashWheelTimerCancel |      632 ns     |    641 ns  |   1000000\nBM_HHWheelTimerCancel   |      942 ns     |    953 ns  |   1000000\nBM_PQTimerTick          |     29.8 ns     |   29.8 ns  |  23578947\nBM_QuadHeapTimerTick    |     30.3 ns     |   30.5 ns  |  23578947\nBM_RBTreeTimerTick      |     30.2 ns     |   29.8 ns  |  23578947\nBM_HashWheelTimerTick   |     31.2 ns     |   30.8 ns  |  21333333\nBM_HHWheelTimerTick     |     30.5 ns     |   30.7 ns  |  22400000\n\n## Conclusion\n\n* rbtree timer Add/Cancel has not so good performance compare to other implementations;\n* 红黑树的插入和删除相比其它实现，表现都弱了一些；\n* binary min heap is a good choice, easy to implement and have a good performance, but without FIFO expiration order(heap sort is unstable);\n* 最小堆是一个不错的选择，代码实现简单性能也不俗，但不支持相同超时的定时器按FIFO顺序触发;\n\n\n## Reference\n\n* [Hashed and Hierarchical Timing Wheels](https://paulcavallaro.com/blog/hashed-and-hierarchical-timing-wheels/)\n* [Hashed and Hierarchical Timing Wheels](http://www.cs.columbia.edu/~nahum/w6998/papers/sosp87-timing-wheels.pdf)\n* [Netty HashedWheelTimer](https://github.com/netty/netty/blob/4.1/common/src/main/java/io/netty/util/HashedWheelTimer.java)\n* [Apache Kafka, Purgatory, and Hierarchical Timing Wheels](https://www.confluent.io/blog/apache-kafka-purgatory-hierarchical-timing-wheels/s)\n\n\n"
  },
  {
    "path": "src/Clock.cpp",
    "content": "// Copyright © 2021 ichenq@gmail.com All rights reserved.\n// See accompanying files LICENSE.txt\n\n#include \"Clock.h\"\n#include <chrono>\n#include \"Logging.h\"\n#include \"CmdFlag.h\"\n\nusing namespace std::chrono;\n\nint64_t Clock::clock_offset_ = 0;\n\nint64_t Clock::CurrentTimeMillis()\n{\n    auto now = system_clock::now();\n    auto ms = duration_cast<milliseconds>(now.time_since_epoch()).count();\n    return ms + clock_offset_;\n}\n\nvoid Clock::TimeReset()\n{\n    clock_offset_ = 0;\n}\n\nvoid Clock::TimeFly(int64_t ms)\n{\n    clock_offset_ += ms;\n}\n\nstd::string Clock::CurrentTimeString(int64_t timepoint)\n{\n    if (timepoint == 0)\n    {\n        timepoint = CurrentTimeMillis();\n    }\n    time_t sec = timepoint / 1000;\n    struct tm t = *localtime(&sec); // make sure localtime has thread-safety\n    char buffer[100] = {};\n    int n = snprintf(buffer, 100, \"%d-%02d-%02d %02d:%02d:%02d.%03d\", 1900 + t.tm_year, t.tm_mon + 1,\n        t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, int(timepoint % 1000));\n    return std::string(buffer, n);\n}\n\n\nint64_t Clock::GetNowTickCount()\n{\n    auto now = std::chrono::high_resolution_clock::now();\n    return duration_cast<nanoseconds>(now.time_since_epoch()).count();\n}\n\n"
  },
  {
    "path": "src/Clock.h",
    "content": "// Copyright © 2022 ichenq@gmail.com All rights reserved.\n// See accompanying files LICENSE\n\n#pragma once\n\n#include <stdint.h>\n#include <string>\n\n\nclass Clock\n{\npublic:\n    // Get current unix time in milliseconds\n    static int64_t CurrentTimeMillis();\n\n    // Get current time in string format\n    static std::string CurrentTimeString(int64_t timepoint);\n\n    // Get current tick count, in nanoseconds\n    static int64_t GetNowTickCount();\n    static void TimeFly(int64_t ms);\n    static void TimeReset();\n\nprivate:\n    static int64_t clock_offset_; // offset time of logic clock\n};\n"
  },
  {
    "path": "src/CmdFlag.h",
    "content": "// Copyright (c) 2008, Google Inc.\n// All rights reserved.\n\n// ---\n// This file is a compatibility layer that defines Google's version of\n// command line flags that are used for configuration.\n//\n// We put flags into their own namespace.  It is purposefully\n// named in an opaque way that people should have trouble typing\n// directly.  The idea is that DEFINE puts the flag in the weird\n// namespace, and DECLARE imports the flag from there into the\n// current namespace.  The net result is to force people to use\n// DECLARE to get access to a flag, rather than saying\n//   extern bool FLAGS_logtostderr;\n// or some such instead.  We want this so we can put extra\n// functionality (like sanity-checking) in DECLARE if we want,\n// and make sure it is picked up everywhere.\n//\n// We also put the type of the variable in the namespace, so that\n// people can't DECLARE_int32 something that they DEFINE_bool'd\n// elsewhere.\n\n#pragma once\n\n#include <cstdint>\n#include <cstdlib>\n#include <string>\n\n#define DECLARE_VARIABLE(type, shorttype, name, tn)                 \\\n  namespace fL##shorttype {                                         \\\n  extern type FLAGS_##name;                                         \\\n    }                                                               \\\n  using fL##shorttype::FLAGS_##name\n\n#define DEFINE_VARIABLE(type, shorttype, name, value, meaning, tn)  \\\n  namespace fL##shorttype {                                         \\\n    type FLAGS_##name(value);                                       \\\n    char FLAGS_no##name;                                            \\\n        }                                                           \\\n  using fL##shorttype::FLAGS_##name\n\n// bool specialization\n#define DECLARE_bool(name)          DECLARE_VARIABLE(bool, B, name, bool)\n#define DEFINE_bool(name, val, txt) DEFINE_VARIABLE(bool, B, name, val, txt, bool)\n  \n\n#define DECLARE_int32(name)         DECLARE_VARIABLE(int32_t, I, name, int32_t)\n#define DEFINE_int32(name,val,txt)  DEFINE_VARIABLE(int32_t, I, name, val, txt, int32_t)\n\n#define DECLARE_int64(name)         DECLARE_VARIABLE(int64_t, I64, name, int64_t)\n#define DEFINE_int64(name,val,txt)  DEFINE_VARIABLE(int64_t, I64, name, val, txt, int64_t)\n\n#define DECLARE_double(name)        DECLARE_VARIABLE(double, D, name, double)\n#define DEFINE_double(name,val,txt) DEFINE_VARIABLE(double, D, name, val, txt, double)\n\n// Special case for string, because we have to specify the namespace\n// std::string, which doesn't play nicely with our FLAG__namespace hackery.\n#define DECLARE_string(name)                                        \\\n  namespace fLS {                                                   \\\n    extern std::string& FLAGS_##name;                               \\\n        }                                                           \\\n  using fLS::FLAGS_##name\n\n#define DEFINE_string(name, value, meaning)                         \\\n  namespace fLS {                                                   \\\n    std::string FLAGS_##name##_buf(value);                          \\\n    std::string& FLAGS_##name = FLAGS_##name##_buf;                 \\\n    char FLAGS_no##name;                                            \\\n        }                                                           \\\n  using fLS::FLAGS_##name\n\n\n// If both an environment variable and a flag are specified, the value\n// specified by a flag wins. \n\n#define QSF_DEFINE_bool(name, value, meaning) \\\n  DEFINE_bool(name, EnvToBool(\"QSF_\" #name, value), meaning)\n\n#define QSF_DEFINE_int32(name, value, meaning) \\\n  DEFINE_int32(name, EnvToInt(\"QSF_\" #name, value), meaning)\n\n#define QSF_DEFINE_string(name, value, meaning) \\\n  DEFINE_string(name, EnvToString(\"QSF_\" #name, value), meaning)\n\n// These macros (could be functions, but I don't want to bother with a .cc\n// file), make it easier to initialize flags from the environment.\n\n#define EnvToString(envname, dflt)   \\\n  (!getenv(envname) ? (dflt) : getenv(envname))\n\n#define EnvToBool(envname, dflt)   \\\n  (!getenv(envname) ? (dflt) : memchr(\"tTyY1\\0\", getenv(envname)[0], 6) != NULL)\n\n#define EnvToInt(envname, dflt)  \\\n  (!getenv(envname) ? (dflt) : strtol(getenv(envname), NULL, 10))\n"
  },
  {
    "path": "src/HHWheelTimer.cpp",
    "content": "// Copyright © 2021 ichenq@gmail.com All rights reserved.\n// See accompanying files LICENSE.txt\n\n#include \"HHWheelTimer.h\"\n#include \"Clock.h\"\n#include \"Logging.h\"\n#include <assert.h>\n\ninline int64_t current_clock() {\n    return Clock::CurrentTimeMillis();\n}\n\nHHWheelTimer::HHWheelTimer()\n{\n    int64_t now = Clock::CurrentTimeMillis();\n    started_at_ = now;\n    init_timers(&base_, now);\n    ref_.rehash(1024);\n}\n\n\nHHWheelTimer::~HHWheelTimer()\n{\n    clear();\n}\n\nvoid HHWheelTimer::clear()\n{\n    init_timers(&base_, 0);\n    for (const auto& kv : ref_) {\n        delete kv.second;\n    }\n    ref_.clear();\n}\n\n\nint HHWheelTimer::Start(uint32_t duration, TimeoutAction action)\n{\n    int id = nextId();\n    timer_list* timer = new timer_list();\n    timer->id = id;\n    timer->base = &base_;\n    timer->data = this;\n    timer->expires = Clock::CurrentTimeMillis() + (int64_t)duration;\n    timer->function = HHWheelTimer::handleTimerExpired;\n\n    add_timer(timer);\n    ref_[id] = timer;\n    actions_[id] = action;\n    return id;\n}\n\nbool HHWheelTimer::Cancel(int timer_id)\n{\n    auto iter = ref_.find(timer_id);\n    if (iter == ref_.end()) {\n        return false;\n    }\n\n    timer_list* timer = iter->second;\n    del_timer(timer);\n    ref_.erase(timer_id);\n    actions_.erase(timer_id);\n\n    timer->base = NULL;\n    timer->function = NULL;\n    delete timer;\n\n    return true;\n}\n\nint HHWheelTimer::Update(int64_t ticks)\n{\n    return run_timers(&base_, ticks);\n}\n\nTimeoutAction HHWheelTimer::findAndDelAction(int id)\n{\n    auto iter = actions_.find(id);\n    if (iter != actions_.end())\n    {\n        TimeoutAction action = std::move(iter->second);\n        actions_.erase(iter);\n        return std::move(action);\n    }\n    return nullptr;\n}\n\nvoid HHWheelTimer::handleTimerExpired(timer_list* timer)\n{\n    assert(timer);\n    auto wheel = reinterpret_cast<HHWheelTimer*>(timer->data);\n    TimeoutAction action = wheel->findAndDelAction(timer->id);\n    wheel->Cancel(timer->id);\n\n    if (action) {\n        action();\n    }\n}\n\n"
  },
  {
    "path": "src/HHWheelTimer.h",
    "content": "// Copyright © 2022 ichenq@gmail.com All rights reserved.\n// See accompanying files LICENSE\n\n#pragma once\n\n#include \"TimerBase.h\"\n#include \"timer_list.h\"\n#include <unordered_map>\n\n// Hashed and Hierarchical Timing Wheels\n// see https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/kernel/timer.c?h=linux-3.10.y\n//\n// timer scheduler implemented by hashed & hierachical wheels\n// complexity:\n//      StartTimer   CancelTimer   PerTick\n//       O(1)         O(1)          O(1)\n//\n\nstruct TimerNode;\n\nclass HHWheelTimer : public TimerBase\n{\npublic:\n    HHWheelTimer();\n    ~HHWheelTimer();\n\n    TimerSchedType Type() const override\n    {\n        return TimerSchedType::TIMER_HH_WHEEL;\n    }\n\n    // start a timer after `duration` milliseconds\n    int Start(uint32_t duration, TimeoutAction action) override;\n\n    // cancel a timer\n    bool Cancel(int timer_id) override;\n\n    // we assume 1 tick per ms\n    int Update(int64_t ticks) override;\n\n    int Size() const override\n    {\n        return (int)ref_.size();\n    }\n\n    TimeoutAction findAndDelAction(int id);\n\nprivate:\n    void clear();\n    static void handleTimerExpired(timer_list*);\n\nprivate:\n    int64_t started_at_ = 0;\n    tvec_base base_;\n    std::unordered_map<int, timer_list*> ref_;\n    std::unordered_map<int, TimeoutAction> actions_;\n};\n"
  },
  {
    "path": "src/HashedWheelBucket.cpp",
    "content": "// Copyright © 2021 ichenq@gmail.com All rights reserved.\n// See accompanying files LICENSE.txt\n\n#include \"HashedWheelBucket.h\"\n#include \"HashedWheelTimer.h\"\n#include \"Logging.h\"\n#include <assert.h>\n\n\nbool HashedWheelTimeout::Expire()\n{\n    // trigger timeout action\n    if (action) {\n        action();\n        action = nullptr;\n        return true;\n    }\n    return false;\n}\n\nvoid HashedWheelTimeout::Remove()\n{\n    if (bucket != nullptr) {\n        bucket->Remove(this);\n    }\n}\n\nHashedWheelBucket::HashedWheelBucket()\n{\n}\n\nHashedWheelBucket::~HashedWheelBucket()\n{\n}\n\n// add `timeout` to this bucket\nvoid HashedWheelBucket::AddTimeout(HashedWheelTimeout* timeout)\n{\n    CHECK(timeout != nullptr);\n    CHECK(timeout->bucket == nullptr);\n    timeout->bucket = this;\n    if (head == nullptr) {\n        head = tail = timeout;\n    }\n    else {\n        tail->next = timeout;\n        timeout->prev = tail;\n        tail = timeout;\n    }\n}\n\n// Expire all HashedWheelTimeouts for the given deadline.\nvoid HashedWheelBucket::ExpireTimeouts(int64_t deadline, std::vector<HashedWheelTimeout*>& expired)\n{\n    HashedWheelTimeout* timeout = head;\n    while (timeout != nullptr) {\n        HashedWheelTimeout* next = timeout->next;\n        if (timeout->remaining_rounds <= 0) {\n            next = Remove(timeout);\n            expired.push_back(timeout);\n            if (timeout->deadline > deadline) {\n                // The timeout was placed into a wrong slot. This should never happen.\n                LOG(FATAL) << \"timeout deadline: \" << timeout->deadline << \" > \" << deadline;\n            }\n        }\n        else {\n            timeout->remaining_rounds--;\n        }\n        timeout = next;\n    }\n}\n\n// remove `timeout` from linked list and return next linked one\nHashedWheelTimeout* HashedWheelBucket::Remove(HashedWheelTimeout* timeout)\n{\n    HashedWheelTimeout* next = timeout->next;\n    if (timeout->prev != nullptr) {\n        timeout->prev->next = next;\n    }\n    if (timeout->next != nullptr) {\n        timeout->next->prev = timeout->prev;\n    }\n    if (timeout == head) {\n        // if timeout is also the tail we need to adjust the entry too\n        if (timeout == tail) {\n            head = tail = nullptr;\n        }\n        else {\n            head = next;\n        }\n    }\n    else if (timeout == tail) {\n        // if the timeout is the tail modify the tail to be the prev node.\n        tail = timeout->prev;\n    }\n    // unchain from this bucket\n    timeout->prev = nullptr;\n    timeout->next = nullptr;\n    timeout->bucket = nullptr;\n    return next;\n}\n\n// Clear this bucket and return all not expired / cancelled Timeouts.\nvoid HashedWheelBucket::ClearTimeouts(std::unordered_map<int, HashedWheelTimeout*>& set)\n{\n    while (true)\n    {\n        HashedWheelTimeout* timeout = pollTimeout();\n        if (timeout == nullptr) {\n            break;\n        }\n        set[timeout->id] = timeout;\n    }\n}\n\n// poll first timeout\nHashedWheelTimeout* HashedWheelBucket::pollTimeout()\n{\n    HashedWheelTimeout* node = this->head;\n    if (node == nullptr) {\n        return nullptr;\n    }\n    HashedWheelTimeout* next = node->next;\n    if (next == nullptr) {\n        head = tail = nullptr;\n    }\n    else {\n        head = next;\n        next->prev = nullptr;\n    }\n    // unchain this element\n    node->next = nullptr;\n    node->prev = nullptr;\n    node->bucket = nullptr;\n    return node;\n}\n"
  },
  {
    "path": "src/HashedWheelBucket.h",
    "content": "// Copyright © 2021 ichenq@gmail.com All rights reserved.\n// See accompanying files LICENSE\n\n#pragma once\n\n#include \"TimerBase.h\"\n#include <vector>\n#include <unordered_map>\n\n\nclass HashedWheelTimer;\nclass HashedWheelBucket;\n\nclass HashedWheelTimeout\n{\npublic:\n    HashedWheelTimeout(int id, int64_t deadline, TimeoutAction aciton)\n        : id(id), deadline(deadline), action(aciton)\n    {\n    }\n\n    HashedWheelTimeout(const HashedWheelTimeout&) = delete;\n    HashedWheelTimeout& operator=(const HashedWheelTimeout&) = delete;\n\n\n    bool Expire();\n    void Remove();\n\n    bool operator < (const HashedWheelTimeout& b) const\n    {\n        if (deadline == b.deadline) {\n            return id > b.id;\n        }\n        return deadline < b.deadline;\n    }\n\npublic:\n    HashedWheelTimeout* next = nullptr;\n    HashedWheelTimeout* prev = nullptr;\n\n    HashedWheelBucket* bucket = nullptr;\n    HashedWheelTimer* timer = nullptr;\n\n    int32_t remaining_rounds = 0;           // wheel round left\n    int64_t deadline = 0;                   // expired time in ms\n    int id = 0;                             // unique timer id\n    TimeoutAction action = nullptr;\n};\n\n// Bucket that stores HashedWheelTimeouts.\nclass HashedWheelBucket\n{\npublic:\n    HashedWheelBucket();\n    ~HashedWheelBucket();\n\n    HashedWheelBucket(const HashedWheelBucket&) = delete;\n    HashedWheelBucket& operator=(const HashedWheelBucket&) = delete;\n\n    void AddTimeout(HashedWheelTimeout* timeout);\n    void ExpireTimeouts(int64_t deadline, std::vector< HashedWheelTimeout*>& expired);\n    HashedWheelTimeout* Remove(HashedWheelTimeout* timeout);\n    void ClearTimeouts(std::unordered_map<int, HashedWheelTimeout*>& set);\n\nprivate:\n    friend class HashedWheelTimer;\n\n    HashedWheelTimeout* pollTimeout();\n\n    HashedWheelTimeout* head = nullptr;\n    HashedWheelTimeout* tail = nullptr;\n};\n"
  },
  {
    "path": "src/HashedWheelTimer.cpp",
    "content": "// Copyright © 2021 ichenq@gmail.com All rights reserved.\n// See accompanying files LICENSE.txt\n\n#include \"HashedWheelTimer.h\"\n#include \"HashedWheelBucket.h\"\n#include <thread>\n#include <chrono>\n#include \"Clock.h\"\n#include \"Logging.h\"\n\nconst int WHEEL_SIZE = 512;\nconst int64_t TICK_DURATION = 100;  // milliseconds\nconst int64_t TIME_UNIT = 10;       // 10ms\n\nHashedWheelTimer::HashedWheelTimer()\n{\n    started_at_ = Clock::CurrentTimeMillis();\n    last_time_ = Clock::CurrentTimeMillis();\n    wheel_.resize(WHEEL_SIZE);\n    for (int i = 0; i < WHEEL_SIZE; i++) {\n        wheel_[i] = new HashedWheelBucket();\n    }\n}\n\n\nHashedWheelTimer::~HashedWheelTimer()\n{\n    purge();\n}\n\nvoid HashedWheelTimer::purge()\n{\n    for (int i = 0; i < (int)wheel_.size(); i++) {\n        HashedWheelBucket* bucket = wheel_[i];\n        HashedWheelTimeout* node = bucket->head;\n        while (node != nullptr) {\n            HashedWheelTimeout* next = node->next;\n            delTimeout(node);\n            node = next;\n        }\n        bucket->head = bucket->tail = nullptr;\n        delete wheel_[i];\n    }\n    wheel_.clear();\n}\n\n\nint HashedWheelTimer::Start(uint32_t duration, TimeoutAction action)\n{\n    int id = nextId();\n    int64_t deadline = Clock::CurrentTimeMillis() + (int64_t)duration;\n    HashedWheelTimeout* timeout = allocTimeout(id, deadline, action);\n    int calculated = (int)(timeout->deadline - started_at_) / TICK_DURATION;\n    timeout->remaining_rounds = (calculated - ticks_) / WHEEL_SIZE;\n    int ticks = calculated < ticks_ ? ticks_ : calculated;\n    int stop_idx = ticks & (WHEEL_SIZE - 1);\n    wheel_[stop_idx]->AddTimeout(timeout);\n    ref_[id] = timeout;\n    return id;\n}\n\nbool HashedWheelTimer::Cancel(int timer_id)\n{\n    auto iter = ref_.find(timer_id);\n    if (iter == ref_.end()) {\n        return false;\n    }\n    HashedWheelTimeout* timeout = iter->second;\n    if (timeout != nullptr) {\n        timeout->bucket->Remove(timeout);\n        delTimeout(timeout);\n    }\n    return true;\n}\n\nint HashedWheelTimer::Update(int64_t now)\n{\n    if (Size() == 0) \n    {\n        return 0;\n    }\n    int64_t elapsed = now - last_time_;\n    int64_t ticks = elapsed / TIME_UNIT;\n    if (ticks <= 0)\n    {\n        return 0;\n    }\n    last_time_ = now;\n    int fired = 0;\n    for (int64_t i = 0; i < ticks; i++)\n    {\n        fired += tick();\n    }\n    return fired;\n}\n\nint HashedWheelTimer::tick()\n{\n    int64_t deadline = started_at_ + TICK_DURATION * (ticks_ + 1);\n    int idx = ticks_ % (WHEEL_SIZE - 1);\n    HashedWheelBucket* bucket = wheel_[idx];\n    std::vector<HashedWheelTimeout*> expired;\n    bucket->ExpireTimeouts(deadline, expired);\n    int count = (int)expired.size();\n    for (int i = 0; i < (int)expired.size(); i++) {\n        HashedWheelTimeout* timeout = expired[i];\n        timeout->Expire();\n        delTimeout(timeout);\n    }\n    ticks_++;\n    return count;\n}\n\n\nvoid HashedWheelTimer::delTimeout(HashedWheelTimeout* timeout)\n{\n    ref_.erase(timeout->id);\n    freeTimeout(timeout);\n}\n\nHashedWheelTimeout* HashedWheelTimer::allocTimeout(int id, int64_t deadline, TimeoutAction action)\n{\n    return new HashedWheelTimeout(id, deadline, action);\n}\n\nvoid HashedWheelTimer::freeTimeout(HashedWheelTimeout* p)\n{\n    delete p;\n}\n"
  },
  {
    "path": "src/HashedWheelTimer.h",
    "content": "// Copyright © 2021 ichenq@gmail.com All rights reserved.\n// See accompanying files LICENSE\n\n#pragma once\n\n#include \"TimerBase.h\"\n#include <vector>\n#include <unordered_map>\n\nclass HashedWheelBucket;\nclass HashedWheelTimeout;\n\n// A simple hashed wheel timer inspired by [Netty HashedWheelTimer]\n// see https://github.com/netty/netty/blob/4.1/common/src/main/java/io/netty/util/HashedWheelTimer.java\n//\n// timer scheduler implemented by hashed wheel\n// complexity:\n//      StartTimer   CancelTimer   PerTick\n//       O(1)         O(1)          O(1)\n//\nclass HashedWheelTimer : public TimerBase\n{\npublic:\n    HashedWheelTimer();\n    ~HashedWheelTimer();\n\n    TimerSchedType Type() const override\n    {\n        return TimerSchedType::TIMER_HASHED_WHEEL;\n    }\n\n    // start a timer after `duration` milliseconds\n    int Start(uint32_t duration, TimeoutAction action) override;\n\n    // cancel a timer\n    bool Cancel(int timer_id) override;\n\n    int Update(int64_t now = 0) override;\n\n    int Size() const override\n    {\n        return (int)ref_.size();\n    }\n\nprivate:\n    friend class HashedWheelTimeout;\n    friend class HashedWheelBucket;\n\n    int tick();\n\n    void purge();\n    void delTimeout(HashedWheelTimeout*);\n\n    HashedWheelTimeout* allocTimeout(int id, int64_t deadline, TimeoutAction action);\n    void freeTimeout(HashedWheelTimeout*);\n\nprivate:\n    std::vector<HashedWheelBucket*> wheel_;\n    std::unordered_map<int, HashedWheelTimeout*> ref_;\n    \n    int ticks_ = 0;\n    int64_t started_at_ = 0;\n    int64_t last_time_ = 0;\n};\n"
  },
  {
    "path": "src/Logging.cpp",
    "content": "// Protocol Buffers - Google's data interchange format\n// Copyright 2008 Google Inc.  All rights reserved.\n// https://developers.google.com/protocol-buffers/\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"Logging.h\"\n#include <cstdio>\n#include <cstring>\n#include <assert.h>\n#include <mutex>\n\n#ifdef _WIN32\n#include <Windows.h>\n#define snprintf _snprintf\n#endif\n\n#ifdef _MSC_VER\n#define DEBUG_BREAK __debugbreak()\n#else\n#define DEBUG_BREAK assert(false)\n#endif\n\nusing std::mutex;\nusing std::lock_guard;\n\nnamespace internal {\n\nvoid DefaultLogHandler(LogLevel level, const char* filename, int line,\n                       const std::string& message) \n{\n    static const char* level_names[] = { \"INFO\", \"WARNING\", \"ERROR\", \"FATAL\" };\n    const char* sep = strrchr(filename, '\\\\');\n    if (sep)\n    {\n        filename = sep;\n    }\n    char buffer[1024] = {};\n    snprintf(buffer, 1023, \"[%s %s:%d] %s\\n\", level_names[level], filename,\n        line, message.c_str());\n#if defined(_WIN32)\n    OutputDebugStringA(buffer);\n#else\n    fprintf(stderr, \"%s\", buffer);\n#endif\n}\n\nvoid NullLogHandler(LogLevel /* level */, const char* /* filename */,\n                    int /* line */, const std::string& /* message */) \n{\n    // Nothing.\n}\n\nstatic LogHandler* log_handler_ = &DefaultLogHandler;\nstatic int log_silencer_count_ = 0;\nstatic mutex log_silencer_count_mutex_;\n\nvoid LogMessage::Finish() {\n    bool suppress = false;\n\n    if (level_ != LOGLEVEL_FATAL) {\n        lock_guard<mutex> lock(log_silencer_count_mutex_);\n        suppress = log_silencer_count_ > 0;\n    }\n\n    if (!suppress) {\n        log_handler_(level_, filename_, line_, message_);\n    }\n\n    if (level_ == LOGLEVEL_FATAL) {\n        DEBUG_BREAK;\n        abort();\n    }\n}\n\nvoid LogFinisher::operator=(LogMessage& other) {\n    other.Finish();\n}\n\n} // namespace internal\n\n\nLogHandler* SetLogHandler(LogHandler* new_func) {\n    LogHandler* old = internal::log_handler_;\n    if (old == &internal::NullLogHandler) {\n        old = NULL;\n    }\n    if (new_func == NULL) {\n        internal::log_handler_ = &internal::NullLogHandler;\n    }\n    else {\n        internal::log_handler_ = new_func;\n    }\n    return old;\n}\n"
  },
  {
    "path": "src/Logging.h",
    "content": "// Protocol Buffers - Google's data interchange format\n// Copyright 2008 Google Inc.  All rights reserved.\n// https://developers.google.com/protocol-buffers/\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#ifndef UTILITY_LOGGING_H\n#define UTILITY_LOGGING_H\n\n#include <stdint.h>\n#include <string>\n#include <sstream>\n#include <type_traits>\n\n// ===================================================================\n// emulates google3/base/logging.h\n\nenum LogLevel {\n    LOGLEVEL_INFO,      // Informational.  \n    LOGLEVEL_WARNING,   // Warns about issues that, although not technically a\n                        // problem now, could cause problems in the future.  For\n                        // example, a // warning will be printed when parsing a\n                        // message that is near the message size limit.\n    LOGLEVEL_ERROR,     // An error occurred which should never happen during\n                        // normal use.\n    LOGLEVEL_FATAL,     // An error occurred from which the library cannot\n                        // recover.  This usually indicates a programming error\n                        // in the code which calls the library, especially when\n                        // compiled in debug mode.\n\n    LOGLEVEL_DFATAL = LOGLEVEL_FATAL\n};\n\nnamespace internal {\n\nclass LogFinisher;\n\nclass LogMessage {\npublic:\n    LogMessage(LogLevel level, const char* filename, int line)\n        : level_(level), filename_(filename), line_(line)\n    {\n    }\n\n    ~LogMessage()\n    {\n    }\n\n    LogMessage& operator<<(const std::string& value)\n    {\n        message_ += value;\n        return *this;\n    }\n\n    LogMessage& operator<<(const char* value)\n    {\n        message_ += value;\n        return *this;\n    }\n\n    template <typename T>\n    typename std::enable_if<\n        std::is_arithmetic<T>::value\n        || std::is_enum<T>::value, LogMessage&>::type\n        operator<<(T value)\n    {\n        std::ostringstream os;\n        os << value;\n        message_ += os.str();\n        return *this;\n    }\n\nprivate:\n    friend class LogFinisher;\n    void Finish();\n\n    LogLevel    level_;\n    const char* filename_;\n    int         line_;\n    std::string message_;\n};\n\n// Used to make the entire \"LOG(BLAH) << etc.\" expression have a void return\n// type and print a newline after each message.\nclass LogFinisher {\npublic:\n    void operator=(LogMessage& other);\n};\n\n}  // namespace internal\n\n// Undef everything in case we're being mixed with some other Google library\n// which already defined them itself.  Presumably all Google libraries will\n// support the same syntax for these so it should not be a big deal if they\n// end up using our definitions instead.\n#undef LOG\n#undef LOG_IF\n\n#undef CHECK\n#undef CHECK_OK\n#undef CHECK_EQ\n#undef CHECK_NE\n#undef CHECK_LT\n#undef CHECK_LE\n#undef CHECK_GT\n#undef CHECK_GE\n#undef CHECK_NOTNULL\n\n#undef DLOG\n#undef DCHECK\n#undef DCHECK_EQ\n#undef DCHECK_NE\n#undef DCHECK_LT\n#undef DCHECK_LE\n#undef DCHECK_GT\n#undef DCHECK_GE\n\n#define LOG(LEVEL) \\\n    ::internal::LogFinisher() =  \\\n    ::internal::LogMessage(::LOGLEVEL_##LEVEL, __FILE__, __LINE__)\n\n#define LOG_IF(LEVEL, CONDITION) \\\n  !(CONDITION) ? (void)0 : LOG(LEVEL)\n\n#define CHECK(EXPRESSION) \\\n  LOG_IF(FATAL, !(EXPRESSION)) << \"CHECK failed: \" #EXPRESSION \": \"\n#define CHECK_OK(A)     CHECK(A)\n#define CHECK_EQ(A, B)  CHECK((A) == (B))\n#define CHECK_NE(A, B)  CHECK((A) != (B))\n#define CHECK_LT(A, B)  CHECK((A) <  (B))\n#define CHECK_LE(A, B)  CHECK((A) <= (B))\n#define CHECK_GT(A, B)  CHECK((A) >  (B))\n#define CHECK_GE(A, B)  CHECK((A) >= (B))\n\n\nnamespace internal {\n    template<typename T>\n    T* CheckNotNull(const char* /* file */, int /* line */,\n        const char* name, T* val) {\n        if (val == NULL) {\n            LOG(FATAL) << name;\n        }\n        return val;\n    }\n}  // namespace internal\n\n\n#define CHECK_NOTNULL(A) \\\n  ::internal::CheckNotNull(__FILE__, __LINE__, \"'\" #A \"' must not be NULL\", (A))\n\n#ifdef NDEBUG\n\n#define DLOG LOG_IF(INFO, false)\n\n#define DCHECK(EXPRESSION) while(false) CHECK(EXPRESSION)\n#define DCHECK_EQ(A, B) DCHECK((A) == (B))\n#define DCHECK_NE(A, B) DCHECK((A) != (B))\n#define DCHECK_LT(A, B) DCHECK((A) <  (B))\n#define DCHECK_LE(A, B) DCHECK((A) <= (B))\n#define DCHECK_GT(A, B) DCHECK((A) >  (B))\n#define DCHECK_GE(A, B) DCHECK((A) >= (B))\n#define DCHECK_NOTNULL  CHECK_NOTNULL\n\n#else  // NDEBUG\n\n#define DLOG LOG\n\n#define DCHECK          CHECK\n#define DCHECK_EQ       CHECK_EQ\n#define DCHECK_NE       CHECK_NE\n#define DCHECK_LT       CHECK_LT\n#define DCHECK_LE       CHECK_LE\n#define DCHECK_GT       CHECK_GT\n#define DCHECK_GE       CHECK_GE\n#define DCHECK_NOTNULL  CHECK_NOTNULL\n\n#endif  // !NDEBUG\n\ntypedef void LogHandler(LogLevel level, const char* filename, int line,\n                        const std::string& message);\n\n// The protobuf library sometimes writes warning and error messages to\n// stderr.  These messages are primarily useful for developers, but may\n// also help end users figure out a problem.  If you would prefer that\n// these messages be sent somewhere other than stderr, call SetLogHandler()\n// to set your own handler.  This returns the old handler.  Set the handler\n// to NULL to ignore log messages (but see also LogSilencer, below).\n//\n// Obviously, SetLogHandler is not thread-safe.  You should only call it\n// at initialization time, and probably not from library code.  If you\n// simply want to suppress log messages temporarily (e.g. because you\n// have some code that tends to trigger them frequently and you know\n// the warnings are not important to you), use the LogSilencer class\n// below.\nLogHandler* SetLogHandler(LogHandler* new_func);\n\n\n#endif // UTILITY_LOGGING_H"
  },
  {
    "path": "src/Preprocessor.h",
    "content": "/*\n * Copyright 2014 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *   http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// @author: Andrei Alexandrescu\n\n#pragma once\n\n/**\n * FB_ANONYMOUS_VARIABLE(str) introduces an identifier starting with\n * str and ending with a number that varies with the line.\n */\n#ifndef FB_ANONYMOUS_VARIABLE\n#define FB_CONCATENATE_IMPL(s1, s2) s1##s2\n#define FB_CONCATENATE(s1, s2) FB_CONCATENATE_IMPL(s1, s2)\n#ifdef __COUNTER__\n#define FB_ANONYMOUS_VARIABLE(str) FB_CONCATENATE(str, __COUNTER__)\n#else\n#define FB_ANONYMOUS_VARIABLE(str) FB_CONCATENATE(str, __LINE__)\n#endif\n#endif\n\n/**\n * Use FB_STRINGIZE(x) when you'd want to do what #x does inside\n * another macro expansion.\n */\n#define FB_STRINGIZE(x) #x\n\n#ifdef _MSC_VER\n#define snprintf   sprintf_s\n#endif\n\n\n /**\n  * Call doNotOptimizeAway(var) to ensure that var will be computed even\n  * post-optimization.  Use it for variables that are computed during\n  * benchmarking but otherwise are useless. The compiler tends to do a\n  * good job at eliminating unused variables, and this function fools it\n  * into thinking var is in fact needed.\n  *\n  * Call makeUnpredictable(var) when you don't want the optimizer to use\n  * its knowledge of var to shape the following code.  This is useful\n  * when constant propagation or power reduction is possible during your\n  * benchmark but not in real use cases.\n  */\n\n#ifdef _MSC_VER\n\n#pragma optimize(\"\", off)\n\ninline void doNotOptimizeDependencySink(const void*) {}\n\n#pragma optimize(\"\", on)\n\ntemplate <class T>\nvoid doNotOptimizeAway(const T& datum) {\n    doNotOptimizeDependencySink(&datum);\n}\n\n#else\n\nnamespace detail {\ntemplate <typename T>\nstruct DoNotOptimizeAwayNeedsIndirect {\n    using Decayed = typename std::decay<T>::type;\n\n    // First two constraints ensure it can be an \"r\" operand.\n    // std::is_pointer check is because callers seem to expect that\n    // doNotOptimizeAway(&x) is equivalent to doNotOptimizeAway(x).\n    const static bool value = sizeof(Decayed) > sizeof(long) || std::is_pointer<Decayed>::value;\n};\n} // detail namespace\n\ntemplate <typename T>\nauto doNotOptimizeAway(const T& datum) -> typename std::enable_if<\n    !detail::DoNotOptimizeAwayNeedsIndirect<T>::value>::type {\n    // The \"r\" constraint forces the compiler to make datum available\n    // in a register to the asm block, which means that it must have\n    // computed/loaded it.  We use this path for things that are <=\n    // sizeof(long) (they have to fit), trivial (otherwise the compiler\n    // doesn't want to put them in a register), and not a pointer (because\n    // doNotOptimizeAway(&foo) would otherwise be a foot gun that didn't\n    // necessarily compute foo).\n    //\n    // An earlier version of this method had a more permissive input operand\n    // constraint, but that caused unnecessary variation between clang and\n    // gcc benchmarks.\n    asm volatile(\"\" ::\"r\"(datum));\n}\n\ntemplate <typename T>\nauto doNotOptimizeAway(const T& datum) -> typename std::enable_if<\n    detail::DoNotOptimizeAwayNeedsIndirect<T>::value>::type {\n    // This version of doNotOptimizeAway tells the compiler that the asm\n    // block will read datum from memory, and that in addition it might read\n    // or write from any memory location.  If the memory clobber could be\n    // separated into input and output that would be preferrable.\n    asm volatile(\"\" ::\"m\"(datum) : \"memory\");\n}\n\n#endif\n"
  },
  {
    "path": "src/PriorityQueueTimer.cpp",
    "content": "// Copyright © 2021 ichenq@gmail.com All rights reserved.\n// See accompanying files LICENSE\n\n#include \"PriorityQueueTimer.h\"\n#include \"Clock.h\"\n\nusing namespace std;\n\nstruct TimerNode\n{\n    int index = -1;  // array index at heap\n    int id = 0;      // unique timer id\n    int64_t deadline = 0;   // expired time in ms\n    TimeoutAction action = nullptr;\n\n    bool lessThan(const TimerNode* b) const\n    {\n        if (deadline == b->deadline) {\n            return id > b->id;\n        }\n        return deadline < b->deadline;\n    }\n};\n\n\nPriorityQueueTimer::PriorityQueueTimer()\n{\n    timers_.reserve(64); // reserve a little space\n}\n\n\nPriorityQueueTimer::~PriorityQueueTimer()\n{\n    clear();\n}\n\nvoid PriorityQueueTimer::clear()\n{\n    for (auto& kv : ref_)\n    {\n        delete(kv.second);\n    }\n    ref_.clear();\n    timers_.clear();\n}\n\n// Heap maintenance algorithms.\n// this to ensure run same min-heap algorithm on different platform,\n// you may replace with std::priority_queue instead\n\nstatic bool siftdownTimer(vector<TimerNode*>& timers, int x, int n)\n{\n    int i = x;\n    for (;;) {\n        int j1 = 2 * i + 1;\n        // j1 < 0 after int overflow         \n        if ((j1 >= n) || (j1 < 0)) {\n            break;\n        }\n        int j = j1; // left child\n        int j2 = j1 + 1;\n        if (j2 < n && !(timers[j1] < timers[j2])) {\n            j = j2; // = 2*i + 2right child\n        }\n        if (!(timers[j]->lessThan(timers[i]))) {\n            break;\n        }\n        std::swap(timers[i], timers[j]);\n        timers[i]->index = i;\n        timers[j]->index = j;\n        i = j;\n    }\n    return i > x;\n}\n\nstatic void siftupTimer(vector<TimerNode*>& timers, int j)\n{\n    for (;;) {\n        int i = (j - 1) / 2; // parent node\n        if (i == j || !(timers[j] < timers[i])) {\n            break;\n        }\n        std::swap(timers[i], timers[j]);\n        timers[i]->index = i;\n        timers[j]->index = j;\n        j = i;\n    }\n}\n\nstatic void removeTimer(vector<TimerNode*>& timers, int i) {\n    // swap with last element of array\n    int n = (int)timers.size() - 1;\n    if (i != n) {\n        std::swap(timers[i], timers[n]);\n        timers[i]->index = i;\n\n        // re-balance heap\n        if (!siftdownTimer(timers, i, n)) {\n            siftupTimer(timers, i);\n        }\n    }\n    timers.pop_back();\n}\n\nint PriorityQueueTimer::Start(uint32_t duration, TimeoutAction action)\n{\n    int id = nextId();\n    int64_t expire = Clock::CurrentTimeMillis() + (int64_t)duration;\n    int i = (int)timers_.size();\n\n    TimerNode* node = new TimerNode;\n    node->id = id;\n    node->index = i;\n    node->deadline = expire;\n    node->action = action;\n\n    ref_[id] = node;\n    timers_.push_back(node);\n    siftupTimer(timers_, i);\n\n    return id;\n}\n\nbool PriorityQueueTimer::Cancel(int timer_id)\n{\n    auto iter = ref_.find(timer_id);\n    if (iter != ref_.end()) {\n        TimerNode* node = iter->second;\n        removeTimer(timers_, node->index);\n        ref_.erase(iter);\n        delete node;\n        return true;\n    }\n    return false;\n}\n\nint PriorityQueueTimer::Update(int64_t now)\n{\n    if (timers_.empty()) {\n        return 0;\n    }\n    int fired = 0;\n    int max_id = next_id_;\n    while (!timers_.empty()) {\n        TimerNode* node = timers_[0];\n        if (now < node->deadline) {\n            break; // no timer expired\n        }\n        if (node->id > max_id) {\n            break; // process newly added timer at next tick\n        }\n        auto action = std::move(node->action);\n\n        removeTimer(timers_, 0);\n        ref_.erase(node->id);\n        delete node;\n\n        fired++;\n\n        if (action) {\n            action();\n        }\n    }\n    return fired;\n}\n\n"
  },
  {
    "path": "src/PriorityQueueTimer.h",
    "content": "// Copyright © 2021 ichenq@gmail.com All rights reserved.\n// See accompanying files LICENSE\n\n#pragma once\n\n#include \"TimerBase.h\"\n#include <vector>\n#include <unordered_map>\n\n\n// timer scheduler implemented by priority queue(min-heap)\n//\n// complexity:\n//     StartTimer  CancelTimer   PerTick\n//      O(log N)    O(log N)       O(1)\n//\n\nstruct TimerNode;\n\nclass PriorityQueueTimer : public TimerBase\n{\npublic:\n\n\npublic:\n    PriorityQueueTimer();\n    ~PriorityQueueTimer();\n\n    TimerSchedType Type() const override\n    {\n        return TimerSchedType::TIMER_PRIORITY_QUEUE;\n    }\n\n    // start a timer after `duration` milliseconds\n    int Start(uint32_t duration, TimeoutAction action) override;\n\n    // cancel a timer\n    bool Cancel(int timer_id) override;\n\n    int Update(int64_t now = 0) override;\n\n    int Size() const override \n    {\n        return (int)timers_.size();\n    }\n\nprivate:\n    void clear();\n\nprivate:\n    std::vector<TimerNode*>  timers_; // binary timer heap\n    std::unordered_map<int, TimerNode*> ref_; // to make O(1) lookup\n};\n"
  },
  {
    "path": "src/QuadHeapTimer.cpp",
    "content": "// Copyright © 2022 ichenq@gmail.com All rights reserved.\n// See accompanying files LICENSE\n\n\n#include \"QuadHeapTimer.h\"\n#include \"Clock.h\"\n#include \"Logging.h\"\n\nusing namespace std;\n\nstruct TimerNode\n{\n    int id = 0;       // unique timer id\n    int deleted = 0;  // lazy deletion\n    int64_t deadline = 0;\n    TimeoutAction action = nullptr;\n};\n\nQuadHeapTimer::QuadHeapTimer()\n{\n    timers_.reserve(64); // reserve a little space\n}\n\n\nQuadHeapTimer::~QuadHeapTimer()\n{\n    clear();\n}\n\nvoid QuadHeapTimer::clear()\n{\n    for (auto& kv : ref_)\n    {\n        delete kv.second;\n    }\n    ref_.clear();\n    timers_.clear();\n}\n\n// Heap maintenance algorithms.\n// details see https://github.com/golang/go/blob/go1.19.10/src/runtime/time.go\n\n// puts the timer at position i in the right place\n// in the heap by moving it up toward the top of the heap.\n// It returns the smallest changed index.\nstatic int siftupTimer(vector<TimerNode*>& timers, int i)\n{\n    CHECK(size_t(i) < timers.size());\n    int64_t when = timers[i]->deadline;\n    CHECK(when > 0);\n    TimerNode* tmp = timers[i];\n    while (i > 0) {\n        int p = (i - 1) / 4; // parent\n        if (when >= timers[p]->deadline) {\n            break;\n        }\n        timers[i] = timers[p];\n        i = p;\n    }\n    if (tmp != timers[i]) {\n        timers[i] = tmp;\n    }\n    return i;\n}\n\n// puts the timer at position i in the right place\n// in the heap by moving it down toward the bottom of the heap.\nstatic void siftdownTimer(vector<TimerNode*>& timers, int i)\n{\n    int n = int(timers.size());\n    CHECK(i < n);\n    int64_t when = timers[i]->deadline;\n    CHECK(when > 0);\n    TimerNode* tmp = timers[i];\n    while (true) {\n        int c = i * 4 + 1; // left child\n        int c3 = c + 2; // mid child\n        if (c >= n) {\n            break;\n        }\n        int64_t w = timers[c]->deadline;\n        if ((c + 1 < n) && (timers[c + 1]->deadline < w)) {\n            w = timers[c + 1]->deadline;\n            c++;\n        }\n        if (c3 < n) {\n            int64_t w3 = timers[c3]->deadline;\n            if ((c3 + 1 < n) && (timers[c3 + 1]->deadline < w3)) {\n                w3 = timers[c3 + 1]->deadline;\n                c3++;\n            }\n            if (w3 < w) {\n                w = w3;\n                c = c3;\n            }\n        }\n        if (w >= when) {\n            break;\n        }\n        timers[i] = timers[c];\n        i = c;\n    }\n    if (tmp != timers[i]) {\n        timers[i] = tmp;\n    }\n}\n\n// removes timer i from the current heap.\n// returns the smallest changed index in `timers`\nint deltimer(vector<TimerNode*>& timers, int i) {\n    int last = int(timers.size()) - 1;\n    if (last > 0) {\n        timers[0] = timers[last];\n    }\n    timers[last] = nullptr;\n    timers.pop_back();\n    int smallestChanged = i;\n    if (i != last) {\n        // Moving to i may have moved the last timer to a new parent,\n        // so sift up to preserve the heap guarantee.\n        smallestChanged = siftupTimer(timers, i);\n        siftdownTimer(timers, i);\n    }\n    return smallestChanged;\n}\n\n// removes timer 0 from the current heap.\nvoid deltimer0(vector<TimerNode*>& timers) {\n    int last = int(timers.size()) - 1;\n    if (last > 0) {\n        timers[0] = timers[last];\n    }\n    timers[last] = nullptr;\n    timers.pop_back();\n    if (last > 0) {\n        siftdownTimer(timers, 0);\n    }\n}\n\nint QuadHeapTimer::Start(uint32_t duration, TimeoutAction action)\n{\n    int id = nextId();\n    int64_t expire = Clock::CurrentTimeMillis() + (int64_t)duration;\n    int i = (int)timers_.size();\n\n    TimerNode* node = new TimerNode();\n    node->id = id;\n    node->deadline = expire;\n    node->action = action;\n\n    ref_[id] = node;\n    timers_.push_back(node);\n    siftupTimer(timers_, i);\n\n    return id;\n}\n\nbool QuadHeapTimer::Cancel(int timer_id)\n{\n    auto iter = ref_.find(timer_id);\n    if (iter != ref_.end()) {\n        iter->second->deleted = 1;\n        ref_.erase(iter);\n        return true;\n    }\n    return false;\n}\n\nint QuadHeapTimer::Update(int64_t now)\n{\n    if (timers_.empty()) {\n        return 0;\n    }\n    int fired = 0;\n    int max_id = next_id_;\n    while (!timers_.empty()) {\n        TimerNode* node = timers_[0];\n        if (now < node->deadline) {\n            break; // no timer expired\n        }\n        if (node->id > max_id) {\n            break; // process newly added timer at next tick\n        }\n        if (node->deleted) {\n            deltimer0(timers_);\n            ref_.erase(node->id);\n            delete node;\n            continue;\n        }\n\n        auto action = std::move(node->action);\n\n        deltimer0(timers_);\n        ref_.erase(node->id);\n        delete node;\n\n        fired++;\n\n        if (action) {\n            action();\n        }\n    }\n    return fired;\n}\n\n\n"
  },
  {
    "path": "src/QuadHeapTimer.h",
    "content": "// Copyright © 2022 ichenq@gmail.com All rights reserved.\n// See accompanying files LICENSE\n\n#pragma once\n\n#include \"TimerBase.h\"\n#include <vector>\n#include <unordered_map>\n\n// Quaternary-ary heap\n// https://en.wikipedia.org/wiki/D-ary_heap\n// \n// timer scheduler implemented by quaternary-ary heap\n//\n// complexity:\n//     StartTimer    CancelTimer   PerTick\n//      O(logN)      O(logN)          O(1)\n//\n\nstruct TimerNode;\n\nclass QuadHeapTimer : public TimerBase\n{public:\n    QuadHeapTimer();\n    ~QuadHeapTimer();\n\n    TimerSchedType Type() const override\n    {\n        return TimerSchedType::TIMER_QUAD_HEAP;\n    }\n\n    // start a timer after `duration` milliseconds\n    int Start(uint32_t duration, TimeoutAction action) override;\n\n    // cancel a timer\n    bool Cancel(int timer_id) override;\n\n    int Update(int64_t now = 0) override;\n\n    int Size() const override \n    {\n        return (int)timers_.size();\n    }    \n\nprivate:\n    void clear();\n    int delTimer(TimerNode& node);\n\n    std::vector<TimerNode*>  timers_; // 4-ary heap\n    std::unordered_map<int, TimerNode*> ref_; // O(1) search\n};\n"
  },
  {
    "path": "src/RBTreeTimer.cpp",
    "content": "// Copyright © 2022 ichenq@gmail.com All rights reserved.\n// See accompanying files LICENSE\n\n#include \"RBTreeTimer.h\"\n#include \"Clock.h\"\n\n\nRBTreeTimer::RBTreeTimer()\n{\n}\n\n\nRBTreeTimer::~RBTreeTimer()\n{\n    clear();\n}\n\nvoid RBTreeTimer::clear()\n{\n    timers_.clear();\n    ref_.clear();\n}\n\nint RBTreeTimer::Start(uint32_t duration, TimeoutAction action)\n{\n    int id = nextId();\n    NodeKey key;\n    key.id = id;\n    key.deadline = Clock::CurrentTimeMillis() + (int64_t)duration;\n    timers_.insert(std::make_pair(key, action));\n    ref_[id] = key;\n    return id;\n}\n\nbool RBTreeTimer::Cancel(int timer_id)\n{\n    auto iter = ref_.find(timer_id);\n    if (iter != ref_.end()) {\n        NodeKey key = iter->second;\n        ref_.erase(iter);\n        timers_.erase(key);\n        return true;\n    }\n    return false;\n}\n\nint RBTreeTimer::Update(int64_t now)\n{\n    if (timers_.size() == 0) {\n        return 0;\n    }\n    auto iter = timers_.begin();\n    int fired = 0;\n    int max_id = next_id_;\n    while (timers_.size() > 0 && iter != timers_.end())\n    {\n        const NodeKey& key = iter->first;\n        if (now < key.deadline) {\n            break; // no more due timer to trigger\n        }\n        // make sure we don't process newly created timer in timeout event\n        if (key.id > max_id) {\n            break;\n        }\n\n        TimeoutAction action = std::move(iter->second);\n        ref_.erase(key.id);\n        timers_.erase(key);\n\n        if (action) {\n            action(); // timeout action\n            fired++;\n        }\n\n        if (timers_.size() > 0) {\n            iter = timers_.begin();\n        }\n    }\n    return fired;\n}\n"
  },
  {
    "path": "src/RBTreeTimer.h",
    "content": "// Copyright © 2022 ichenq@gmail.com All rights reserved.\n// See accompanying files LICENSE\n\n#pragma once\n\n#include \"TimerBase.h\"\n#include <map>\n#include <unordered_map>\n\n// timer scheduler implemented by red-black tree.\n// complexity:\n//      StartTimer  CancelTimer   PerTick\n//       O(logN)     O(logN)      O(logN)\n//\nclass RBTreeTimer : public TimerBase\n{\npublic:\n    struct NodeKey\n    {\n        int id = 0;\n        int64_t deadline = 0;\n        \n        bool operator < (const NodeKey& b) const\n        {\n            if (deadline == b.deadline) {\n                return id > b.id; \n            }\n            return deadline < b.deadline;\n        }\n    };\n\npublic:\n    RBTreeTimer();\n    ~RBTreeTimer();\n\n    TimerSchedType Type() const override\n    {\n        return TimerSchedType::TIMER_RBTREE;\n    }\n\n    // start a timer after `duration` milliseconds\n    int Start(uint32_t duration, TimeoutAction action) override;\n\n    // cancel a timer\n    bool Cancel(int timer_id) override;\n\n    int Update(int64_t now = 0) override;\n\n    int Size() const override \n    { \n        return (int)timers_.size();\n    }\n\nprivate:\n    void clear();\n\n    // rbtree map implementation\n    std::multimap<NodeKey, TimeoutAction> timers_;\n    std::unordered_map<int , NodeKey> ref_;\n};\n\n"
  },
  {
    "path": "src/TimerBase.cpp",
    "content": "// Copyright © 2021 ichenq@gmail.com All rights reserved.\n// See accompanying files LICENSE\n\n#include \"TimerBase.h\"\n#include \"PriorityQueueTimer.h\"\n#include \"QuadHeapTimer.h\"\n#include \"RBTreeTimer.h\"\n#include \"HashedWheelTimer.h\"\n#include \"HHWheelTimer.h\"\n\nTimerBase::TimerBase()\n{\n}\n\nTimerBase::~TimerBase()\n{\n}\n\nint TimerBase::nextId()\n{\n    return next_id_++; // we do no duplicate checking here\n}\n\n\nstd::shared_ptr<TimerBase> CreateTimer(TimerSchedType sched_type)\n{\n    switch (sched_type)\n    {\n    case TimerSchedType::TIMER_PRIORITY_QUEUE:\n        return std::shared_ptr<TimerBase>(new PriorityQueueTimer());\n    case TimerSchedType::TIMER_QUAD_HEAP:\n        return std::shared_ptr<TimerBase>(new QuadHeapTimer());\n    case TimerSchedType::TIMER_RBTREE:\n        return std::shared_ptr<TimerBase>(new RBTreeTimer());\n    case TimerSchedType::TIMER_HASHED_WHEEL:\n        return std::shared_ptr<TimerBase>(new HashedWheelTimer());\n    case TimerSchedType::TIMER_HH_WHEEL:\n        return std::shared_ptr<TimerBase>(new HHWheelTimer());\n    default:\n        return nullptr;\n    }\n}\n"
  },
  {
    "path": "src/TimerBase.h",
    "content": "// Copyright © 2022 ichenq@gmail.com All rights reserved.\n// See accompanying files LICENSE\n\n#pragma once\n\n#include <stdint.h>\n#include <memory>\n#include <functional>\n\n\nenum class TimerSchedType\n{\n    TIMER_PRIORITY_QUEUE = 1,\n    TIMER_QUAD_HEAP = 2,\n    TIMER_RBTREE = 3,\n    TIMER_HASHED_WHEEL = 4,\n    TIMER_HH_WHEEL = 5,\n};\n\n// expiry action\ntypedef std::function<void()> TimeoutAction;\n\n// we model 3 simple API for the construction and management of timers.\n// \n//  1. int Start(interval, expiry_action)\n//     start a timer that will expire after `interval` unit of time\n//\n//  2. void Stop(timer_id)\n//    use `tiemr_id` to locate a timer and stop it\n//\n//  3. int Tick(now)\n//    per-tick bookking routine\n// \nclass TimerBase\n{\npublic:\n    TimerBase();\n    virtual ~TimerBase();\n\n    TimerBase(const TimerBase&) = delete;\n    TimerBase& operator=(const TimerBase&) = delete;\n\n    virtual TimerSchedType Type() const = 0;\n\n    // schedule a timer to run after specified time units(milliseconds).\n    // returns an unique id identify this timer.\n    // \n    // a `uint32_t` type of milliseconds means at most 49.7 days, that's good enough\n    virtual int Start(uint32_t ms, TimeoutAction action) = 0;\n\n    // cancel a timer by id\n    // return true if successfully canceld\n    virtual bool Cancel(int timer_id) = 0;\n\n    // per-tick bookkeeping\n    // return number of fired timers\n    virtual int Update(int64_t now) = 0;\n\n    // count of pending timers.\n    virtual int Size() const = 0;\n\nprotected:\n    int nextId();\n\n    int next_id_ = 2020;   // auto-increment timer id, with a magic  number\n};\n\nstd::shared_ptr<TimerBase> CreateTimer(TimerSchedType sched_type);\n"
  },
  {
    "path": "src/list_impl.h",
    "content": "// Distributed under GPLv3 license, see accompanying files LICENSE\n\n#pragma once\n\n#include <stddef.h>\n\n\n/**\n * container_of - cast a member of a structure out to the containing structure\n *\n * @ptr:\t    the pointer to the member.\n * @type:       the type of the container struct this is embedded in.\n * @member:     the name of the member within the struct.\n *\n */\n#ifndef container_of\n#define container_of(ptr, type, member) ((type *)((char *)(ptr) - offsetof(type, member)))\n#endif\n\n\n/**\n * list_entry - get the struct for this entry\n * @ptr:\tthe &struct list_head pointer.\n * @type:\tthe type of the struct this is embedded in.\n * @member:\tthe name of the list_struct within the struct.\n */\n#ifndef list_entry\n#define list_entry(ptr, type, member) container_of(ptr, type, member)\n#endif\n\n /**\n  * list_first_entry - get the first element from a list\n  * @ptr:\tthe list head to take the element from.\n  * @type:\tthe type of the struct this is embedded in.\n  * @member:\tthe name of the list_struct within the struct.\n  *\n  * Note, that list is expected to be not empty.\n  */\n#define list_first_entry(ptr, type, member) list_entry((ptr)->next, type, member)\n\n\nstruct list_head {\n    list_head* next = NULL;\n    list_head* prev = NULL;\n};\n\ninline void INIT_LIST_HEAD(list_head* list) {\n    list->next = list;\n    list->prev = list;\n}\n\n/**\n * list_empty - tests whether a list is empty\n * @head: the list to test.\n */\ninline int list_empty(const struct list_head* head)\n{\n    return head->next == head;\n}\n\n/**\n * list_replace - replace old entry by new one\n * @old : the element to be replaced\n * @new : the new element to insert\n *\n * If @old was empty, it will be overwritten.\n */\ninline void list_replace(list_head* old, list_head* new_)\n{\n    new_->next = old->next;\n    new_->next->prev = new_;\n    new_->prev = old->prev;\n    new_->prev->next = new_;\n}\n\ninline void list_replace_init(list_head* old, list_head* new_) {\n    list_replace(old, new_);\n    INIT_LIST_HEAD(old);\n}\n\n/*\n * Insert a new entry between two known consecutive entries.\n *\n * This is only for internal list manipulation where we know\n * the prev/next entries already!\n */\ninline void __list_add(list_head* new_, list_head* prev, list_head* next) {\n    next->prev = new_;\n    new_->next = next;\n    new_->prev = prev;\n    prev->next = new_;\n}\n\n/*\n * Delete a list entry by making the prev/next entries\n * point to each other.\n *\n * This is only for internal list manipulation where we know\n * the prev/next entries already!\n */\ninline void __list_del(list_head* prev, list_head* next)\n{\n    next->prev = prev;\n    prev->next = next;\n}\n\n/**\n * list_add_tail - add a new entry\n * @new: new entry to be added\n * @head: list head to add it before\n *\n * Insert a new entry before the specified head.\n * This is useful for implementing queues.\n */\ninline void list_add_tail(struct list_head* new_, struct list_head* head)\n{\n    __list_add(new_, head->prev, head);\n}\n\n\n/*\n * Architectures might want to move the poison pointer offset\n * into some well-recognized area such as 0xdead000000000000,\n * that is also not mappable by user-space exploits:\n */\n#define POISON_POINTER_DELTA 0\n\n\n/*\n * These are non-NULL pointers that will result in page faults\n * under normal circumstances, used to verify that nobody uses\n * non-initialized list entries.\n */\n#define LIST_POISON1  (0x00100100 + POISON_POINTER_DELTA)\n#define LIST_POISON2  (0x00200200 + POISON_POINTER_DELTA)\n"
  },
  {
    "path": "src/timer_list.cpp",
    "content": "// Distributed under GPLv3 license, see accompanying files LICENSE\n\n#include \"timer_list.h\"\n#include <assert.h>\n\nvoid init_timers(struct tvec_base* base, int64_t clock)\n{\n    for (int j = 0; j < TVN_SIZE; j++) {\n        INIT_LIST_HEAD(base->tv5.vec + j);\n        INIT_LIST_HEAD(base->tv4.vec + j);\n        INIT_LIST_HEAD(base->tv3.vec + j);\n        INIT_LIST_HEAD(base->tv2.vec + j);\n    }\n    for (int j = 0; j < TVR_SIZE; j++)\n        INIT_LIST_HEAD(base->tv1.vec + j);\n\n    base->timer_clk = clock;\n}\n\nstatic inline void timer_set_base(struct timer_list* timer, struct tvec_base* new_base)\n{\n    timer->base = new_base;\n}\n\nstatic void __internal_add_timer(struct tvec_base* base, struct timer_list* timer)\n{\n    int64_t expires = timer->expires;\n    int64_t idx = expires - base->timer_clk;\n    struct list_head* vec;\n\n    if (idx < TVR_SIZE) {\n        int i = expires & TVR_MASK;\n        vec = base->tv1.vec + i;\n    }\n    else if (idx < 1 << (TVR_BITS + TVN_BITS)) {\n        int i = (expires >> TVR_BITS) & TVN_MASK;\n        vec = base->tv2.vec + i;\n    }\n    else if (idx < 1 << (TVR_BITS + 2 * TVN_BITS)) {\n        int i = (expires >> (TVR_BITS + TVN_BITS)) & TVN_MASK;\n        vec = base->tv3.vec + i;\n    }\n    else if (idx < 1 << (TVR_BITS + 3 * TVN_BITS)) {\n        int i = (expires >> (TVR_BITS + 2 * TVN_BITS)) & TVN_MASK;\n        vec = base->tv4.vec + i;\n    }\n    else if (idx < 0) {\n        /*\n         * Can happen if you add a timer with expires == jiffies,\n         * or you set a timer to go off in the past\n         */\n        vec = base->tv1.vec + (base->timer_clk & TVR_MASK);\n    }\n    else {\n        int i;\n        /* If the timeout is larger than MAX_TVAL (on 64-bit\n         * architectures or with CONFIG_BASE_SMALL=1) then we\n         * use the maximum timeout.\n         */\n        if (idx > MAX_TVAL) {\n            idx = MAX_TVAL;\n            expires = idx + base->timer_clk;\n        }\n        i = (expires >> (TVR_BITS + 3 * TVN_BITS)) & TVN_MASK;\n        vec = base->tv5.vec + i;\n    }\n    /*\n     * Timers are FIFO:\n     */\n    list_add_tail(&timer->entry, vec);\n}\n\nstatic void internal_add_timer(struct tvec_base* base, struct timer_list* timer)\n{\n    __internal_add_timer(base, timer);\n    // Update base->active_timers and base->next_timer\n}\n\nstatic inline void detach_timer(struct timer_list* timer, bool clear_pending)\n{\n    struct list_head* entry = &timer->entry;\n\n    __list_del(entry->prev, entry->next);\n    if (clear_pending) {\n        entry->next = NULL;\n    }\n    entry->prev = reinterpret_cast<list_head*>(LIST_POISON2);\n}\n\nstatic inline void detach_expired_timer(struct timer_list* timer, struct tvec_base* base)\n{\n    detach_timer(timer, true);\n}\n\nstatic int detach_if_pending(struct timer_list* timer, struct tvec_base* base, bool clear_pending)\n{\n    if (!timer_pending(timer)) {\n        return 0;\n    }\n\n    detach_timer(timer, clear_pending);\n    return 1;\n}\n\nstatic inline int __mod_timer(struct timer_list* timer, int64_t expires, bool pending_only)\n{\n    assert(timer->function);\n    int ret = detach_if_pending(timer, timer->base, false);\n    if (!ret && pending_only) {\n        return ret;\n    }\n    timer->expires = expires;\n    internal_add_timer(timer->base, timer);\n    return ret;\n}\n\nstatic void migrate_timer_list(struct tvec_base* new_base, struct list_head* head)\n{\n    struct timer_list* timer;\n\n    while (!list_empty(head)) {\n        timer = list_first_entry(head, struct timer_list, entry);\n        /* We ignore the accounting on the dying cpu */\n        detach_timer(timer, false);\n        timer_set_base(timer, new_base);\n        internal_add_timer(new_base, timer);\n    }\n}\n\nint mod_timer_pending(struct timer_list* timer, int64_t expires)\n{\n    return __mod_timer(timer, expires, true);\n}\n\nint mod_timer(struct timer_list* timer, int64_t expires)\n{\n    if (timer_pending(timer) && timer->expires == expires) {\n        return 1;\n    }\n    return __mod_timer(timer, expires, false);\n}\n\nvoid add_timer(struct timer_list* timer)\n{\n    assert(!timer_pending(timer));\n    mod_timer(timer, timer->expires);\n}\n\nint del_timer(struct timer_list* timer)\n{\n    int ret = 0;\n    if (timer_pending(timer)) {\n        ret = detach_if_pending(timer, timer->base, true);\n    }\n    return ret;\n}\n\nstatic int cascade(struct tvec_base* base, struct tvec* tv, int index)\n{\n    /* cascade all the timers from tv up one level */\n    struct list_head tv_list;\n\n    list_replace_init(tv->vec + index, &tv_list);\n\n    /*\n     * We are removing _all_ timers from the list, so we\n     * don't have to detach them individually.\n     */\n    timer_list* timer = list_entry(tv_list.next, timer_list, entry);\n    timer_list* tmp = list_entry(timer->entry.next, timer_list, entry);\n\n    while (&timer->entry != &tv_list)\n    {\n        timer = tmp;\n        tmp = list_entry(tmp->entry.next, timer_list, entry);\n        // BUG_ON(tbase_get_base(timer->base) != base);\n        /* No accounting, while moving them */\n        __internal_add_timer(base, timer);\n    }\n\n    return index;\n}\n\n\n\n#define INDEX(N) ((base->timer_clk >> (TVR_BITS + (N) * TVN_BITS)) & TVN_MASK)\n\nint run_timers(struct tvec_base* base, int64_t clock)\n{\n    int n = 0;\n    while (time_after_eq(clock, base->timer_clk)) {\n        struct list_head work_list;\n        struct list_head* head = &work_list;\n        int index = base->timer_clk & TVR_MASK;\n        \n         // Cascade timers:\n        if (!index &&\n            (!cascade(base, &base->tv2, INDEX(0))) &&\n            (!cascade(base, &base->tv3, INDEX(1))) &&\n            !cascade(base, &base->tv4, INDEX(2))) {\n            cascade(base, &base->tv5, INDEX(3));\n        }\n        ++base->timer_clk;\n        list_replace_init(base->tv1.vec + index, &work_list);\n\n        while (!list_empty(head)) {\n            struct timer_list* timer = list_first_entry(head, timer_list, entry);\n            auto fn = timer->function;\n            base->running_timer = timer;\n            detach_expired_timer(timer, base);\n\n            assert(fn);\n            fn(timer);\n\n            n++;\n        }\n    }\n    base->running_timer = NULL;\n    return n;\n}\n\n"
  },
  {
    "path": "src/timer_list.h",
    "content": "// Distributed under GPLv3 license, see accompanying files LICENSE\n\n#pragma once\n\n#include <stdint.h>\n#include \"list_impl.h\"\n\n/*\n *\tThese inlines deal with timer wrapping correctly. You are\n *\tstrongly encouraged to use them\n *\t1. Because people otherwise forget\n *\t2. Because if the timer wrap changes in future you won't have to\n *\t   alter your driver code.\n *\n * time_after(a,b) returns true if the time a is after time b.\n *\n * Do this with \"<0\" and \">=0\" to only test the sign of the result. A\n * good compiler would generate better code (and a really good compiler\n * wouldn't care). Gcc is currently neither.\n */\n#define time_after(a,b)     ((int64_t)(b) - (int64_t)(a) < 0)\n#define time_before(a,b)\ttime_after(b,a)\n\n#define time_after_eq(a,b)\t((int64_t)(a) - (int64_t)(b) >= 0)\n#define time_before_eq(a,b)\ttime_after_eq(b,a)\n\n /*\n  * timer vector definitions\n  */\n#define TVN_BITS (6)\n#define TVR_BITS (8)\n#define TVN_SIZE (1 << TVN_BITS)\n#define TVR_SIZE (1 << TVR_BITS)\n#define TVN_MASK (TVN_SIZE - 1)\n#define TVR_MASK (TVR_SIZE - 1)\n#define MAX_TVAL ((uint64_t)((1ULL << (TVR_BITS + 4*TVN_BITS)) - 1))\n\n\nstruct tvec {\n    list_head vec[TVN_SIZE];\n};\n\nstruct tvec_root {\n    list_head vec[TVR_SIZE];\n};\n\nstruct tvec_base;\n\nstruct timer_list {\n    struct list_head entry;\n    int id = 0;\n    int64_t expires = 0;\n    tvec_base* base = NULL;\n    void (*function)(timer_list*) = NULL;\n    void* data;\n};\n\nstruct tvec_base {\n    timer_list* running_timer = NULL;\n    int64_t timer_clk = 0;\n    struct tvec_root tv1;\n    struct tvec tv2;\n    struct tvec tv3;\n    struct tvec tv4;\n    struct tvec tv5;\n};\n\n\n// is a timer pending ?\ninline int timer_pending(const struct timer_list* timer)\n{\n    return timer->entry.next != NULL;\n}\n\nvoid init_timers(struct tvec_base* base, int64_t clock);\n\n/*\n * mod_timer_pending - modify a pending timer's timeout\n * @timer: the pending timer to be modified\n * @expires: new timeout in jiffies\n *\n * mod_timer_pending() is the same for pending timers as mod_timer(),\n * but will not re-activate and modify already deleted timers.\n *\n * It is useful for unserialized use of timers.\n */\nint mod_timer_pending(struct timer_list* timer, int64_t expires);\n\n/*\n * mod_timer - modify a timer's timeout\n * @timer: the timer to be modified\n * @expires: new timeout \n *\n * mod_timer() is a more efficient way to update the expire field of an\n * active timer (if the timer is inactive it will be activated)\n *\n * mod_timer(timer, expires) is equivalent to:\n *\n *     del_timer(timer); timer->expires = expires; add_timer(timer);\n *\n *\n * The function returns whether it has modified a pending timer or not.\n * (ie. mod_timer() of an inactive timer returns 0, mod_timer() of an\n * active timer returns 1.)\n */\nint mod_timer(struct timer_list* timer, int64_t expires);\n\n/*\n * add_timer - start a timer\n * @timer: the timer to be added\n *\n * Timers with an ->expires field in the past will be executed in the next\n * timer tick.\n */\nvoid add_timer(struct timer_list* timer);\n\n/*\n * del_timer - deactive a timer.\n * @timer: the timer to be deactivated\n *\n * del_timer() deactivates a timer - this works on both active and inactive\n * timers.\n *\n * The function returns whether it has deactivated a pending timer or not.\n * (ie. del_timer() of an inactive timer returns 0, del_timer() of an\n * active timer returns 1.)\n */\nint del_timer(struct timer_list* timer);\n\n/**\n * run_timers - run all expired timers (if any).\n * @base: the timer vector to be processed.\n *\n * This function cascades all vectors and executes all expired timer\n * vectors.\n */\nint run_timers(struct tvec_base* base, int64_t clock);\n"
  },
  {
    "path": "test/BenchTimer.cpp",
    "content": "// Copyright (C) 2018 ichenq@outlook.com. All rights reserved.\n// Distributed under the terms and conditions of the Apache License. \n// See accompanying files LICENSE.\n\n#include <algorithm>\n#include \"TimerBase.h\"\n#include \"Clock.h\"\n#include \"Preprocessor.h\"\n#include <benchmark/benchmark.h>\n#include <vector>\n\nusing namespace std;\n\nconst int MaxN = 50000;   // max timer count\n\n// see https://en.wikipedia.org/wiki/Linear_congruential_generator\nuint32_t lcg_seed(uint32_t seed) {\n    return seed * 214013 + 2531011;\n}\n\nuint32_t lcg_rand(uint32_t& seed) {\n    seed = seed * 214013 + 2531011;\n    uint32_t r = uint32_t(seed >> 16) & 0x7fff;\n    return r;\n}\n\nstatic std::shared_ptr<TimerBase> createAndStartTimer(TimerSchedType timerType, benchmark::State& state) {\n    uint32_t seed = lcg_seed(12345);\n\n    auto timer = CreateTimer(timerType);\n    auto dummy = []() {};\n    for (auto _ : state)\n    {\n        uint32_t duration = lcg_rand(seed) % 5000;\n        timer->Start(duration, dummy);\n    }\n    return timer;\n}\n\nstatic void BM_PQTimerAdd(benchmark::State& state)\n{\n    auto timer = createAndStartTimer(TimerSchedType::TIMER_PRIORITY_QUEUE, state);\n    doNotOptimizeAway(timer);\n}\n\nstatic void BM_QuadHeapTimerAdd(benchmark::State& state)\n{\n    auto timer = createAndStartTimer(TimerSchedType::TIMER_QUAD_HEAP, state);\n    doNotOptimizeAway(timer);\n}\n\nstatic void BM_RBTreeTimerAdd(benchmark::State& state)\n{\n    auto timer = createAndStartTimer(TimerSchedType::TIMER_RBTREE, state);\n    doNotOptimizeAway(timer);\n}\n\nstatic void BM_HashWheelTimerAdd(benchmark::State& state)\n{\n    auto timer = createAndStartTimer(TimerSchedType::TIMER_HASHED_WHEEL, state);\n    doNotOptimizeAway(timer);\n}\n\nstatic void BM_HHWheelTimerAdd(benchmark::State& state)\n{\n    auto timer = createAndStartTimer(TimerSchedType::TIMER_HH_WHEEL, state);\n    doNotOptimizeAway(timer);\n}\n\nBENCHMARK(BM_PQTimerAdd);\nBENCHMARK(BM_QuadHeapTimerAdd);\nBENCHMARK(BM_RBTreeTimerAdd);\nBENCHMARK(BM_HashWheelTimerAdd);\nBENCHMARK(BM_HHWheelTimerAdd);\n\n\nstatic std::shared_ptr<TimerBase> createAndFillTimer(TimerSchedType timerType, int N, vector<int>& out) {\n    uint32_t seed = lcg_seed(12345);\n    auto timer = CreateTimer(timerType);\n    auto dummy = []() {};\n    for (int i = 0; i < N; i++)\n    {\n        uint32_t duration = lcg_rand(seed) % 5000;\n        int tid = timer->Start(duration, dummy);\n        out.push_back(tid);\n    }\n    std::random_shuffle(out.begin(), out.end());\n    return timer;\n}\n\nstatic void benchTimerCancel(TimerSchedType timerType, benchmark::State& state)\n{\n    int N = (int)state.max_iterations;\n    vector<int> timer_ids;\n    timer_ids.reserve(N);\n    auto timer = createAndFillTimer(timerType, N, timer_ids);\n    for (auto _ : state)\n    {\n        if (timer_ids.empty()) {\n            break;\n        }\n        int timer_id = timer_ids.back();\n        timer_ids.pop_back();\n        timer->Cancel(timer_id);\n    }\n    doNotOptimizeAway(timer);\n}\n\nstatic void BM_PQTimerCancel(benchmark::State& state) {\n\n    benchTimerCancel(TimerSchedType::TIMER_PRIORITY_QUEUE, state);\n}\n\nstatic void BM_QuadHeapTimerCancel(benchmark::State& state) {\n\n    benchTimerCancel(TimerSchedType::TIMER_QUAD_HEAP, state);\n}\n\nstatic void BM_RBTreeTimerCancel(benchmark::State& state) {\n\n    benchTimerCancel(TimerSchedType::TIMER_RBTREE, state);\n}\n\nstatic void BM_HashWheelTimerCancel(benchmark::State& state) {\n\n    benchTimerCancel(TimerSchedType::TIMER_HASHED_WHEEL, state);\n}\n\nstatic void BM_HHWheelTimerCancel(benchmark::State& state) {\n\n    benchTimerCancel(TimerSchedType::TIMER_HH_WHEEL, state);\n}\n\n\nBENCHMARK(BM_PQTimerCancel);\nBENCHMARK(BM_QuadHeapTimerCancel); // lazy deletion here not fair\nBENCHMARK(BM_RBTreeTimerCancel);\nBENCHMARK(BM_HashWheelTimerCancel);\nBENCHMARK(BM_HHWheelTimerCancel);\n\n\nstatic void benchTimerTick(TimerSchedType timerType, benchmark::State& state)\n{\n    vector<int> timer_ids;\n    timer_ids.reserve(MaxN);\n    auto timer = createAndFillTimer(timerType, MaxN, timer_ids);\n    for (auto _ : state)\n    {\n        timer->Update(Clock::CurrentTimeMillis());\n    }\n    doNotOptimizeAway(timer);\n}\n\nstatic void BM_PQTimerTick(benchmark::State& state) {\n\n    benchTimerTick(TimerSchedType::TIMER_PRIORITY_QUEUE, state);\n}\n\nstatic void BM_QuadHeapTimerTick(benchmark::State& state) {\n\n    benchTimerTick(TimerSchedType::TIMER_QUAD_HEAP, state);\n}\n\nstatic void BM_RBTreeTimerTick(benchmark::State& state) {\n\n    benchTimerTick(TimerSchedType::TIMER_RBTREE, state);\n}\n\nstatic void BM_HashWheelTimerTick(benchmark::State& state) {\n\n    benchTimerTick(TimerSchedType::TIMER_HASHED_WHEEL, state);\n}\n\nstatic void BM_HHWheelTimerTick(benchmark::State& state) {\n\n    benchTimerTick(TimerSchedType::TIMER_HH_WHEEL, state);\n}\n\n\nBENCHMARK(BM_PQTimerTick);\nBENCHMARK(BM_QuadHeapTimerTick);\nBENCHMARK(BM_RBTreeTimerTick);\nBENCHMARK(BM_HashWheelTimerTick);\nBENCHMARK(BM_HHWheelTimerTick);\n\n"
  },
  {
    "path": "test/TestTimer.cpp",
    "content": "// Copyright © 2021 ichenq@gmail.com All rights reserved.\r\n// See accompanying files LICENSE\r\n\r\n#include <chrono>\r\n#include <thread>\r\n#include <numeric>\r\n#include <vector>\r\n#include <algorithm>\r\n#include <unordered_map>\r\n#include <memory>\r\n#include <gtest/gtest.h>\r\n#include \"Clock.h\"\r\n#include \"TimerBase.h\"\r\n#include \"Preprocessor.h\"\r\n\r\nusing namespace std;\r\n\r\nconst int N1 = 1000;\r\nconst int N2 = 10;\r\nconst int TRY = 2;\r\nconst int TIME_DELTA = 10;\r\n\r\nstruct TimeOutContext {\r\n    int id = 0;\r\n    int interval = 0;\r\n    int64_t deadline = 0;\r\n    int64_t fired_at = 0;\r\n};\r\n\r\nstatic void TestTimerAdd(TimerBase *timer, int count) {\r\n    int called = 0;\r\n    for (int i = 0; i < count; i++) {\r\n        timer->Start(0, [&]() {\r\n            called++;\r\n        });\r\n    }\r\n\r\n    // to make sure timing-wheel trigger all timers at next time unit\r\n    std::this_thread::sleep_for(std::chrono::milliseconds(10));\r\n\r\n    EXPECT_EQ(timer->Size(), count);\r\n    int fired = timer->Update(Clock::CurrentTimeMillis());\r\n    EXPECT_EQ(fired, count);\r\n    EXPECT_EQ(called, count);\r\n    EXPECT_EQ(timer->Size(), 0);\r\n\r\n    called = 0;\r\n    for (int i = 0; i < count; i++) {\r\n        int id = timer->Start(0, [&]() {\r\n            called++;\r\n        });\r\n        timer->Cancel(id);\r\n    }\r\n    fired = timer->Update(Clock::CurrentTimeMillis());\r\n    EXPECT_EQ(fired, 0);\r\n    EXPECT_EQ(timer->Size(), 0);\r\n    EXPECT_EQ(called, 0);\r\n\r\n    doNotOptimizeAway(called);\r\n    doNotOptimizeAway(fired);\r\n}\r\n\r\nstatic void TestTimerDel(TimerBase *timer, int count) {\r\n    int called = 0;\r\n    int tid = timer->Start(100, [&]() {\r\n        called++;\r\n    });\r\n\r\n    timer->Update(Clock::CurrentTimeMillis());\r\n    timer->Cancel(tid);\r\n\r\n    EXPECT_EQ(called, 0);\r\n}\r\n\r\nstatic void TestTimerExpire(TimerBase *timer, int count) {\r\n    int64_t max_interval = 0;\r\n    std::unordered_map<int, TimeOutContext*> timedOut;\r\n    for (int i = 0; i < count; i++) {\r\n        int interval = TIME_DELTA + (rand() % 100);\r\n        TimeOutContext* ctx = new(TimeOutContext);\r\n        ctx->interval = interval;\r\n        ctx->deadline = Clock::CurrentTimeMillis() + interval;\r\n        if (max_interval < interval) {\r\n            max_interval = interval;\r\n        }\r\n        int id = timer->Start(interval, [=]() {\r\n            //printf(\"timer %d fired\\n\", ctx->id);\r\n            ctx->fired_at = Clock::CurrentTimeMillis();\r\n        });\r\n        ctx->id = id;\r\n    }\r\n    EXPECT_EQ(timer->Size(), count);\r\n\r\n    // execute all timers\r\n    auto now = Clock::CurrentTimeString(Clock::CurrentTimeMillis());\r\n    printf(\"start execute timer at %s\\n\", now.c_str());\r\n\r\n    int fired = 0;\r\n    for (int i = 0; i <= max_interval; i++) {\r\n        fired += timer->Update(Clock::CurrentTimeMillis());\r\n        std::this_thread::sleep_for(std::chrono::milliseconds(1));\r\n    }\r\n\r\n    EXPECT_EQ(timer->Size(), 0);\r\n\r\n    for (const auto& kv : timedOut) {\r\n        TimeOutContext* ctx = kv.second;\r\n        EXPECT_GE(ctx->fired_at, ctx->deadline);\r\n        int64_t duration = ctx->fired_at > ctx->deadline;\r\n        if (duration < 0) {\r\n            printf(\"timer %d failed %lld\\n\", ctx->id, duration);\r\n        }\r\n    }\r\n}\r\n\r\n// same deadline timers should expired in FIFO order\r\nstatic void TestTimerExpireFIFO(TimerBase *timer) {\r\n    std::vector<TimeOutContext*> expired;\r\n    int64_t deadline = Clock::CurrentTimeMillis() + 100;\r\n    for (int i = 0; i < 50; i++) {\r\n        uint32_t duration = uint32_t(deadline - Clock::CurrentTimeMillis());\r\n        TimeOutContext* ctx = new(TimeOutContext);\r\n        ctx->deadline = deadline;\r\n        ctx->interval = duration;\r\n        int tid = timer->Start(duration, [=,&expired]() {\r\n            //printf(\"timer %d fired\\n\", ctx->id);\r\n            ctx->fired_at = Clock::CurrentTimeMillis();\r\n            expired.push_back(ctx);\r\n        });\r\n        ctx->id = tid;\r\n    }\r\n    for (int i = 0; i < 100; i++) {\r\n        timer->Update(Clock::CurrentTimeMillis());\r\n        std::this_thread::sleep_for(std::chrono::milliseconds(1));\r\n    }\r\n    timer->Update(Clock::CurrentTimeMillis());\r\n\r\n    EXPECT_EQ(expired.size(), 50);\r\n\r\n    cout << \"expire order: \";\r\n    for (int i = 0; i < expired.size(); i++)\r\n    {\r\n        cout << expired[i]->id << \" \";\r\n    }\r\n    cout << endl;\r\n    \r\n    bool sorted = std::is_sorted(expired.begin(), expired.end(), [](TimeOutContext* a, TimeOutContext* b) {\r\n        return a->id < b->id;\r\n    });\r\n    bool reverseSorted = std::is_sorted(expired.begin(), expired.end(), [](TimeOutContext* a, TimeOutContext* b) {\r\n        return a->id > b->id;\r\n    });\r\n\r\n    if (sorted) {\r\n        printf(\"timer type %d is expired in FIFO order\\n\", timer->Type());\r\n    } else if (reverseSorted) {\r\n        printf(\"timer type %d is expired in FILO order\\n\", timer->Type());\r\n    } else {\r\n        printf(\"timer type %d is expired out of order\\n\", timer->Type());\r\n    }\r\n}\r\n\r\n\r\nTEST(TimerPriorityQueue, TimerAdd) {\r\n    auto timer = CreateTimer(TimerSchedType::TIMER_PRIORITY_QUEUE);\r\n    TestTimerAdd(timer.get(), N1);\r\n}\r\n\r\nTEST(TimerPriorityQueue, TimerDel) {\r\n    auto timer = CreateTimer(TimerSchedType::TIMER_PRIORITY_QUEUE);\r\n    TestTimerDel(timer.get(), N1);\r\n}\r\n\r\n\r\nTEST(TimerPriorityQueue, TimerExpireDelay) {\r\n    auto timer = CreateTimer(TimerSchedType::TIMER_PRIORITY_QUEUE);\r\n    TestTimerExpire(timer.get(), N1);\r\n}\r\n\r\nTEST(TimerPriorityQueue, TimerExpireFIFO) {\r\n    auto timer = CreateTimer(TimerSchedType::TIMER_PRIORITY_QUEUE);\r\n    TestTimerExpireFIFO(timer.get());\r\n}\r\n\r\n///////////////////////////////////////////////////////////////////\r\n\r\n\r\nTEST(TimerQuadHeap, TimerAdd) {\r\n    auto timer = CreateTimer(TimerSchedType::TIMER_QUAD_HEAP);\r\n    TestTimerAdd(timer.get(), N1);\r\n}\r\n\r\nTEST(TimerQuadHeap, TimerDel) {\r\n    auto timer = CreateTimer(TimerSchedType::TIMER_QUAD_HEAP);\r\n    TestTimerDel(timer.get(), N1);\r\n}\r\n\r\n\r\nTEST(TimerQuadHeap, TimerExpireDelay) {\r\n    auto timer = CreateTimer(TimerSchedType::TIMER_QUAD_HEAP);\r\n    TestTimerExpire(timer.get(), N1);\r\n}\r\n\r\nTEST(TimerQuadHeap, TimerExpireFIFO) {\r\n    auto timer = CreateTimer(TimerSchedType::TIMER_QUAD_HEAP);\r\n    TestTimerExpireFIFO(timer.get());\r\n}\r\n\r\n\r\n/////////////////////////////////////////////////////////////////\r\n\r\nTEST(TimerRBTree, TimerAdd) {\r\n    auto timer = CreateTimer(TimerSchedType::TIMER_RBTREE);\r\n    TestTimerAdd(timer.get(), N1);\r\n}\r\n\r\nTEST(TimerRBTree, TimerDel) {\r\n    auto timer = CreateTimer(TimerSchedType::TIMER_RBTREE);\r\n    TestTimerDel(timer.get(), N1);\r\n}\r\n\r\n\r\nTEST(TimerRBTree, TimerExecute) {\r\n    auto timer = CreateTimer(TimerSchedType::TIMER_RBTREE);\r\n    TestTimerExpire(timer.get(), N1);\r\n}\r\n\r\nTEST(TimerRBTree, TimerExpireFIFO) {\r\n    auto timer = CreateTimer(TimerSchedType::TIMER_RBTREE);\r\n    TestTimerExpireFIFO(timer.get());\r\n}\r\n\r\n\r\n/////////////////////////////////////////////////////////////////\r\n\r\nTEST(TimerHashedWheel, TimerAdd) {\r\n    auto timer = CreateTimer(TimerSchedType::TIMER_HASHED_WHEEL);\r\n    TestTimerAdd(timer.get(), N1);\r\n}\r\n\r\nTEST(TimerHashedWheel, TimerDel) {\r\n    auto timer = CreateTimer(TimerSchedType::TIMER_HASHED_WHEEL);\r\n    TestTimerDel(timer.get(), N1);\r\n}\r\n\r\n\r\nTEST(TimerHashedWheel, TimerExecute) {\r\n    auto timer = CreateTimer(TimerSchedType::TIMER_HASHED_WHEEL);\r\n    TestTimerExpire(timer.get(), N1);\r\n}\r\n\r\nTEST(TimerHashedWheel, TimerExpireFIFO) {\r\n    auto timer = CreateTimer(TimerSchedType::TIMER_HASHED_WHEEL);\r\n    TestTimerExpireFIFO(timer.get());\r\n}\r\n\r\n\r\n///////////////////////////////////////////////////////////////////////\r\n\r\nTEST(TimerHHWheel, TimerAdd) {\r\n    auto timer = CreateTimer(TimerSchedType::TIMER_HH_WHEEL);\r\n    TestTimerAdd(timer.get(), N1);\r\n}\r\n\r\nTEST(TimerHHWheel, TimerDel) {\r\n    auto timer = CreateTimer(TimerSchedType::TIMER_HH_WHEEL);\r\n    TestTimerDel(timer.get(), N1);\r\n}\r\n\r\n\r\nTEST(TimerHHWheel, TimerExecute) {\r\n    auto timer = CreateTimer(TimerSchedType::TIMER_HH_WHEEL);\r\n    TestTimerExpire(timer.get(), N1);\r\n}\r\n\r\nTEST(TimerHHWheel, TimerExpireFIFO) {\r\n    auto timer = CreateTimer(TimerSchedType::TIMER_HH_WHEEL);\r\n    TestTimerExpireFIFO(timer.get());\r\n}\r\n"
  },
  {
    "path": "test/main.cpp",
    "content": "// Copyright © 2021 ichenq@gmail.com All rights reserved.\n// See accompanying files LICENSE\n\n#include <iostream>\n#include <time.h>\n#include <stdlib.h>\n#include <gtest/gtest.h>\n#include <benchmark/benchmark.h>\n\n\nint main(int argc, char* argv[])\n{\n    srand((int)time(NULL));\n\n    testing::InitGoogleTest(&argc, argv);\n\n    int r = RUN_ALL_TESTS();\n    if (r == 1) {\n        return 1;\n    }\n\n    printf(\"start run benchmarks\\n\");\n    benchmark::Initialize(&argc, argv);\n    if (benchmark::ReportUnrecognizedArguments(argc, argv)) {\n        return 1;\n    }\n    benchmark::RunSpecifiedBenchmarks();                              \n    benchmark::Shutdown();\n\n    return 0;\n}\n"
  }
]